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::{future, FutureExt};
72use fuzzy::{StringMatch, StringMatchCandidate};
73use git::blame::GitBlame;
74use gpui::{
75 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
76 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
77 ClipboardItem, Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle,
78 FocusOutEvent, FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText,
79 KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
80 SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
81 UTF16Selection, UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler,
82 VisualContext, WeakFocusHandle, WeakView, WindowContext,
83};
84use highlight_matching_bracket::refresh_matching_bracket_highlights;
85use hover_popover::{hide_hover, HoverState};
86pub(crate) use hunk_diff::HoveredHunk;
87use hunk_diff::{diff_hunk_to_display, ExpandedHunks};
88use indent_guides::ActiveIndentGuidesState;
89use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
90pub use inline_completion_provider::*;
91pub use items::MAX_TAB_TITLE_LEN;
92use itertools::Itertools;
93use language::{
94 language_settings::{self, all_language_settings, InlayHintSettings},
95 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
96 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
97 Point, Selection, SelectionGoal, TransactionId,
98};
99use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
100use linked_editing_ranges::refresh_linked_ranges;
101use proposed_changes_editor::{ProposedChangesBuffer, ProposedChangesEditor};
102use similar::{ChangeTag, TextDiff};
103use task::{ResolvedTask, TaskTemplate, TaskVariables};
104
105use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
106pub use lsp::CompletionContext;
107use lsp::{
108 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
109 LanguageServerId,
110};
111use mouse_context_menu::MouseContextMenu;
112use movement::TextLayoutDetails;
113pub use multi_buffer::{
114 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
115 ToPoint,
116};
117use multi_buffer::{
118 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
119};
120use ordered_float::OrderedFloat;
121use parking_lot::{Mutex, RwLock};
122use project::project_settings::{GitGutterSetting, ProjectSettings};
123use project::{
124 lsp_store::FormatTrigger, CodeAction, Completion, CompletionIntent, Item, Location, Project,
125 ProjectPath, ProjectTransaction, TaskSourceKind,
126};
127use rand::prelude::*;
128use rpc::{proto::*, ErrorExt};
129use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
130use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
131use serde::{Deserialize, Serialize};
132use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
133use smallvec::SmallVec;
134use snippet::Snippet;
135use std::{
136 any::TypeId,
137 borrow::Cow,
138 cell::RefCell,
139 cmp::{self, Ordering, Reverse},
140 mem,
141 num::NonZeroU32,
142 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
143 path::{Path, PathBuf},
144 rc::Rc,
145 sync::Arc,
146 time::{Duration, Instant},
147};
148pub use sum_tree::Bias;
149use sum_tree::TreeMap;
150use text::{BufferId, OffsetUtf16, Rope};
151use theme::{
152 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
153 ThemeColors, ThemeSettings,
154};
155use ui::{
156 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
157 ListItem, Popover, PopoverMenuHandle, Tooltip,
158};
159use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
160use workspace::item::{ItemHandle, PreviewTabsSettings};
161use workspace::notifications::{DetachAndPromptErr, NotificationId};
162use workspace::{
163 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
164};
165use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
166
167use crate::hover_links::find_url;
168use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
169
170pub const FILE_HEADER_HEIGHT: u32 = 1;
171pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
172pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
173pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
174const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
175const MAX_LINE_LEN: usize = 1024;
176const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
177const MAX_SELECTION_HISTORY_LEN: usize = 1024;
178pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
179#[doc(hidden)]
180pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
181#[doc(hidden)]
182pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
183
184pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
185pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
186
187pub fn render_parsed_markdown(
188 element_id: impl Into<ElementId>,
189 parsed: &language::ParsedMarkdown,
190 editor_style: &EditorStyle,
191 workspace: Option<WeakView<Workspace>>,
192 cx: &mut WindowContext,
193) -> InteractiveText {
194 let code_span_background_color = cx
195 .theme()
196 .colors()
197 .editor_document_highlight_read_background;
198
199 let highlights = gpui::combine_highlights(
200 parsed.highlights.iter().filter_map(|(range, highlight)| {
201 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
202 Some((range.clone(), highlight))
203 }),
204 parsed
205 .regions
206 .iter()
207 .zip(&parsed.region_ranges)
208 .filter_map(|(region, range)| {
209 if region.code {
210 Some((
211 range.clone(),
212 HighlightStyle {
213 background_color: Some(code_span_background_color),
214 ..Default::default()
215 },
216 ))
217 } else {
218 None
219 }
220 }),
221 );
222
223 let mut links = Vec::new();
224 let mut link_ranges = Vec::new();
225 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
226 if let Some(link) = region.link.clone() {
227 links.push(link);
228 link_ranges.push(range.clone());
229 }
230 }
231
232 InteractiveText::new(
233 element_id,
234 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
235 )
236 .on_click(link_ranges, move |clicked_range_ix, cx| {
237 match &links[clicked_range_ix] {
238 markdown::Link::Web { url } => cx.open_url(url),
239 markdown::Link::Path { path } => {
240 if let Some(workspace) = &workspace {
241 _ = workspace.update(cx, |workspace, cx| {
242 workspace.open_abs_path(path.clone(), false, cx).detach();
243 });
244 }
245 }
246 }
247 })
248}
249
250#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
251pub(crate) enum InlayId {
252 Suggestion(usize),
253 Hint(usize),
254}
255
256impl InlayId {
257 fn id(&self) -> usize {
258 match self {
259 Self::Suggestion(id) => *id,
260 Self::Hint(id) => *id,
261 }
262 }
263}
264
265enum DiffRowHighlight {}
266enum DocumentHighlightRead {}
267enum DocumentHighlightWrite {}
268enum InputComposition {}
269
270#[derive(Copy, Clone, PartialEq, Eq)]
271pub enum Direction {
272 Prev,
273 Next,
274}
275
276#[derive(Debug, Copy, Clone, PartialEq, Eq)]
277pub enum Navigated {
278 Yes,
279 No,
280}
281
282impl Navigated {
283 pub fn from_bool(yes: bool) -> Navigated {
284 if yes {
285 Navigated::Yes
286 } else {
287 Navigated::No
288 }
289 }
290}
291
292pub fn init_settings(cx: &mut AppContext) {
293 EditorSettings::register(cx);
294}
295
296pub fn init(cx: &mut AppContext) {
297 init_settings(cx);
298
299 workspace::register_project_item::<Editor>(cx);
300 workspace::FollowableViewRegistry::register::<Editor>(cx);
301 workspace::register_serializable_item::<Editor>(cx);
302
303 cx.observe_new_views(
304 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
305 workspace.register_action(Editor::new_file);
306 workspace.register_action(Editor::new_file_vertical);
307 workspace.register_action(Editor::new_file_horizontal);
308 },
309 )
310 .detach();
311
312 cx.on_action(move |_: &workspace::NewFile, cx| {
313 let app_state = workspace::AppState::global(cx);
314 if let Some(app_state) = app_state.upgrade() {
315 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
316 Editor::new_file(workspace, &Default::default(), cx)
317 })
318 .detach();
319 }
320 });
321 cx.on_action(move |_: &workspace::NewWindow, cx| {
322 let app_state = workspace::AppState::global(cx);
323 if let Some(app_state) = app_state.upgrade() {
324 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
325 Editor::new_file(workspace, &Default::default(), cx)
326 })
327 .detach();
328 }
329 });
330}
331
332pub struct SearchWithinRange;
333
334trait InvalidationRegion {
335 fn ranges(&self) -> &[Range<Anchor>];
336}
337
338#[derive(Clone, Debug, PartialEq)]
339pub enum SelectPhase {
340 Begin {
341 position: DisplayPoint,
342 add: bool,
343 click_count: usize,
344 },
345 BeginColumnar {
346 position: DisplayPoint,
347 reset: bool,
348 goal_column: u32,
349 },
350 Extend {
351 position: DisplayPoint,
352 click_count: usize,
353 },
354 Update {
355 position: DisplayPoint,
356 goal_column: u32,
357 scroll_delta: gpui::Point<f32>,
358 },
359 End,
360}
361
362#[derive(Clone, Debug)]
363pub enum SelectMode {
364 Character,
365 Word(Range<Anchor>),
366 Line(Range<Anchor>),
367 All,
368}
369
370#[derive(Copy, Clone, PartialEq, Eq, Debug)]
371pub enum EditorMode {
372 SingleLine { auto_width: bool },
373 AutoHeight { max_lines: usize },
374 Full,
375}
376
377#[derive(Clone, Debug)]
378pub enum SoftWrap {
379 None,
380 PreferLine,
381 EditorWidth,
382 Column(u32),
383 Bounded(u32),
384}
385
386#[derive(Clone)]
387pub struct EditorStyle {
388 pub background: Hsla,
389 pub local_player: PlayerColor,
390 pub text: TextStyle,
391 pub scrollbar_width: Pixels,
392 pub syntax: Arc<SyntaxTheme>,
393 pub status: StatusColors,
394 pub inlay_hints_style: HighlightStyle,
395 pub suggestions_style: HighlightStyle,
396 pub unnecessary_code_fade: f32,
397}
398
399impl Default for EditorStyle {
400 fn default() -> Self {
401 Self {
402 background: Hsla::default(),
403 local_player: PlayerColor::default(),
404 text: TextStyle::default(),
405 scrollbar_width: Pixels::default(),
406 syntax: Default::default(),
407 // HACK: Status colors don't have a real default.
408 // We should look into removing the status colors from the editor
409 // style and retrieve them directly from the theme.
410 status: StatusColors::dark(),
411 inlay_hints_style: HighlightStyle::default(),
412 suggestions_style: HighlightStyle::default(),
413 unnecessary_code_fade: Default::default(),
414 }
415 }
416}
417
418pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
419 let show_background = all_language_settings(None, cx)
420 .language(None)
421 .inlay_hints
422 .show_background;
423
424 HighlightStyle {
425 color: Some(cx.theme().status().hint),
426 background_color: show_background.then(|| cx.theme().status().hint_background),
427 ..HighlightStyle::default()
428 }
429}
430
431type CompletionId = usize;
432
433#[derive(Clone, Debug)]
434struct CompletionState {
435 // render_inlay_ids represents the inlay hints that are inserted
436 // for rendering the inline completions. They may be discontinuous
437 // in the event that the completion provider returns some intersection
438 // with the existing content.
439 render_inlay_ids: Vec<InlayId>,
440 // text is the resulting rope that is inserted when the user accepts a completion.
441 text: Rope,
442 // position is the position of the cursor when the completion was triggered.
443 position: multi_buffer::Anchor,
444 // delete_range is the range of text that this completion state covers.
445 // if the completion is accepted, this range should be deleted.
446 delete_range: Option<Range<multi_buffer::Anchor>>,
447}
448
449#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
450struct EditorActionId(usize);
451
452impl EditorActionId {
453 pub fn post_inc(&mut self) -> Self {
454 let answer = self.0;
455
456 *self = Self(answer + 1);
457
458 Self(answer)
459 }
460}
461
462// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
463// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
464
465type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
466type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
467
468#[derive(Default)]
469struct ScrollbarMarkerState {
470 scrollbar_size: Size<Pixels>,
471 dirty: bool,
472 markers: Arc<[PaintQuad]>,
473 pending_refresh: Option<Task<Result<()>>>,
474}
475
476impl ScrollbarMarkerState {
477 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
478 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
479 }
480}
481
482#[derive(Clone, Debug)]
483struct RunnableTasks {
484 templates: Vec<(TaskSourceKind, TaskTemplate)>,
485 offset: MultiBufferOffset,
486 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
487 column: u32,
488 // Values of all named captures, including those starting with '_'
489 extra_variables: HashMap<String, String>,
490 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
491 context_range: Range<BufferOffset>,
492}
493
494#[derive(Clone)]
495struct ResolvedTasks {
496 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
497 position: Anchor,
498}
499#[derive(Copy, Clone, Debug)]
500struct MultiBufferOffset(usize);
501#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
502struct BufferOffset(usize);
503
504// Addons allow storing per-editor state in other crates (e.g. Vim)
505pub trait Addon: 'static {
506 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
507
508 fn to_any(&self) -> &dyn std::any::Any;
509}
510
511/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
512///
513/// See the [module level documentation](self) for more information.
514pub struct Editor {
515 focus_handle: FocusHandle,
516 last_focused_descendant: Option<WeakFocusHandle>,
517 /// The text buffer being edited
518 buffer: Model<MultiBuffer>,
519 /// Map of how text in the buffer should be displayed.
520 /// Handles soft wraps, folds, fake inlay text insertions, etc.
521 pub display_map: Model<DisplayMap>,
522 pub selections: SelectionsCollection,
523 pub scroll_manager: ScrollManager,
524 /// When inline assist editors are linked, they all render cursors because
525 /// typing enters text into each of them, even the ones that aren't focused.
526 pub(crate) show_cursor_when_unfocused: bool,
527 columnar_selection_tail: Option<Anchor>,
528 add_selections_state: Option<AddSelectionsState>,
529 select_next_state: Option<SelectNextState>,
530 select_prev_state: Option<SelectNextState>,
531 selection_history: SelectionHistory,
532 autoclose_regions: Vec<AutocloseRegion>,
533 snippet_stack: InvalidationStack<SnippetState>,
534 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
535 ime_transaction: Option<TransactionId>,
536 active_diagnostics: Option<ActiveDiagnosticGroup>,
537 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
538 project: Option<Model<Project>>,
539 completion_provider: Option<Box<dyn CompletionProvider>>,
540 collaboration_hub: Option<Box<dyn CollaborationHub>>,
541 blink_manager: Model<BlinkManager>,
542 show_cursor_names: bool,
543 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
544 pub show_local_selections: bool,
545 mode: EditorMode,
546 show_breadcrumbs: bool,
547 show_gutter: bool,
548 show_line_numbers: Option<bool>,
549 use_relative_line_numbers: Option<bool>,
550 show_git_diff_gutter: Option<bool>,
551 show_code_actions: Option<bool>,
552 show_runnables: Option<bool>,
553 show_wrap_guides: Option<bool>,
554 show_indent_guides: Option<bool>,
555 placeholder_text: Option<Arc<str>>,
556 highlight_order: usize,
557 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
558 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
559 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
560 scrollbar_marker_state: ScrollbarMarkerState,
561 active_indent_guides_state: ActiveIndentGuidesState,
562 nav_history: Option<ItemNavHistory>,
563 context_menu: RwLock<Option<ContextMenu>>,
564 mouse_context_menu: Option<MouseContextMenu>,
565 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
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<[AvailableCodeAction]>)>,
573 code_actions_task: Option<Task<Result<()>>>,
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 code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
594 active_inline_completion: Option<CompletionState>,
595 // enable_inline_completions is a switch that Vim can use to disable
596 // inline completions based on its mode.
597 enable_inline_completions: bool,
598 show_inline_completions_override: Option<bool>,
599 inlay_hint_cache: InlayHintCache,
600 expanded_hunks: ExpandedHunks,
601 next_inlay_id: usize,
602 _subscriptions: Vec<Subscription>,
603 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
604 gutter_dimensions: GutterDimensions,
605 style: Option<EditorStyle>,
606 next_editor_action_id: EditorActionId,
607 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
608 use_autoclose: bool,
609 use_auto_surround: bool,
610 auto_replace_emoji_shortcode: bool,
611 show_git_blame_gutter: bool,
612 show_git_blame_inline: bool,
613 show_git_blame_inline_delay_task: Option<Task<()>>,
614 git_blame_inline_enabled: bool,
615 serialize_dirty_buffers: bool,
616 show_selection_menu: Option<bool>,
617 blame: Option<Model<GitBlame>>,
618 blame_subscription: Option<Subscription>,
619 custom_context_menu: Option<
620 Box<
621 dyn 'static
622 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
623 >,
624 >,
625 last_bounds: Option<Bounds<Pixels>>,
626 expect_bounds_change: Option<Bounds<Pixels>>,
627 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
628 tasks_update_task: Option<Task<()>>,
629 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
630 file_header_size: u32,
631 breadcrumb_header: Option<String>,
632 focused_block: Option<FocusedBlock>,
633 next_scroll_position: NextScrollCursorCenterTopBottom,
634 addons: HashMap<TypeId, Box<dyn Addon>>,
635 _scroll_cursor_center_top_bottom_task: Task<()>,
636}
637
638#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
639enum NextScrollCursorCenterTopBottom {
640 #[default]
641 Center,
642 Top,
643 Bottom,
644}
645
646impl NextScrollCursorCenterTopBottom {
647 fn next(&self) -> Self {
648 match self {
649 Self::Center => Self::Top,
650 Self::Top => Self::Bottom,
651 Self::Bottom => Self::Center,
652 }
653 }
654}
655
656#[derive(Clone)]
657pub struct EditorSnapshot {
658 pub mode: EditorMode,
659 show_gutter: bool,
660 show_line_numbers: Option<bool>,
661 show_git_diff_gutter: Option<bool>,
662 show_code_actions: Option<bool>,
663 show_runnables: Option<bool>,
664 render_git_blame_gutter: bool,
665 pub display_snapshot: DisplaySnapshot,
666 pub placeholder_text: Option<Arc<str>>,
667 is_focused: bool,
668 scroll_anchor: ScrollAnchor,
669 ongoing_scroll: OngoingScroll,
670 current_line_highlight: CurrentLineHighlight,
671 gutter_hovered: bool,
672}
673
674const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
675
676#[derive(Default, Debug, Clone, Copy)]
677pub struct GutterDimensions {
678 pub left_padding: Pixels,
679 pub right_padding: Pixels,
680 pub width: Pixels,
681 pub margin: Pixels,
682 pub git_blame_entries_width: Option<Pixels>,
683}
684
685impl GutterDimensions {
686 /// The full width of the space taken up by the gutter.
687 pub fn full_width(&self) -> Pixels {
688 self.margin + self.width
689 }
690
691 /// The width of the space reserved for the fold indicators,
692 /// use alongside 'justify_end' and `gutter_width` to
693 /// right align content with the line numbers
694 pub fn fold_area_width(&self) -> Pixels {
695 self.margin + self.right_padding
696 }
697}
698
699#[derive(Debug)]
700pub struct RemoteSelection {
701 pub replica_id: ReplicaId,
702 pub selection: Selection<Anchor>,
703 pub cursor_shape: CursorShape,
704 pub peer_id: PeerId,
705 pub line_mode: bool,
706 pub participant_index: Option<ParticipantIndex>,
707 pub user_name: Option<SharedString>,
708}
709
710#[derive(Clone, Debug)]
711struct SelectionHistoryEntry {
712 selections: Arc<[Selection<Anchor>]>,
713 select_next_state: Option<SelectNextState>,
714 select_prev_state: Option<SelectNextState>,
715 add_selections_state: Option<AddSelectionsState>,
716}
717
718enum SelectionHistoryMode {
719 Normal,
720 Undoing,
721 Redoing,
722}
723
724#[derive(Clone, PartialEq, Eq, Hash)]
725struct HoveredCursor {
726 replica_id: u16,
727 selection_id: usize,
728}
729
730impl Default for SelectionHistoryMode {
731 fn default() -> Self {
732 Self::Normal
733 }
734}
735
736#[derive(Default)]
737struct SelectionHistory {
738 #[allow(clippy::type_complexity)]
739 selections_by_transaction:
740 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
741 mode: SelectionHistoryMode,
742 undo_stack: VecDeque<SelectionHistoryEntry>,
743 redo_stack: VecDeque<SelectionHistoryEntry>,
744}
745
746impl SelectionHistory {
747 fn insert_transaction(
748 &mut self,
749 transaction_id: TransactionId,
750 selections: Arc<[Selection<Anchor>]>,
751 ) {
752 self.selections_by_transaction
753 .insert(transaction_id, (selections, None));
754 }
755
756 #[allow(clippy::type_complexity)]
757 fn transaction(
758 &self,
759 transaction_id: TransactionId,
760 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
761 self.selections_by_transaction.get(&transaction_id)
762 }
763
764 #[allow(clippy::type_complexity)]
765 fn transaction_mut(
766 &mut self,
767 transaction_id: TransactionId,
768 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
769 self.selections_by_transaction.get_mut(&transaction_id)
770 }
771
772 fn push(&mut self, entry: SelectionHistoryEntry) {
773 if !entry.selections.is_empty() {
774 match self.mode {
775 SelectionHistoryMode::Normal => {
776 self.push_undo(entry);
777 self.redo_stack.clear();
778 }
779 SelectionHistoryMode::Undoing => self.push_redo(entry),
780 SelectionHistoryMode::Redoing => self.push_undo(entry),
781 }
782 }
783 }
784
785 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
786 if self
787 .undo_stack
788 .back()
789 .map_or(true, |e| e.selections != entry.selections)
790 {
791 self.undo_stack.push_back(entry);
792 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
793 self.undo_stack.pop_front();
794 }
795 }
796 }
797
798 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
799 if self
800 .redo_stack
801 .back()
802 .map_or(true, |e| e.selections != entry.selections)
803 {
804 self.redo_stack.push_back(entry);
805 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
806 self.redo_stack.pop_front();
807 }
808 }
809 }
810}
811
812struct RowHighlight {
813 index: usize,
814 range: RangeInclusive<Anchor>,
815 color: Option<Hsla>,
816 should_autoscroll: bool,
817}
818
819#[derive(Clone, Debug)]
820struct AddSelectionsState {
821 above: bool,
822 stack: Vec<usize>,
823}
824
825#[derive(Clone)]
826struct SelectNextState {
827 query: AhoCorasick,
828 wordwise: bool,
829 done: bool,
830}
831
832impl std::fmt::Debug for SelectNextState {
833 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
834 f.debug_struct(std::any::type_name::<Self>())
835 .field("wordwise", &self.wordwise)
836 .field("done", &self.done)
837 .finish()
838 }
839}
840
841#[derive(Debug)]
842struct AutocloseRegion {
843 selection_id: usize,
844 range: Range<Anchor>,
845 pair: BracketPair,
846}
847
848#[derive(Debug)]
849struct SnippetState {
850 ranges: Vec<Vec<Range<Anchor>>>,
851 active_index: usize,
852}
853
854#[doc(hidden)]
855pub struct RenameState {
856 pub range: Range<Anchor>,
857 pub old_name: Arc<str>,
858 pub editor: View<Editor>,
859 block_id: CustomBlockId,
860}
861
862struct InvalidationStack<T>(Vec<T>);
863
864struct RegisteredInlineCompletionProvider {
865 provider: Arc<dyn InlineCompletionProviderHandle>,
866 _subscription: Subscription,
867}
868
869enum ContextMenu {
870 Completions(CompletionsMenu),
871 CodeActions(CodeActionsMenu),
872}
873
874impl ContextMenu {
875 fn select_first(
876 &mut self,
877 project: Option<&Model<Project>>,
878 cx: &mut ViewContext<Editor>,
879 ) -> bool {
880 if self.visible() {
881 match self {
882 ContextMenu::Completions(menu) => menu.select_first(project, cx),
883 ContextMenu::CodeActions(menu) => menu.select_first(cx),
884 }
885 true
886 } else {
887 false
888 }
889 }
890
891 fn select_prev(
892 &mut self,
893 project: Option<&Model<Project>>,
894 cx: &mut ViewContext<Editor>,
895 ) -> bool {
896 if self.visible() {
897 match self {
898 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
899 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
900 }
901 true
902 } else {
903 false
904 }
905 }
906
907 fn select_next(
908 &mut self,
909 project: Option<&Model<Project>>,
910 cx: &mut ViewContext<Editor>,
911 ) -> bool {
912 if self.visible() {
913 match self {
914 ContextMenu::Completions(menu) => menu.select_next(project, cx),
915 ContextMenu::CodeActions(menu) => menu.select_next(cx),
916 }
917 true
918 } else {
919 false
920 }
921 }
922
923 fn select_last(
924 &mut self,
925 project: Option<&Model<Project>>,
926 cx: &mut ViewContext<Editor>,
927 ) -> bool {
928 if self.visible() {
929 match self {
930 ContextMenu::Completions(menu) => menu.select_last(project, cx),
931 ContextMenu::CodeActions(menu) => menu.select_last(cx),
932 }
933 true
934 } else {
935 false
936 }
937 }
938
939 fn visible(&self) -> bool {
940 match self {
941 ContextMenu::Completions(menu) => menu.visible(),
942 ContextMenu::CodeActions(menu) => menu.visible(),
943 }
944 }
945
946 fn render(
947 &self,
948 cursor_position: DisplayPoint,
949 style: &EditorStyle,
950 max_height: Pixels,
951 workspace: Option<WeakView<Workspace>>,
952 cx: &mut ViewContext<Editor>,
953 ) -> (ContextMenuOrigin, AnyElement) {
954 match self {
955 ContextMenu::Completions(menu) => (
956 ContextMenuOrigin::EditorPoint(cursor_position),
957 menu.render(style, max_height, workspace, cx),
958 ),
959 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
960 }
961 }
962}
963
964enum ContextMenuOrigin {
965 EditorPoint(DisplayPoint),
966 GutterIndicator(DisplayRow),
967}
968
969#[derive(Clone)]
970struct CompletionsMenu {
971 id: CompletionId,
972 sort_completions: bool,
973 initial_position: Anchor,
974 buffer: Model<Buffer>,
975 completions: Arc<RwLock<Box<[Completion]>>>,
976 match_candidates: Arc<[StringMatchCandidate]>,
977 matches: Arc<[StringMatch]>,
978 selected_item: usize,
979 scroll_handle: UniformListScrollHandle,
980 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
981}
982
983impl CompletionsMenu {
984 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
985 self.selected_item = 0;
986 self.scroll_handle.scroll_to_item(self.selected_item);
987 self.attempt_resolve_selected_completion_documentation(project, cx);
988 cx.notify();
989 }
990
991 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
992 if self.selected_item > 0 {
993 self.selected_item -= 1;
994 } else {
995 self.selected_item = self.matches.len() - 1;
996 }
997 self.scroll_handle.scroll_to_item(self.selected_item);
998 self.attempt_resolve_selected_completion_documentation(project, cx);
999 cx.notify();
1000 }
1001
1002 fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
1003 if self.selected_item + 1 < self.matches.len() {
1004 self.selected_item += 1;
1005 } else {
1006 self.selected_item = 0;
1007 }
1008 self.scroll_handle.scroll_to_item(self.selected_item);
1009 self.attempt_resolve_selected_completion_documentation(project, cx);
1010 cx.notify();
1011 }
1012
1013 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
1014 self.selected_item = self.matches.len() - 1;
1015 self.scroll_handle.scroll_to_item(self.selected_item);
1016 self.attempt_resolve_selected_completion_documentation(project, cx);
1017 cx.notify();
1018 }
1019
1020 fn pre_resolve_completion_documentation(
1021 buffer: Model<Buffer>,
1022 completions: Arc<RwLock<Box<[Completion]>>>,
1023 matches: Arc<[StringMatch]>,
1024 editor: &Editor,
1025 cx: &mut ViewContext<Editor>,
1026 ) -> Task<()> {
1027 let settings = EditorSettings::get_global(cx);
1028 if !settings.show_completion_documentation {
1029 return Task::ready(());
1030 }
1031
1032 let Some(provider) = editor.completion_provider.as_ref() else {
1033 return Task::ready(());
1034 };
1035
1036 let resolve_task = provider.resolve_completions(
1037 buffer,
1038 matches.iter().map(|m| m.candidate_id).collect(),
1039 completions.clone(),
1040 cx,
1041 );
1042
1043 cx.spawn(move |this, mut cx| async move {
1044 if let Some(true) = resolve_task.await.log_err() {
1045 this.update(&mut cx, |_, cx| cx.notify()).ok();
1046 }
1047 })
1048 }
1049
1050 fn attempt_resolve_selected_completion_documentation(
1051 &mut self,
1052 project: Option<&Model<Project>>,
1053 cx: &mut ViewContext<Editor>,
1054 ) {
1055 let settings = EditorSettings::get_global(cx);
1056 if !settings.show_completion_documentation {
1057 return;
1058 }
1059
1060 let completion_index = self.matches[self.selected_item].candidate_id;
1061 let Some(project) = project else {
1062 return;
1063 };
1064
1065 let resolve_task = project.update(cx, |project, cx| {
1066 project.resolve_completions(
1067 self.buffer.clone(),
1068 vec![completion_index],
1069 self.completions.clone(),
1070 cx,
1071 )
1072 });
1073
1074 let delay_ms =
1075 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1076 let delay = Duration::from_millis(delay_ms);
1077
1078 self.selected_completion_documentation_resolve_debounce
1079 .lock()
1080 .fire_new(delay, cx, |_, cx| {
1081 cx.spawn(move |this, mut cx| async move {
1082 if let Some(true) = resolve_task.await.log_err() {
1083 this.update(&mut cx, |_, cx| cx.notify()).ok();
1084 }
1085 })
1086 });
1087 }
1088
1089 fn visible(&self) -> bool {
1090 !self.matches.is_empty()
1091 }
1092
1093 fn render(
1094 &self,
1095 style: &EditorStyle,
1096 max_height: Pixels,
1097 workspace: Option<WeakView<Workspace>>,
1098 cx: &mut ViewContext<Editor>,
1099 ) -> AnyElement {
1100 let settings = EditorSettings::get_global(cx);
1101 let show_completion_documentation = settings.show_completion_documentation;
1102
1103 let widest_completion_ix = self
1104 .matches
1105 .iter()
1106 .enumerate()
1107 .max_by_key(|(_, mat)| {
1108 let completions = self.completions.read();
1109 let completion = &completions[mat.candidate_id];
1110 let documentation = &completion.documentation;
1111
1112 let mut len = completion.label.text.chars().count();
1113 if let Some(Documentation::SingleLine(text)) = documentation {
1114 if show_completion_documentation {
1115 len += text.chars().count();
1116 }
1117 }
1118
1119 len
1120 })
1121 .map(|(ix, _)| ix);
1122
1123 let completions = self.completions.clone();
1124 let matches = self.matches.clone();
1125 let selected_item = self.selected_item;
1126 let style = style.clone();
1127
1128 let multiline_docs = if show_completion_documentation {
1129 let mat = &self.matches[selected_item];
1130 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1131 Some(Documentation::MultiLinePlainText(text)) => {
1132 Some(div().child(SharedString::from(text.clone())))
1133 }
1134 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1135 Some(div().child(render_parsed_markdown(
1136 "completions_markdown",
1137 parsed,
1138 &style,
1139 workspace,
1140 cx,
1141 )))
1142 }
1143 _ => None,
1144 };
1145 multiline_docs.map(|div| {
1146 div.id("multiline_docs")
1147 .max_h(max_height)
1148 .flex_1()
1149 .px_1p5()
1150 .py_1()
1151 .min_w(px(260.))
1152 .max_w(px(640.))
1153 .w(px(500.))
1154 .overflow_y_scroll()
1155 .occlude()
1156 })
1157 } else {
1158 None
1159 };
1160
1161 let list = uniform_list(
1162 cx.view().clone(),
1163 "completions",
1164 matches.len(),
1165 move |_editor, range, cx| {
1166 let start_ix = range.start;
1167 let completions_guard = completions.read();
1168
1169 matches[range]
1170 .iter()
1171 .enumerate()
1172 .map(|(ix, mat)| {
1173 let item_ix = start_ix + ix;
1174 let candidate_id = mat.candidate_id;
1175 let completion = &completions_guard[candidate_id];
1176
1177 let documentation = if show_completion_documentation {
1178 &completion.documentation
1179 } else {
1180 &None
1181 };
1182
1183 let highlights = gpui::combine_highlights(
1184 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1185 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1186 |(range, mut highlight)| {
1187 // Ignore font weight for syntax highlighting, as we'll use it
1188 // for fuzzy matches.
1189 highlight.font_weight = None;
1190
1191 if completion.lsp_completion.deprecated.unwrap_or(false) {
1192 highlight.strikethrough = Some(StrikethroughStyle {
1193 thickness: 1.0.into(),
1194 ..Default::default()
1195 });
1196 highlight.color = Some(cx.theme().colors().text_muted);
1197 }
1198
1199 (range, highlight)
1200 },
1201 ),
1202 );
1203 let completion_label = StyledText::new(completion.label.text.clone())
1204 .with_highlights(&style.text, highlights);
1205 let documentation_label =
1206 if let Some(Documentation::SingleLine(text)) = documentation {
1207 if text.trim().is_empty() {
1208 None
1209 } else {
1210 Some(
1211 Label::new(text.clone())
1212 .ml_4()
1213 .size(LabelSize::Small)
1214 .color(Color::Muted),
1215 )
1216 }
1217 } else {
1218 None
1219 };
1220
1221 div().min_w(px(220.)).max_w(px(540.)).child(
1222 ListItem::new(mat.candidate_id)
1223 .inset(true)
1224 .selected(item_ix == selected_item)
1225 .on_click(cx.listener(move |editor, _event, cx| {
1226 cx.stop_propagation();
1227 if let Some(task) = editor.confirm_completion(
1228 &ConfirmCompletion {
1229 item_ix: Some(item_ix),
1230 },
1231 cx,
1232 ) {
1233 task.detach_and_log_err(cx)
1234 }
1235 }))
1236 .child(h_flex().overflow_hidden().child(completion_label))
1237 .end_slot::<Label>(documentation_label),
1238 )
1239 })
1240 .collect()
1241 },
1242 )
1243 .occlude()
1244 .max_h(max_height)
1245 .track_scroll(self.scroll_handle.clone())
1246 .with_width_from_item(widest_completion_ix)
1247 .with_sizing_behavior(ListSizingBehavior::Infer);
1248
1249 Popover::new()
1250 .child(list)
1251 .when_some(multiline_docs, |popover, multiline_docs| {
1252 popover.aside(multiline_docs)
1253 })
1254 .into_any_element()
1255 }
1256
1257 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1258 let mut matches = if let Some(query) = query {
1259 fuzzy::match_strings(
1260 &self.match_candidates,
1261 query,
1262 query.chars().any(|c| c.is_uppercase()),
1263 100,
1264 &Default::default(),
1265 executor,
1266 )
1267 .await
1268 } else {
1269 self.match_candidates
1270 .iter()
1271 .enumerate()
1272 .map(|(candidate_id, candidate)| StringMatch {
1273 candidate_id,
1274 score: Default::default(),
1275 positions: Default::default(),
1276 string: candidate.string.clone(),
1277 })
1278 .collect()
1279 };
1280
1281 // Remove all candidates where the query's start does not match the start of any word in the candidate
1282 if let Some(query) = query {
1283 if let Some(query_start) = query.chars().next() {
1284 matches.retain(|string_match| {
1285 split_words(&string_match.string).any(|word| {
1286 // Check that the first codepoint of the word as lowercase matches the first
1287 // codepoint of the query as lowercase
1288 word.chars()
1289 .flat_map(|codepoint| codepoint.to_lowercase())
1290 .zip(query_start.to_lowercase())
1291 .all(|(word_cp, query_cp)| word_cp == query_cp)
1292 })
1293 });
1294 }
1295 }
1296
1297 let completions = self.completions.read();
1298 if self.sort_completions {
1299 matches.sort_unstable_by_key(|mat| {
1300 // We do want to strike a balance here between what the language server tells us
1301 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1302 // `Creat` and there is a local variable called `CreateComponent`).
1303 // So what we do is: we bucket all matches into two buckets
1304 // - Strong matches
1305 // - Weak matches
1306 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1307 // and the Weak matches are the rest.
1308 //
1309 // For the strong matches, we sort by the language-servers score first and for the weak
1310 // matches, we prefer our fuzzy finder first.
1311 //
1312 // The thinking behind that: it's useless to take the sort_text the language-server gives
1313 // us into account when it's obviously a bad match.
1314
1315 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1316 enum MatchScore<'a> {
1317 Strong {
1318 sort_text: Option<&'a str>,
1319 score: Reverse<OrderedFloat<f64>>,
1320 sort_key: (usize, &'a str),
1321 },
1322 Weak {
1323 score: Reverse<OrderedFloat<f64>>,
1324 sort_text: Option<&'a str>,
1325 sort_key: (usize, &'a str),
1326 },
1327 }
1328
1329 let completion = &completions[mat.candidate_id];
1330 let sort_key = completion.sort_key();
1331 let sort_text = completion.lsp_completion.sort_text.as_deref();
1332 let score = Reverse(OrderedFloat(mat.score));
1333
1334 if mat.score >= 0.2 {
1335 MatchScore::Strong {
1336 sort_text,
1337 score,
1338 sort_key,
1339 }
1340 } else {
1341 MatchScore::Weak {
1342 score,
1343 sort_text,
1344 sort_key,
1345 }
1346 }
1347 });
1348 }
1349
1350 for mat in &mut matches {
1351 let completion = &completions[mat.candidate_id];
1352 mat.string.clone_from(&completion.label.text);
1353 for position in &mut mat.positions {
1354 *position += completion.label.filter_range.start;
1355 }
1356 }
1357 drop(completions);
1358
1359 self.matches = matches.into();
1360 self.selected_item = 0;
1361 }
1362}
1363
1364struct AvailableCodeAction {
1365 excerpt_id: ExcerptId,
1366 action: CodeAction,
1367 provider: Arc<dyn CodeActionProvider>,
1368}
1369
1370#[derive(Clone)]
1371struct CodeActionContents {
1372 tasks: Option<Arc<ResolvedTasks>>,
1373 actions: Option<Arc<[AvailableCodeAction]>>,
1374}
1375
1376impl CodeActionContents {
1377 fn len(&self) -> usize {
1378 match (&self.tasks, &self.actions) {
1379 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1380 (Some(tasks), None) => tasks.templates.len(),
1381 (None, Some(actions)) => actions.len(),
1382 (None, None) => 0,
1383 }
1384 }
1385
1386 fn is_empty(&self) -> bool {
1387 match (&self.tasks, &self.actions) {
1388 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1389 (Some(tasks), None) => tasks.templates.is_empty(),
1390 (None, Some(actions)) => actions.is_empty(),
1391 (None, None) => true,
1392 }
1393 }
1394
1395 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1396 self.tasks
1397 .iter()
1398 .flat_map(|tasks| {
1399 tasks
1400 .templates
1401 .iter()
1402 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1403 })
1404 .chain(self.actions.iter().flat_map(|actions| {
1405 actions.iter().map(|available| CodeActionsItem::CodeAction {
1406 excerpt_id: available.excerpt_id,
1407 action: available.action.clone(),
1408 provider: available.provider.clone(),
1409 })
1410 }))
1411 }
1412 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1413 match (&self.tasks, &self.actions) {
1414 (Some(tasks), Some(actions)) => {
1415 if index < tasks.templates.len() {
1416 tasks
1417 .templates
1418 .get(index)
1419 .cloned()
1420 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1421 } else {
1422 actions.get(index - tasks.templates.len()).map(|available| {
1423 CodeActionsItem::CodeAction {
1424 excerpt_id: available.excerpt_id,
1425 action: available.action.clone(),
1426 provider: available.provider.clone(),
1427 }
1428 })
1429 }
1430 }
1431 (Some(tasks), None) => tasks
1432 .templates
1433 .get(index)
1434 .cloned()
1435 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1436 (None, Some(actions)) => {
1437 actions
1438 .get(index)
1439 .map(|available| CodeActionsItem::CodeAction {
1440 excerpt_id: available.excerpt_id,
1441 action: available.action.clone(),
1442 provider: available.provider.clone(),
1443 })
1444 }
1445 (None, None) => None,
1446 }
1447 }
1448}
1449
1450#[allow(clippy::large_enum_variant)]
1451#[derive(Clone)]
1452enum CodeActionsItem {
1453 Task(TaskSourceKind, ResolvedTask),
1454 CodeAction {
1455 excerpt_id: ExcerptId,
1456 action: CodeAction,
1457 provider: Arc<dyn CodeActionProvider>,
1458 },
1459}
1460
1461impl CodeActionsItem {
1462 fn as_task(&self) -> Option<&ResolvedTask> {
1463 let Self::Task(_, task) = self else {
1464 return None;
1465 };
1466 Some(task)
1467 }
1468 fn as_code_action(&self) -> Option<&CodeAction> {
1469 let Self::CodeAction { action, .. } = self else {
1470 return None;
1471 };
1472 Some(action)
1473 }
1474 fn label(&self) -> String {
1475 match self {
1476 Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
1477 Self::Task(_, task) => task.resolved_label.clone(),
1478 }
1479 }
1480}
1481
1482struct CodeActionsMenu {
1483 actions: CodeActionContents,
1484 buffer: Model<Buffer>,
1485 selected_item: usize,
1486 scroll_handle: UniformListScrollHandle,
1487 deployed_from_indicator: Option<DisplayRow>,
1488}
1489
1490impl CodeActionsMenu {
1491 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1492 self.selected_item = 0;
1493 self.scroll_handle.scroll_to_item(self.selected_item);
1494 cx.notify()
1495 }
1496
1497 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1498 if self.selected_item > 0 {
1499 self.selected_item -= 1;
1500 } else {
1501 self.selected_item = self.actions.len() - 1;
1502 }
1503 self.scroll_handle.scroll_to_item(self.selected_item);
1504 cx.notify();
1505 }
1506
1507 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1508 if self.selected_item + 1 < self.actions.len() {
1509 self.selected_item += 1;
1510 } else {
1511 self.selected_item = 0;
1512 }
1513 self.scroll_handle.scroll_to_item(self.selected_item);
1514 cx.notify();
1515 }
1516
1517 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1518 self.selected_item = self.actions.len() - 1;
1519 self.scroll_handle.scroll_to_item(self.selected_item);
1520 cx.notify()
1521 }
1522
1523 fn visible(&self) -> bool {
1524 !self.actions.is_empty()
1525 }
1526
1527 fn render(
1528 &self,
1529 cursor_position: DisplayPoint,
1530 _style: &EditorStyle,
1531 max_height: Pixels,
1532 cx: &mut ViewContext<Editor>,
1533 ) -> (ContextMenuOrigin, AnyElement) {
1534 let actions = self.actions.clone();
1535 let selected_item = self.selected_item;
1536 let element = uniform_list(
1537 cx.view().clone(),
1538 "code_actions_menu",
1539 self.actions.len(),
1540 move |_this, range, cx| {
1541 actions
1542 .iter()
1543 .skip(range.start)
1544 .take(range.end - range.start)
1545 .enumerate()
1546 .map(|(ix, action)| {
1547 let item_ix = range.start + ix;
1548 let selected = selected_item == item_ix;
1549 let colors = cx.theme().colors();
1550 div()
1551 .px_1()
1552 .rounded_md()
1553 .text_color(colors.text)
1554 .when(selected, |style| {
1555 style
1556 .bg(colors.element_active)
1557 .text_color(colors.text_accent)
1558 })
1559 .hover(|style| {
1560 style
1561 .bg(colors.element_hover)
1562 .text_color(colors.text_accent)
1563 })
1564 .whitespace_nowrap()
1565 .when_some(action.as_code_action(), |this, action| {
1566 this.on_mouse_down(
1567 MouseButton::Left,
1568 cx.listener(move |editor, _, cx| {
1569 cx.stop_propagation();
1570 if let Some(task) = editor.confirm_code_action(
1571 &ConfirmCodeAction {
1572 item_ix: Some(item_ix),
1573 },
1574 cx,
1575 ) {
1576 task.detach_and_log_err(cx)
1577 }
1578 }),
1579 )
1580 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1581 .child(SharedString::from(action.lsp_action.title.clone()))
1582 })
1583 .when_some(action.as_task(), |this, task| {
1584 this.on_mouse_down(
1585 MouseButton::Left,
1586 cx.listener(move |editor, _, cx| {
1587 cx.stop_propagation();
1588 if let Some(task) = editor.confirm_code_action(
1589 &ConfirmCodeAction {
1590 item_ix: Some(item_ix),
1591 },
1592 cx,
1593 ) {
1594 task.detach_and_log_err(cx)
1595 }
1596 }),
1597 )
1598 .child(SharedString::from(task.resolved_label.clone()))
1599 })
1600 })
1601 .collect()
1602 },
1603 )
1604 .elevation_1(cx)
1605 .p_1()
1606 .max_h(max_height)
1607 .occlude()
1608 .track_scroll(self.scroll_handle.clone())
1609 .with_width_from_item(
1610 self.actions
1611 .iter()
1612 .enumerate()
1613 .max_by_key(|(_, action)| match action {
1614 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1615 CodeActionsItem::CodeAction { action, .. } => {
1616 action.lsp_action.title.chars().count()
1617 }
1618 })
1619 .map(|(ix, _)| ix),
1620 )
1621 .with_sizing_behavior(ListSizingBehavior::Infer)
1622 .into_any_element();
1623
1624 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1625 ContextMenuOrigin::GutterIndicator(row)
1626 } else {
1627 ContextMenuOrigin::EditorPoint(cursor_position)
1628 };
1629
1630 (cursor_position, element)
1631 }
1632}
1633
1634#[derive(Debug)]
1635struct ActiveDiagnosticGroup {
1636 primary_range: Range<Anchor>,
1637 primary_message: String,
1638 group_id: usize,
1639 blocks: HashMap<CustomBlockId, Diagnostic>,
1640 is_valid: bool,
1641}
1642
1643#[derive(Serialize, Deserialize, Clone, Debug)]
1644pub struct ClipboardSelection {
1645 pub len: usize,
1646 pub is_entire_line: bool,
1647 pub first_line_indent: u32,
1648}
1649
1650#[derive(Debug)]
1651pub(crate) struct NavigationData {
1652 cursor_anchor: Anchor,
1653 cursor_position: Point,
1654 scroll_anchor: ScrollAnchor,
1655 scroll_top_row: u32,
1656}
1657
1658#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1659enum GotoDefinitionKind {
1660 Symbol,
1661 Declaration,
1662 Type,
1663 Implementation,
1664}
1665
1666#[derive(Debug, Clone)]
1667enum InlayHintRefreshReason {
1668 Toggle(bool),
1669 SettingsChange(InlayHintSettings),
1670 NewLinesShown,
1671 BufferEdited(HashSet<Arc<Language>>),
1672 RefreshRequested,
1673 ExcerptsRemoved(Vec<ExcerptId>),
1674}
1675
1676impl InlayHintRefreshReason {
1677 fn description(&self) -> &'static str {
1678 match self {
1679 Self::Toggle(_) => "toggle",
1680 Self::SettingsChange(_) => "settings change",
1681 Self::NewLinesShown => "new lines shown",
1682 Self::BufferEdited(_) => "buffer edited",
1683 Self::RefreshRequested => "refresh requested",
1684 Self::ExcerptsRemoved(_) => "excerpts removed",
1685 }
1686 }
1687}
1688
1689pub(crate) struct FocusedBlock {
1690 id: BlockId,
1691 focus_handle: WeakFocusHandle,
1692}
1693
1694impl Editor {
1695 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1696 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1697 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1698 Self::new(
1699 EditorMode::SingleLine { auto_width: false },
1700 buffer,
1701 None,
1702 false,
1703 cx,
1704 )
1705 }
1706
1707 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1708 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1709 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1710 Self::new(EditorMode::Full, buffer, None, false, cx)
1711 }
1712
1713 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1714 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1715 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1716 Self::new(
1717 EditorMode::SingleLine { auto_width: true },
1718 buffer,
1719 None,
1720 false,
1721 cx,
1722 )
1723 }
1724
1725 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1726 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1727 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1728 Self::new(
1729 EditorMode::AutoHeight { max_lines },
1730 buffer,
1731 None,
1732 false,
1733 cx,
1734 )
1735 }
1736
1737 pub fn for_buffer(
1738 buffer: Model<Buffer>,
1739 project: Option<Model<Project>>,
1740 cx: &mut ViewContext<Self>,
1741 ) -> Self {
1742 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1743 Self::new(EditorMode::Full, buffer, project, false, cx)
1744 }
1745
1746 pub fn for_multibuffer(
1747 buffer: Model<MultiBuffer>,
1748 project: Option<Model<Project>>,
1749 show_excerpt_controls: bool,
1750 cx: &mut ViewContext<Self>,
1751 ) -> Self {
1752 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1753 }
1754
1755 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1756 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1757 let mut clone = Self::new(
1758 self.mode,
1759 self.buffer.clone(),
1760 self.project.clone(),
1761 show_excerpt_controls,
1762 cx,
1763 );
1764 self.display_map.update(cx, |display_map, cx| {
1765 let snapshot = display_map.snapshot(cx);
1766 clone.display_map.update(cx, |display_map, cx| {
1767 display_map.set_state(&snapshot, cx);
1768 });
1769 });
1770 clone.selections.clone_state(&self.selections);
1771 clone.scroll_manager.clone_state(&self.scroll_manager);
1772 clone.searchable = self.searchable;
1773 clone
1774 }
1775
1776 pub fn new(
1777 mode: EditorMode,
1778 buffer: Model<MultiBuffer>,
1779 project: Option<Model<Project>>,
1780 show_excerpt_controls: bool,
1781 cx: &mut ViewContext<Self>,
1782 ) -> Self {
1783 let style = cx.text_style();
1784 let font_size = style.font_size.to_pixels(cx.rem_size());
1785 let editor = cx.view().downgrade();
1786 let fold_placeholder = FoldPlaceholder {
1787 constrain_width: true,
1788 render: Arc::new(move |fold_id, fold_range, cx| {
1789 let editor = editor.clone();
1790 div()
1791 .id(fold_id)
1792 .bg(cx.theme().colors().ghost_element_background)
1793 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1794 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1795 .rounded_sm()
1796 .size_full()
1797 .cursor_pointer()
1798 .child("⋯")
1799 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1800 .on_click(move |_, cx| {
1801 editor
1802 .update(cx, |editor, cx| {
1803 editor.unfold_ranges(
1804 [fold_range.start..fold_range.end],
1805 true,
1806 false,
1807 cx,
1808 );
1809 cx.stop_propagation();
1810 })
1811 .ok();
1812 })
1813 .into_any()
1814 }),
1815 merge_adjacent: true,
1816 };
1817 let file_header_size = if show_excerpt_controls { 3 } else { 2 };
1818 let display_map = cx.new_model(|cx| {
1819 DisplayMap::new(
1820 buffer.clone(),
1821 style.font(),
1822 font_size,
1823 None,
1824 show_excerpt_controls,
1825 file_header_size,
1826 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1827 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1828 fold_placeholder,
1829 cx,
1830 )
1831 });
1832
1833 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1834
1835 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1836
1837 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1838 .then(|| language_settings::SoftWrap::PreferLine);
1839
1840 let mut project_subscriptions = Vec::new();
1841 if mode == EditorMode::Full {
1842 if let Some(project) = project.as_ref() {
1843 if buffer.read(cx).is_singleton() {
1844 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1845 cx.emit(EditorEvent::TitleChanged);
1846 }));
1847 }
1848 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1849 if let project::Event::RefreshInlayHints = event {
1850 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1851 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1852 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1853 let focus_handle = editor.focus_handle(cx);
1854 if focus_handle.is_focused(cx) {
1855 let snapshot = buffer.read(cx).snapshot();
1856 for (range, snippet) in snippet_edits {
1857 let editor_range =
1858 language::range_from_lsp(*range).to_offset(&snapshot);
1859 editor
1860 .insert_snippet(&[editor_range], snippet.clone(), cx)
1861 .ok();
1862 }
1863 }
1864 }
1865 }
1866 }));
1867 let task_inventory = project.read(cx).task_inventory().clone();
1868 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1869 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1870 }));
1871 }
1872 }
1873
1874 let inlay_hint_settings = inlay_hint_settings(
1875 selections.newest_anchor().head(),
1876 &buffer.read(cx).snapshot(cx),
1877 cx,
1878 );
1879 let focus_handle = cx.focus_handle();
1880 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1881 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1882 .detach();
1883 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1884 .detach();
1885 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1886
1887 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1888 Some(false)
1889 } else {
1890 None
1891 };
1892
1893 let mut code_action_providers = Vec::new();
1894 if let Some(project) = project.clone() {
1895 code_action_providers.push(Arc::new(project) as Arc<_>);
1896 }
1897
1898 let mut this = Self {
1899 focus_handle,
1900 show_cursor_when_unfocused: false,
1901 last_focused_descendant: None,
1902 buffer: buffer.clone(),
1903 display_map: display_map.clone(),
1904 selections,
1905 scroll_manager: ScrollManager::new(cx),
1906 columnar_selection_tail: None,
1907 add_selections_state: None,
1908 select_next_state: None,
1909 select_prev_state: None,
1910 selection_history: Default::default(),
1911 autoclose_regions: Default::default(),
1912 snippet_stack: Default::default(),
1913 select_larger_syntax_node_stack: Vec::new(),
1914 ime_transaction: Default::default(),
1915 active_diagnostics: None,
1916 soft_wrap_mode_override,
1917 completion_provider: project.clone().map(|project| Box::new(project) as _),
1918 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1919 project,
1920 blink_manager: blink_manager.clone(),
1921 show_local_selections: true,
1922 mode,
1923 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1924 show_gutter: mode == EditorMode::Full,
1925 show_line_numbers: None,
1926 use_relative_line_numbers: None,
1927 show_git_diff_gutter: None,
1928 show_code_actions: None,
1929 show_runnables: None,
1930 show_wrap_guides: None,
1931 show_indent_guides,
1932 placeholder_text: None,
1933 highlight_order: 0,
1934 highlighted_rows: HashMap::default(),
1935 background_highlights: Default::default(),
1936 gutter_highlights: TreeMap::default(),
1937 scrollbar_marker_state: ScrollbarMarkerState::default(),
1938 active_indent_guides_state: ActiveIndentGuidesState::default(),
1939 nav_history: None,
1940 context_menu: RwLock::new(None),
1941 mouse_context_menu: None,
1942 hunk_controls_menu_handle: PopoverMenuHandle::default(),
1943 completion_tasks: Default::default(),
1944 signature_help_state: SignatureHelpState::default(),
1945 auto_signature_help: None,
1946 find_all_references_task_sources: Vec::new(),
1947 next_completion_id: 0,
1948 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1949 next_inlay_id: 0,
1950 code_action_providers,
1951 available_code_actions: Default::default(),
1952 code_actions_task: Default::default(),
1953 document_highlights_task: Default::default(),
1954 linked_editing_range_task: Default::default(),
1955 pending_rename: Default::default(),
1956 searchable: true,
1957 cursor_shape: EditorSettings::get_global(cx)
1958 .cursor_shape
1959 .unwrap_or_default(),
1960 current_line_highlight: None,
1961 autoindent_mode: Some(AutoindentMode::EachLine),
1962 collapse_matches: false,
1963 workspace: None,
1964 input_enabled: true,
1965 use_modal_editing: mode == EditorMode::Full,
1966 read_only: false,
1967 use_autoclose: true,
1968 use_auto_surround: true,
1969 auto_replace_emoji_shortcode: false,
1970 leader_peer_id: None,
1971 remote_id: None,
1972 hover_state: Default::default(),
1973 hovered_link_state: Default::default(),
1974 inline_completion_provider: None,
1975 active_inline_completion: None,
1976 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1977 expanded_hunks: ExpandedHunks::default(),
1978 gutter_hovered: false,
1979 pixel_position_of_newest_cursor: None,
1980 last_bounds: None,
1981 expect_bounds_change: None,
1982 gutter_dimensions: GutterDimensions::default(),
1983 style: None,
1984 show_cursor_names: false,
1985 hovered_cursors: Default::default(),
1986 next_editor_action_id: EditorActionId::default(),
1987 editor_actions: Rc::default(),
1988 show_inline_completions_override: None,
1989 enable_inline_completions: true,
1990 custom_context_menu: None,
1991 show_git_blame_gutter: false,
1992 show_git_blame_inline: false,
1993 show_selection_menu: None,
1994 show_git_blame_inline_delay_task: None,
1995 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1996 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1997 .session
1998 .restore_unsaved_buffers,
1999 blame: None,
2000 blame_subscription: None,
2001 file_header_size,
2002 tasks: Default::default(),
2003 _subscriptions: vec![
2004 cx.observe(&buffer, Self::on_buffer_changed),
2005 cx.subscribe(&buffer, Self::on_buffer_event),
2006 cx.observe(&display_map, Self::on_display_map_changed),
2007 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
2008 cx.observe_global::<SettingsStore>(Self::settings_changed),
2009 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
2010 cx.observe_window_activation(|editor, cx| {
2011 let active = cx.is_window_active();
2012 editor.blink_manager.update(cx, |blink_manager, cx| {
2013 if active {
2014 blink_manager.enable(cx);
2015 } else {
2016 blink_manager.disable(cx);
2017 }
2018 });
2019 }),
2020 ],
2021 tasks_update_task: None,
2022 linked_edit_ranges: Default::default(),
2023 previous_search_ranges: None,
2024 breadcrumb_header: None,
2025 focused_block: None,
2026 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
2027 addons: HashMap::default(),
2028 _scroll_cursor_center_top_bottom_task: Task::ready(()),
2029 };
2030 this.tasks_update_task = Some(this.refresh_runnables(cx));
2031 this._subscriptions.extend(project_subscriptions);
2032
2033 this.end_selection(cx);
2034 this.scroll_manager.show_scrollbar(cx);
2035
2036 if mode == EditorMode::Full {
2037 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
2038 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
2039
2040 if this.git_blame_inline_enabled {
2041 this.git_blame_inline_enabled = true;
2042 this.start_git_blame_inline(false, cx);
2043 }
2044 }
2045
2046 this.report_editor_event("open", None, cx);
2047 this
2048 }
2049
2050 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
2051 self.mouse_context_menu
2052 .as_ref()
2053 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
2054 }
2055
2056 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
2057 let mut key_context = KeyContext::new_with_defaults();
2058 key_context.add("Editor");
2059 let mode = match self.mode {
2060 EditorMode::SingleLine { .. } => "single_line",
2061 EditorMode::AutoHeight { .. } => "auto_height",
2062 EditorMode::Full => "full",
2063 };
2064
2065 if EditorSettings::jupyter_enabled(cx) {
2066 key_context.add("jupyter");
2067 }
2068
2069 key_context.set("mode", mode);
2070 if self.pending_rename.is_some() {
2071 key_context.add("renaming");
2072 }
2073 if self.context_menu_visible() {
2074 match self.context_menu.read().as_ref() {
2075 Some(ContextMenu::Completions(_)) => {
2076 key_context.add("menu");
2077 key_context.add("showing_completions")
2078 }
2079 Some(ContextMenu::CodeActions(_)) => {
2080 key_context.add("menu");
2081 key_context.add("showing_code_actions")
2082 }
2083 None => {}
2084 }
2085 }
2086
2087 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2088 if !self.focus_handle(cx).contains_focused(cx)
2089 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2090 {
2091 for addon in self.addons.values() {
2092 addon.extend_key_context(&mut key_context, cx)
2093 }
2094 }
2095
2096 if let Some(extension) = self
2097 .buffer
2098 .read(cx)
2099 .as_singleton()
2100 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2101 {
2102 key_context.set("extension", extension.to_string());
2103 }
2104
2105 if self.has_active_inline_completion(cx) {
2106 key_context.add("copilot_suggestion");
2107 key_context.add("inline_completion");
2108 }
2109
2110 key_context
2111 }
2112
2113 pub fn new_file(
2114 workspace: &mut Workspace,
2115 _: &workspace::NewFile,
2116 cx: &mut ViewContext<Workspace>,
2117 ) {
2118 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2119 "Failed to create buffer",
2120 cx,
2121 |e, _| match e.error_code() {
2122 ErrorCode::RemoteUpgradeRequired => Some(format!(
2123 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2124 e.error_tag("required").unwrap_or("the latest version")
2125 )),
2126 _ => None,
2127 },
2128 );
2129 }
2130
2131 pub fn new_in_workspace(
2132 workspace: &mut Workspace,
2133 cx: &mut ViewContext<Workspace>,
2134 ) -> Task<Result<View<Editor>>> {
2135 let project = workspace.project().clone();
2136 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2137
2138 cx.spawn(|workspace, mut cx| async move {
2139 let buffer = create.await?;
2140 workspace.update(&mut cx, |workspace, cx| {
2141 let editor =
2142 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2143 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2144 editor
2145 })
2146 })
2147 }
2148
2149 fn new_file_vertical(
2150 workspace: &mut Workspace,
2151 _: &workspace::NewFileSplitVertical,
2152 cx: &mut ViewContext<Workspace>,
2153 ) {
2154 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2155 }
2156
2157 fn new_file_horizontal(
2158 workspace: &mut Workspace,
2159 _: &workspace::NewFileSplitHorizontal,
2160 cx: &mut ViewContext<Workspace>,
2161 ) {
2162 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2163 }
2164
2165 fn new_file_in_direction(
2166 workspace: &mut Workspace,
2167 direction: SplitDirection,
2168 cx: &mut ViewContext<Workspace>,
2169 ) {
2170 let project = workspace.project().clone();
2171 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2172
2173 cx.spawn(|workspace, mut cx| async move {
2174 let buffer = create.await?;
2175 workspace.update(&mut cx, move |workspace, cx| {
2176 workspace.split_item(
2177 direction,
2178 Box::new(
2179 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2180 ),
2181 cx,
2182 )
2183 })?;
2184 anyhow::Ok(())
2185 })
2186 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2187 ErrorCode::RemoteUpgradeRequired => Some(format!(
2188 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2189 e.error_tag("required").unwrap_or("the latest version")
2190 )),
2191 _ => None,
2192 });
2193 }
2194
2195 pub fn leader_peer_id(&self) -> Option<PeerId> {
2196 self.leader_peer_id
2197 }
2198
2199 pub fn buffer(&self) -> &Model<MultiBuffer> {
2200 &self.buffer
2201 }
2202
2203 pub fn workspace(&self) -> Option<View<Workspace>> {
2204 self.workspace.as_ref()?.0.upgrade()
2205 }
2206
2207 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2208 self.buffer().read(cx).title(cx)
2209 }
2210
2211 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2212 EditorSnapshot {
2213 mode: self.mode,
2214 show_gutter: self.show_gutter,
2215 show_line_numbers: self.show_line_numbers,
2216 show_git_diff_gutter: self.show_git_diff_gutter,
2217 show_code_actions: self.show_code_actions,
2218 show_runnables: self.show_runnables,
2219 render_git_blame_gutter: self.render_git_blame_gutter(cx),
2220 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2221 scroll_anchor: self.scroll_manager.anchor(),
2222 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2223 placeholder_text: self.placeholder_text.clone(),
2224 is_focused: self.focus_handle.is_focused(cx),
2225 current_line_highlight: self
2226 .current_line_highlight
2227 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2228 gutter_hovered: self.gutter_hovered,
2229 }
2230 }
2231
2232 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2233 self.buffer.read(cx).language_at(point, cx)
2234 }
2235
2236 pub fn file_at<T: ToOffset>(
2237 &self,
2238 point: T,
2239 cx: &AppContext,
2240 ) -> Option<Arc<dyn language::File>> {
2241 self.buffer.read(cx).read(cx).file_at(point).cloned()
2242 }
2243
2244 pub fn active_excerpt(
2245 &self,
2246 cx: &AppContext,
2247 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2248 self.buffer
2249 .read(cx)
2250 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2251 }
2252
2253 pub fn mode(&self) -> EditorMode {
2254 self.mode
2255 }
2256
2257 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2258 self.collaboration_hub.as_deref()
2259 }
2260
2261 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2262 self.collaboration_hub = Some(hub);
2263 }
2264
2265 pub fn set_custom_context_menu(
2266 &mut self,
2267 f: impl 'static
2268 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2269 ) {
2270 self.custom_context_menu = Some(Box::new(f))
2271 }
2272
2273 pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
2274 self.completion_provider = Some(provider);
2275 }
2276
2277 pub fn set_inline_completion_provider<T>(
2278 &mut self,
2279 provider: Option<Model<T>>,
2280 cx: &mut ViewContext<Self>,
2281 ) where
2282 T: InlineCompletionProvider,
2283 {
2284 self.inline_completion_provider =
2285 provider.map(|provider| RegisteredInlineCompletionProvider {
2286 _subscription: cx.observe(&provider, |this, _, cx| {
2287 if this.focus_handle.is_focused(cx) {
2288 this.update_visible_inline_completion(cx);
2289 }
2290 }),
2291 provider: Arc::new(provider),
2292 });
2293 self.refresh_inline_completion(false, false, cx);
2294 }
2295
2296 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2297 self.placeholder_text.as_deref()
2298 }
2299
2300 pub fn set_placeholder_text(
2301 &mut self,
2302 placeholder_text: impl Into<Arc<str>>,
2303 cx: &mut ViewContext<Self>,
2304 ) {
2305 let placeholder_text = Some(placeholder_text.into());
2306 if self.placeholder_text != placeholder_text {
2307 self.placeholder_text = placeholder_text;
2308 cx.notify();
2309 }
2310 }
2311
2312 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2313 self.cursor_shape = cursor_shape;
2314
2315 // Disrupt blink for immediate user feedback that the cursor shape has changed
2316 self.blink_manager.update(cx, BlinkManager::show_cursor);
2317
2318 cx.notify();
2319 }
2320
2321 pub fn set_current_line_highlight(
2322 &mut self,
2323 current_line_highlight: Option<CurrentLineHighlight>,
2324 ) {
2325 self.current_line_highlight = current_line_highlight;
2326 }
2327
2328 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2329 self.collapse_matches = collapse_matches;
2330 }
2331
2332 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2333 if self.collapse_matches {
2334 return range.start..range.start;
2335 }
2336 range.clone()
2337 }
2338
2339 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2340 if self.display_map.read(cx).clip_at_line_ends != clip {
2341 self.display_map
2342 .update(cx, |map, _| map.clip_at_line_ends = clip);
2343 }
2344 }
2345
2346 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2347 self.input_enabled = input_enabled;
2348 }
2349
2350 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
2351 self.enable_inline_completions = enabled;
2352 }
2353
2354 pub fn set_autoindent(&mut self, autoindent: bool) {
2355 if autoindent {
2356 self.autoindent_mode = Some(AutoindentMode::EachLine);
2357 } else {
2358 self.autoindent_mode = None;
2359 }
2360 }
2361
2362 pub fn read_only(&self, cx: &AppContext) -> bool {
2363 self.read_only || self.buffer.read(cx).read_only()
2364 }
2365
2366 pub fn set_read_only(&mut self, read_only: bool) {
2367 self.read_only = read_only;
2368 }
2369
2370 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2371 self.use_autoclose = autoclose;
2372 }
2373
2374 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2375 self.use_auto_surround = auto_surround;
2376 }
2377
2378 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2379 self.auto_replace_emoji_shortcode = auto_replace;
2380 }
2381
2382 pub fn toggle_inline_completions(
2383 &mut self,
2384 _: &ToggleInlineCompletions,
2385 cx: &mut ViewContext<Self>,
2386 ) {
2387 if self.show_inline_completions_override.is_some() {
2388 self.set_show_inline_completions(None, cx);
2389 } else {
2390 let cursor = self.selections.newest_anchor().head();
2391 if let Some((buffer, cursor_buffer_position)) =
2392 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2393 {
2394 let show_inline_completions =
2395 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2396 self.set_show_inline_completions(Some(show_inline_completions), cx);
2397 }
2398 }
2399 }
2400
2401 pub fn set_show_inline_completions(
2402 &mut self,
2403 show_inline_completions: Option<bool>,
2404 cx: &mut ViewContext<Self>,
2405 ) {
2406 self.show_inline_completions_override = show_inline_completions;
2407 self.refresh_inline_completion(false, true, cx);
2408 }
2409
2410 fn should_show_inline_completions(
2411 &self,
2412 buffer: &Model<Buffer>,
2413 buffer_position: language::Anchor,
2414 cx: &AppContext,
2415 ) -> bool {
2416 if let Some(provider) = self.inline_completion_provider() {
2417 if let Some(show_inline_completions) = self.show_inline_completions_override {
2418 show_inline_completions
2419 } else {
2420 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
2421 }
2422 } else {
2423 false
2424 }
2425 }
2426
2427 pub fn set_use_modal_editing(&mut self, to: bool) {
2428 self.use_modal_editing = to;
2429 }
2430
2431 pub fn use_modal_editing(&self) -> bool {
2432 self.use_modal_editing
2433 }
2434
2435 fn selections_did_change(
2436 &mut self,
2437 local: bool,
2438 old_cursor_position: &Anchor,
2439 show_completions: bool,
2440 cx: &mut ViewContext<Self>,
2441 ) {
2442 cx.invalidate_character_coordinates();
2443
2444 // Copy selections to primary selection buffer
2445 #[cfg(target_os = "linux")]
2446 if local {
2447 let selections = self.selections.all::<usize>(cx);
2448 let buffer_handle = self.buffer.read(cx).read(cx);
2449
2450 let mut text = String::new();
2451 for (index, selection) in selections.iter().enumerate() {
2452 let text_for_selection = buffer_handle
2453 .text_for_range(selection.start..selection.end)
2454 .collect::<String>();
2455
2456 text.push_str(&text_for_selection);
2457 if index != selections.len() - 1 {
2458 text.push('\n');
2459 }
2460 }
2461
2462 if !text.is_empty() {
2463 cx.write_to_primary(ClipboardItem::new_string(text));
2464 }
2465 }
2466
2467 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2468 self.buffer.update(cx, |buffer, cx| {
2469 buffer.set_active_selections(
2470 &self.selections.disjoint_anchors(),
2471 self.selections.line_mode,
2472 self.cursor_shape,
2473 cx,
2474 )
2475 });
2476 }
2477 let display_map = self
2478 .display_map
2479 .update(cx, |display_map, cx| display_map.snapshot(cx));
2480 let buffer = &display_map.buffer_snapshot;
2481 self.add_selections_state = None;
2482 self.select_next_state = None;
2483 self.select_prev_state = None;
2484 self.select_larger_syntax_node_stack.clear();
2485 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2486 self.snippet_stack
2487 .invalidate(&self.selections.disjoint_anchors(), buffer);
2488 self.take_rename(false, cx);
2489
2490 let new_cursor_position = self.selections.newest_anchor().head();
2491
2492 self.push_to_nav_history(
2493 *old_cursor_position,
2494 Some(new_cursor_position.to_point(buffer)),
2495 cx,
2496 );
2497
2498 if local {
2499 let new_cursor_position = self.selections.newest_anchor().head();
2500 let mut context_menu = self.context_menu.write();
2501 let completion_menu = match context_menu.as_ref() {
2502 Some(ContextMenu::Completions(menu)) => Some(menu),
2503
2504 _ => {
2505 *context_menu = None;
2506 None
2507 }
2508 };
2509
2510 if let Some(completion_menu) = completion_menu {
2511 let cursor_position = new_cursor_position.to_offset(buffer);
2512 let (word_range, kind) =
2513 buffer.surrounding_word(completion_menu.initial_position, true);
2514 if kind == Some(CharKind::Word)
2515 && word_range.to_inclusive().contains(&cursor_position)
2516 {
2517 let mut completion_menu = completion_menu.clone();
2518 drop(context_menu);
2519
2520 let query = Self::completion_query(buffer, cursor_position);
2521 cx.spawn(move |this, mut cx| async move {
2522 completion_menu
2523 .filter(query.as_deref(), cx.background_executor().clone())
2524 .await;
2525
2526 this.update(&mut cx, |this, cx| {
2527 let mut context_menu = this.context_menu.write();
2528 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2529 return;
2530 };
2531
2532 if menu.id > completion_menu.id {
2533 return;
2534 }
2535
2536 *context_menu = Some(ContextMenu::Completions(completion_menu));
2537 drop(context_menu);
2538 cx.notify();
2539 })
2540 })
2541 .detach();
2542
2543 if show_completions {
2544 self.show_completions(&ShowCompletions { trigger: None }, cx);
2545 }
2546 } else {
2547 drop(context_menu);
2548 self.hide_context_menu(cx);
2549 }
2550 } else {
2551 drop(context_menu);
2552 }
2553
2554 hide_hover(self, cx);
2555
2556 if old_cursor_position.to_display_point(&display_map).row()
2557 != new_cursor_position.to_display_point(&display_map).row()
2558 {
2559 self.available_code_actions.take();
2560 }
2561 self.refresh_code_actions(cx);
2562 self.refresh_document_highlights(cx);
2563 refresh_matching_bracket_highlights(self, cx);
2564 self.discard_inline_completion(false, cx);
2565 linked_editing_ranges::refresh_linked_ranges(self, cx);
2566 if self.git_blame_inline_enabled {
2567 self.start_inline_blame_timer(cx);
2568 }
2569 }
2570
2571 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2572 cx.emit(EditorEvent::SelectionsChanged { local });
2573
2574 if self.selections.disjoint_anchors().len() == 1 {
2575 cx.emit(SearchEvent::ActiveMatchChanged)
2576 }
2577 cx.notify();
2578 }
2579
2580 pub fn change_selections<R>(
2581 &mut self,
2582 autoscroll: Option<Autoscroll>,
2583 cx: &mut ViewContext<Self>,
2584 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2585 ) -> R {
2586 self.change_selections_inner(autoscroll, true, cx, change)
2587 }
2588
2589 pub fn change_selections_inner<R>(
2590 &mut self,
2591 autoscroll: Option<Autoscroll>,
2592 request_completions: bool,
2593 cx: &mut ViewContext<Self>,
2594 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2595 ) -> R {
2596 let old_cursor_position = self.selections.newest_anchor().head();
2597 self.push_to_selection_history();
2598
2599 let (changed, result) = self.selections.change_with(cx, change);
2600
2601 if changed {
2602 if let Some(autoscroll) = autoscroll {
2603 self.request_autoscroll(autoscroll, cx);
2604 }
2605 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2606
2607 if self.should_open_signature_help_automatically(
2608 &old_cursor_position,
2609 self.signature_help_state.backspace_pressed(),
2610 cx,
2611 ) {
2612 self.show_signature_help(&ShowSignatureHelp, cx);
2613 }
2614 self.signature_help_state.set_backspace_pressed(false);
2615 }
2616
2617 result
2618 }
2619
2620 pub fn edit<I, S, T>(&mut self, edits: I, 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
2631 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2632 }
2633
2634 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2635 where
2636 I: IntoIterator<Item = (Range<S>, T)>,
2637 S: ToOffset,
2638 T: Into<Arc<str>>,
2639 {
2640 if self.read_only(cx) {
2641 return;
2642 }
2643
2644 self.buffer.update(cx, |buffer, cx| {
2645 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2646 });
2647 }
2648
2649 pub fn edit_with_block_indent<I, S, T>(
2650 &mut self,
2651 edits: I,
2652 original_indent_columns: Vec<u32>,
2653 cx: &mut ViewContext<Self>,
2654 ) where
2655 I: IntoIterator<Item = (Range<S>, T)>,
2656 S: ToOffset,
2657 T: Into<Arc<str>>,
2658 {
2659 if self.read_only(cx) {
2660 return;
2661 }
2662
2663 self.buffer.update(cx, |buffer, cx| {
2664 buffer.edit(
2665 edits,
2666 Some(AutoindentMode::Block {
2667 original_indent_columns,
2668 }),
2669 cx,
2670 )
2671 });
2672 }
2673
2674 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2675 self.hide_context_menu(cx);
2676
2677 match phase {
2678 SelectPhase::Begin {
2679 position,
2680 add,
2681 click_count,
2682 } => self.begin_selection(position, add, click_count, cx),
2683 SelectPhase::BeginColumnar {
2684 position,
2685 goal_column,
2686 reset,
2687 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2688 SelectPhase::Extend {
2689 position,
2690 click_count,
2691 } => self.extend_selection(position, click_count, cx),
2692 SelectPhase::Update {
2693 position,
2694 goal_column,
2695 scroll_delta,
2696 } => self.update_selection(position, goal_column, scroll_delta, cx),
2697 SelectPhase::End => self.end_selection(cx),
2698 }
2699 }
2700
2701 fn extend_selection(
2702 &mut self,
2703 position: DisplayPoint,
2704 click_count: usize,
2705 cx: &mut ViewContext<Self>,
2706 ) {
2707 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2708 let tail = self.selections.newest::<usize>(cx).tail();
2709 self.begin_selection(position, false, click_count, cx);
2710
2711 let position = position.to_offset(&display_map, Bias::Left);
2712 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2713
2714 let mut pending_selection = self
2715 .selections
2716 .pending_anchor()
2717 .expect("extend_selection not called with pending selection");
2718 if position >= tail {
2719 pending_selection.start = tail_anchor;
2720 } else {
2721 pending_selection.end = tail_anchor;
2722 pending_selection.reversed = true;
2723 }
2724
2725 let mut pending_mode = self.selections.pending_mode().unwrap();
2726 match &mut pending_mode {
2727 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2728 _ => {}
2729 }
2730
2731 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2732 s.set_pending(pending_selection, pending_mode)
2733 });
2734 }
2735
2736 fn begin_selection(
2737 &mut self,
2738 position: DisplayPoint,
2739 add: bool,
2740 click_count: usize,
2741 cx: &mut ViewContext<Self>,
2742 ) {
2743 if !self.focus_handle.is_focused(cx) {
2744 self.last_focused_descendant = None;
2745 cx.focus(&self.focus_handle);
2746 }
2747
2748 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2749 let buffer = &display_map.buffer_snapshot;
2750 let newest_selection = self.selections.newest_anchor().clone();
2751 let position = display_map.clip_point(position, Bias::Left);
2752
2753 let start;
2754 let end;
2755 let mode;
2756 let auto_scroll;
2757 match click_count {
2758 1 => {
2759 start = buffer.anchor_before(position.to_point(&display_map));
2760 end = start;
2761 mode = SelectMode::Character;
2762 auto_scroll = true;
2763 }
2764 2 => {
2765 let range = movement::surrounding_word(&display_map, position);
2766 start = buffer.anchor_before(range.start.to_point(&display_map));
2767 end = buffer.anchor_before(range.end.to_point(&display_map));
2768 mode = SelectMode::Word(start..end);
2769 auto_scroll = true;
2770 }
2771 3 => {
2772 let position = display_map
2773 .clip_point(position, Bias::Left)
2774 .to_point(&display_map);
2775 let line_start = display_map.prev_line_boundary(position).0;
2776 let next_line_start = buffer.clip_point(
2777 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2778 Bias::Left,
2779 );
2780 start = buffer.anchor_before(line_start);
2781 end = buffer.anchor_before(next_line_start);
2782 mode = SelectMode::Line(start..end);
2783 auto_scroll = true;
2784 }
2785 _ => {
2786 start = buffer.anchor_before(0);
2787 end = buffer.anchor_before(buffer.len());
2788 mode = SelectMode::All;
2789 auto_scroll = false;
2790 }
2791 }
2792
2793 let point_to_delete: Option<usize> = {
2794 let selected_points: Vec<Selection<Point>> =
2795 self.selections.disjoint_in_range(start..end, cx);
2796
2797 if !add || click_count > 1 {
2798 None
2799 } else if !selected_points.is_empty() {
2800 Some(selected_points[0].id)
2801 } else {
2802 let clicked_point_already_selected =
2803 self.selections.disjoint.iter().find(|selection| {
2804 selection.start.to_point(buffer) == start.to_point(buffer)
2805 || selection.end.to_point(buffer) == end.to_point(buffer)
2806 });
2807
2808 clicked_point_already_selected.map(|selection| selection.id)
2809 }
2810 };
2811
2812 let selections_count = self.selections.count();
2813
2814 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2815 if let Some(point_to_delete) = point_to_delete {
2816 s.delete(point_to_delete);
2817
2818 if selections_count == 1 {
2819 s.set_pending_anchor_range(start..end, mode);
2820 }
2821 } else {
2822 if !add {
2823 s.clear_disjoint();
2824 } else if click_count > 1 {
2825 s.delete(newest_selection.id)
2826 }
2827
2828 s.set_pending_anchor_range(start..end, mode);
2829 }
2830 });
2831 }
2832
2833 fn begin_columnar_selection(
2834 &mut self,
2835 position: DisplayPoint,
2836 goal_column: u32,
2837 reset: bool,
2838 cx: &mut ViewContext<Self>,
2839 ) {
2840 if !self.focus_handle.is_focused(cx) {
2841 self.last_focused_descendant = None;
2842 cx.focus(&self.focus_handle);
2843 }
2844
2845 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2846
2847 if reset {
2848 let pointer_position = display_map
2849 .buffer_snapshot
2850 .anchor_before(position.to_point(&display_map));
2851
2852 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2853 s.clear_disjoint();
2854 s.set_pending_anchor_range(
2855 pointer_position..pointer_position,
2856 SelectMode::Character,
2857 );
2858 });
2859 }
2860
2861 let tail = self.selections.newest::<Point>(cx).tail();
2862 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2863
2864 if !reset {
2865 self.select_columns(
2866 tail.to_display_point(&display_map),
2867 position,
2868 goal_column,
2869 &display_map,
2870 cx,
2871 );
2872 }
2873 }
2874
2875 fn update_selection(
2876 &mut self,
2877 position: DisplayPoint,
2878 goal_column: u32,
2879 scroll_delta: gpui::Point<f32>,
2880 cx: &mut ViewContext<Self>,
2881 ) {
2882 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2883
2884 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2885 let tail = tail.to_display_point(&display_map);
2886 self.select_columns(tail, position, goal_column, &display_map, cx);
2887 } else if let Some(mut pending) = self.selections.pending_anchor() {
2888 let buffer = self.buffer.read(cx).snapshot(cx);
2889 let head;
2890 let tail;
2891 let mode = self.selections.pending_mode().unwrap();
2892 match &mode {
2893 SelectMode::Character => {
2894 head = position.to_point(&display_map);
2895 tail = pending.tail().to_point(&buffer);
2896 }
2897 SelectMode::Word(original_range) => {
2898 let original_display_range = original_range.start.to_display_point(&display_map)
2899 ..original_range.end.to_display_point(&display_map);
2900 let original_buffer_range = original_display_range.start.to_point(&display_map)
2901 ..original_display_range.end.to_point(&display_map);
2902 if movement::is_inside_word(&display_map, position)
2903 || original_display_range.contains(&position)
2904 {
2905 let word_range = movement::surrounding_word(&display_map, position);
2906 if word_range.start < original_display_range.start {
2907 head = word_range.start.to_point(&display_map);
2908 } else {
2909 head = word_range.end.to_point(&display_map);
2910 }
2911 } else {
2912 head = position.to_point(&display_map);
2913 }
2914
2915 if head <= original_buffer_range.start {
2916 tail = original_buffer_range.end;
2917 } else {
2918 tail = original_buffer_range.start;
2919 }
2920 }
2921 SelectMode::Line(original_range) => {
2922 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2923
2924 let position = display_map
2925 .clip_point(position, Bias::Left)
2926 .to_point(&display_map);
2927 let line_start = display_map.prev_line_boundary(position).0;
2928 let next_line_start = buffer.clip_point(
2929 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2930 Bias::Left,
2931 );
2932
2933 if line_start < original_range.start {
2934 head = line_start
2935 } else {
2936 head = next_line_start
2937 }
2938
2939 if head <= original_range.start {
2940 tail = original_range.end;
2941 } else {
2942 tail = original_range.start;
2943 }
2944 }
2945 SelectMode::All => {
2946 return;
2947 }
2948 };
2949
2950 if head < tail {
2951 pending.start = buffer.anchor_before(head);
2952 pending.end = buffer.anchor_before(tail);
2953 pending.reversed = true;
2954 } else {
2955 pending.start = buffer.anchor_before(tail);
2956 pending.end = buffer.anchor_before(head);
2957 pending.reversed = false;
2958 }
2959
2960 self.change_selections(None, cx, |s| {
2961 s.set_pending(pending, mode);
2962 });
2963 } else {
2964 log::error!("update_selection dispatched with no pending selection");
2965 return;
2966 }
2967
2968 self.apply_scroll_delta(scroll_delta, cx);
2969 cx.notify();
2970 }
2971
2972 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2973 self.columnar_selection_tail.take();
2974 if self.selections.pending_anchor().is_some() {
2975 let selections = self.selections.all::<usize>(cx);
2976 self.change_selections(None, cx, |s| {
2977 s.select(selections);
2978 s.clear_pending();
2979 });
2980 }
2981 }
2982
2983 fn select_columns(
2984 &mut self,
2985 tail: DisplayPoint,
2986 head: DisplayPoint,
2987 goal_column: u32,
2988 display_map: &DisplaySnapshot,
2989 cx: &mut ViewContext<Self>,
2990 ) {
2991 let start_row = cmp::min(tail.row(), head.row());
2992 let end_row = cmp::max(tail.row(), head.row());
2993 let start_column = cmp::min(tail.column(), goal_column);
2994 let end_column = cmp::max(tail.column(), goal_column);
2995 let reversed = start_column < tail.column();
2996
2997 let selection_ranges = (start_row.0..=end_row.0)
2998 .map(DisplayRow)
2999 .filter_map(|row| {
3000 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3001 let start = display_map
3002 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3003 .to_point(display_map);
3004 let end = display_map
3005 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3006 .to_point(display_map);
3007 if reversed {
3008 Some(end..start)
3009 } else {
3010 Some(start..end)
3011 }
3012 } else {
3013 None
3014 }
3015 })
3016 .collect::<Vec<_>>();
3017
3018 self.change_selections(None, cx, |s| {
3019 s.select_ranges(selection_ranges);
3020 });
3021 cx.notify();
3022 }
3023
3024 pub fn has_pending_nonempty_selection(&self) -> bool {
3025 let pending_nonempty_selection = match self.selections.pending_anchor() {
3026 Some(Selection { start, end, .. }) => start != end,
3027 None => false,
3028 };
3029
3030 pending_nonempty_selection
3031 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3032 }
3033
3034 pub fn has_pending_selection(&self) -> bool {
3035 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3036 }
3037
3038 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
3039 if self.clear_clicked_diff_hunks(cx) {
3040 cx.notify();
3041 return;
3042 }
3043 if self.dismiss_menus_and_popups(true, cx) {
3044 return;
3045 }
3046
3047 if self.mode == EditorMode::Full
3048 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
3049 {
3050 return;
3051 }
3052
3053 cx.propagate();
3054 }
3055
3056 pub fn dismiss_menus_and_popups(
3057 &mut self,
3058 should_report_inline_completion_event: bool,
3059 cx: &mut ViewContext<Self>,
3060 ) -> bool {
3061 if self.take_rename(false, cx).is_some() {
3062 return true;
3063 }
3064
3065 if hide_hover(self, cx) {
3066 return true;
3067 }
3068
3069 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3070 return true;
3071 }
3072
3073 if self.hide_context_menu(cx).is_some() {
3074 return true;
3075 }
3076
3077 if self.mouse_context_menu.take().is_some() {
3078 return true;
3079 }
3080
3081 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3082 return true;
3083 }
3084
3085 if self.snippet_stack.pop().is_some() {
3086 return true;
3087 }
3088
3089 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3090 self.dismiss_diagnostics(cx);
3091 return true;
3092 }
3093
3094 false
3095 }
3096
3097 fn linked_editing_ranges_for(
3098 &self,
3099 selection: Range<text::Anchor>,
3100 cx: &AppContext,
3101 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3102 if self.linked_edit_ranges.is_empty() {
3103 return None;
3104 }
3105 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3106 selection.end.buffer_id.and_then(|end_buffer_id| {
3107 if selection.start.buffer_id != Some(end_buffer_id) {
3108 return None;
3109 }
3110 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3111 let snapshot = buffer.read(cx).snapshot();
3112 self.linked_edit_ranges
3113 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3114 .map(|ranges| (ranges, snapshot, buffer))
3115 })?;
3116 use text::ToOffset as TO;
3117 // find offset from the start of current range to current cursor position
3118 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3119
3120 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3121 let start_difference = start_offset - start_byte_offset;
3122 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3123 let end_difference = end_offset - start_byte_offset;
3124 // Current range has associated linked ranges.
3125 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3126 for range in linked_ranges.iter() {
3127 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3128 let end_offset = start_offset + end_difference;
3129 let start_offset = start_offset + start_difference;
3130 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3131 continue;
3132 }
3133 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3134 if s.start.buffer_id != selection.start.buffer_id
3135 || s.end.buffer_id != selection.end.buffer_id
3136 {
3137 return false;
3138 }
3139 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3140 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3141 }) {
3142 continue;
3143 }
3144 let start = buffer_snapshot.anchor_after(start_offset);
3145 let end = buffer_snapshot.anchor_after(end_offset);
3146 linked_edits
3147 .entry(buffer.clone())
3148 .or_default()
3149 .push(start..end);
3150 }
3151 Some(linked_edits)
3152 }
3153
3154 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3155 let text: Arc<str> = text.into();
3156
3157 if self.read_only(cx) {
3158 return;
3159 }
3160
3161 let selections = self.selections.all_adjusted(cx);
3162 let mut bracket_inserted = false;
3163 let mut edits = Vec::new();
3164 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3165 let mut new_selections = Vec::with_capacity(selections.len());
3166 let mut new_autoclose_regions = Vec::new();
3167 let snapshot = self.buffer.read(cx).read(cx);
3168
3169 for (selection, autoclose_region) in
3170 self.selections_with_autoclose_regions(selections, &snapshot)
3171 {
3172 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3173 // Determine if the inserted text matches the opening or closing
3174 // bracket of any of this language's bracket pairs.
3175 let mut bracket_pair = None;
3176 let mut is_bracket_pair_start = false;
3177 let mut is_bracket_pair_end = false;
3178 if !text.is_empty() {
3179 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3180 // and they are removing the character that triggered IME popup.
3181 for (pair, enabled) in scope.brackets() {
3182 if !pair.close && !pair.surround {
3183 continue;
3184 }
3185
3186 if enabled && pair.start.ends_with(text.as_ref()) {
3187 bracket_pair = Some(pair.clone());
3188 is_bracket_pair_start = true;
3189 break;
3190 }
3191 if pair.end.as_str() == text.as_ref() {
3192 bracket_pair = Some(pair.clone());
3193 is_bracket_pair_end = true;
3194 break;
3195 }
3196 }
3197 }
3198
3199 if let Some(bracket_pair) = bracket_pair {
3200 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3201 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3202 let auto_surround =
3203 self.use_auto_surround && snapshot_settings.use_auto_surround;
3204 if selection.is_empty() {
3205 if is_bracket_pair_start {
3206 let prefix_len = bracket_pair.start.len() - text.len();
3207
3208 // If the inserted text is a suffix of an opening bracket and the
3209 // selection is preceded by the rest of the opening bracket, then
3210 // insert the closing bracket.
3211 let following_text_allows_autoclose = snapshot
3212 .chars_at(selection.start)
3213 .next()
3214 .map_or(true, |c| scope.should_autoclose_before(c));
3215 let preceding_text_matches_prefix = prefix_len == 0
3216 || (selection.start.column >= (prefix_len as u32)
3217 && snapshot.contains_str_at(
3218 Point::new(
3219 selection.start.row,
3220 selection.start.column - (prefix_len as u32),
3221 ),
3222 &bracket_pair.start[..prefix_len],
3223 ));
3224
3225 if autoclose
3226 && bracket_pair.close
3227 && following_text_allows_autoclose
3228 && preceding_text_matches_prefix
3229 {
3230 let anchor = snapshot.anchor_before(selection.end);
3231 new_selections.push((selection.map(|_| anchor), text.len()));
3232 new_autoclose_regions.push((
3233 anchor,
3234 text.len(),
3235 selection.id,
3236 bracket_pair.clone(),
3237 ));
3238 edits.push((
3239 selection.range(),
3240 format!("{}{}", text, bracket_pair.end).into(),
3241 ));
3242 bracket_inserted = true;
3243 continue;
3244 }
3245 }
3246
3247 if let Some(region) = autoclose_region {
3248 // If the selection is followed by an auto-inserted closing bracket,
3249 // then don't insert that closing bracket again; just move the selection
3250 // past the closing bracket.
3251 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3252 && text.as_ref() == region.pair.end.as_str();
3253 if should_skip {
3254 let anchor = snapshot.anchor_after(selection.end);
3255 new_selections
3256 .push((selection.map(|_| anchor), region.pair.end.len()));
3257 continue;
3258 }
3259 }
3260
3261 let always_treat_brackets_as_autoclosed = snapshot
3262 .settings_at(selection.start, cx)
3263 .always_treat_brackets_as_autoclosed;
3264 if always_treat_brackets_as_autoclosed
3265 && is_bracket_pair_end
3266 && snapshot.contains_str_at(selection.end, text.as_ref())
3267 {
3268 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3269 // and the inserted text is a closing bracket and the selection is followed
3270 // by the closing bracket then move the selection past the closing bracket.
3271 let anchor = snapshot.anchor_after(selection.end);
3272 new_selections.push((selection.map(|_| anchor), text.len()));
3273 continue;
3274 }
3275 }
3276 // If an opening bracket is 1 character long and is typed while
3277 // text is selected, then surround that text with the bracket pair.
3278 else if auto_surround
3279 && bracket_pair.surround
3280 && is_bracket_pair_start
3281 && bracket_pair.start.chars().count() == 1
3282 {
3283 edits.push((selection.start..selection.start, text.clone()));
3284 edits.push((
3285 selection.end..selection.end,
3286 bracket_pair.end.as_str().into(),
3287 ));
3288 bracket_inserted = true;
3289 new_selections.push((
3290 Selection {
3291 id: selection.id,
3292 start: snapshot.anchor_after(selection.start),
3293 end: snapshot.anchor_before(selection.end),
3294 reversed: selection.reversed,
3295 goal: selection.goal,
3296 },
3297 0,
3298 ));
3299 continue;
3300 }
3301 }
3302 }
3303
3304 if self.auto_replace_emoji_shortcode
3305 && selection.is_empty()
3306 && text.as_ref().ends_with(':')
3307 {
3308 if let Some(possible_emoji_short_code) =
3309 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3310 {
3311 if !possible_emoji_short_code.is_empty() {
3312 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3313 let emoji_shortcode_start = Point::new(
3314 selection.start.row,
3315 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3316 );
3317
3318 // Remove shortcode from buffer
3319 edits.push((
3320 emoji_shortcode_start..selection.start,
3321 "".to_string().into(),
3322 ));
3323 new_selections.push((
3324 Selection {
3325 id: selection.id,
3326 start: snapshot.anchor_after(emoji_shortcode_start),
3327 end: snapshot.anchor_before(selection.start),
3328 reversed: selection.reversed,
3329 goal: selection.goal,
3330 },
3331 0,
3332 ));
3333
3334 // Insert emoji
3335 let selection_start_anchor = snapshot.anchor_after(selection.start);
3336 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3337 edits.push((selection.start..selection.end, emoji.to_string().into()));
3338
3339 continue;
3340 }
3341 }
3342 }
3343 }
3344
3345 // If not handling any auto-close operation, then just replace the selected
3346 // text with the given input and move the selection to the end of the
3347 // newly inserted text.
3348 let anchor = snapshot.anchor_after(selection.end);
3349 if !self.linked_edit_ranges.is_empty() {
3350 let start_anchor = snapshot.anchor_before(selection.start);
3351
3352 let is_word_char = text.chars().next().map_or(true, |char| {
3353 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3354 classifier.is_word(char)
3355 });
3356
3357 if is_word_char {
3358 if let Some(ranges) = self
3359 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3360 {
3361 for (buffer, edits) in ranges {
3362 linked_edits
3363 .entry(buffer.clone())
3364 .or_default()
3365 .extend(edits.into_iter().map(|range| (range, text.clone())));
3366 }
3367 }
3368 }
3369 }
3370
3371 new_selections.push((selection.map(|_| anchor), 0));
3372 edits.push((selection.start..selection.end, text.clone()));
3373 }
3374
3375 drop(snapshot);
3376
3377 self.transact(cx, |this, cx| {
3378 this.buffer.update(cx, |buffer, cx| {
3379 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3380 });
3381 for (buffer, edits) in linked_edits {
3382 buffer.update(cx, |buffer, cx| {
3383 let snapshot = buffer.snapshot();
3384 let edits = edits
3385 .into_iter()
3386 .map(|(range, text)| {
3387 use text::ToPoint as TP;
3388 let end_point = TP::to_point(&range.end, &snapshot);
3389 let start_point = TP::to_point(&range.start, &snapshot);
3390 (start_point..end_point, text)
3391 })
3392 .sorted_by_key(|(range, _)| range.start)
3393 .collect::<Vec<_>>();
3394 buffer.edit(edits, None, cx);
3395 })
3396 }
3397 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3398 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3399 let snapshot = this.buffer.read(cx).read(cx);
3400 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3401 .zip(new_selection_deltas)
3402 .map(|(selection, delta)| Selection {
3403 id: selection.id,
3404 start: selection.start + delta,
3405 end: selection.end + delta,
3406 reversed: selection.reversed,
3407 goal: SelectionGoal::None,
3408 })
3409 .collect::<Vec<_>>();
3410
3411 let mut i = 0;
3412 for (position, delta, selection_id, pair) in new_autoclose_regions {
3413 let position = position.to_offset(&snapshot) + delta;
3414 let start = snapshot.anchor_before(position);
3415 let end = snapshot.anchor_after(position);
3416 while let Some(existing_state) = this.autoclose_regions.get(i) {
3417 match existing_state.range.start.cmp(&start, &snapshot) {
3418 Ordering::Less => i += 1,
3419 Ordering::Greater => break,
3420 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3421 Ordering::Less => i += 1,
3422 Ordering::Equal => break,
3423 Ordering::Greater => break,
3424 },
3425 }
3426 }
3427 this.autoclose_regions.insert(
3428 i,
3429 AutocloseRegion {
3430 selection_id,
3431 range: start..end,
3432 pair,
3433 },
3434 );
3435 }
3436
3437 drop(snapshot);
3438 let had_active_inline_completion = this.has_active_inline_completion(cx);
3439 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3440 s.select(new_selections)
3441 });
3442
3443 if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
3444 if let Some(on_type_format_task) =
3445 this.trigger_on_type_formatting(text.to_string(), cx)
3446 {
3447 on_type_format_task.detach_and_log_err(cx);
3448 }
3449 }
3450
3451 let editor_settings = EditorSettings::get_global(cx);
3452 if bracket_inserted
3453 && (editor_settings.auto_signature_help
3454 || editor_settings.show_signature_help_after_edits)
3455 {
3456 this.show_signature_help(&ShowSignatureHelp, cx);
3457 }
3458
3459 let trigger_in_words = !had_active_inline_completion;
3460 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3461 linked_editing_ranges::refresh_linked_ranges(this, cx);
3462 this.refresh_inline_completion(true, false, cx);
3463 });
3464 }
3465
3466 fn find_possible_emoji_shortcode_at_position(
3467 snapshot: &MultiBufferSnapshot,
3468 position: Point,
3469 ) -> Option<String> {
3470 let mut chars = Vec::new();
3471 let mut found_colon = false;
3472 for char in snapshot.reversed_chars_at(position).take(100) {
3473 // Found a possible emoji shortcode in the middle of the buffer
3474 if found_colon {
3475 if char.is_whitespace() {
3476 chars.reverse();
3477 return Some(chars.iter().collect());
3478 }
3479 // If the previous character is not a whitespace, we are in the middle of a word
3480 // and we only want to complete the shortcode if the word is made up of other emojis
3481 let mut containing_word = String::new();
3482 for ch in snapshot
3483 .reversed_chars_at(position)
3484 .skip(chars.len() + 1)
3485 .take(100)
3486 {
3487 if ch.is_whitespace() {
3488 break;
3489 }
3490 containing_word.push(ch);
3491 }
3492 let containing_word = containing_word.chars().rev().collect::<String>();
3493 if util::word_consists_of_emojis(containing_word.as_str()) {
3494 chars.reverse();
3495 return Some(chars.iter().collect());
3496 }
3497 }
3498
3499 if char.is_whitespace() || !char.is_ascii() {
3500 return None;
3501 }
3502 if char == ':' {
3503 found_colon = true;
3504 } else {
3505 chars.push(char);
3506 }
3507 }
3508 // Found a possible emoji shortcode at the beginning of the buffer
3509 chars.reverse();
3510 Some(chars.iter().collect())
3511 }
3512
3513 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3514 self.transact(cx, |this, cx| {
3515 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3516 let selections = this.selections.all::<usize>(cx);
3517 let multi_buffer = this.buffer.read(cx);
3518 let buffer = multi_buffer.snapshot(cx);
3519 selections
3520 .iter()
3521 .map(|selection| {
3522 let start_point = selection.start.to_point(&buffer);
3523 let mut indent =
3524 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3525 indent.len = cmp::min(indent.len, start_point.column);
3526 let start = selection.start;
3527 let end = selection.end;
3528 let selection_is_empty = start == end;
3529 let language_scope = buffer.language_scope_at(start);
3530 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3531 &language_scope
3532 {
3533 let leading_whitespace_len = buffer
3534 .reversed_chars_at(start)
3535 .take_while(|c| c.is_whitespace() && *c != '\n')
3536 .map(|c| c.len_utf8())
3537 .sum::<usize>();
3538
3539 let trailing_whitespace_len = buffer
3540 .chars_at(end)
3541 .take_while(|c| c.is_whitespace() && *c != '\n')
3542 .map(|c| c.len_utf8())
3543 .sum::<usize>();
3544
3545 let insert_extra_newline =
3546 language.brackets().any(|(pair, enabled)| {
3547 let pair_start = pair.start.trim_end();
3548 let pair_end = pair.end.trim_start();
3549
3550 enabled
3551 && pair.newline
3552 && buffer.contains_str_at(
3553 end + trailing_whitespace_len,
3554 pair_end,
3555 )
3556 && buffer.contains_str_at(
3557 (start - leading_whitespace_len)
3558 .saturating_sub(pair_start.len()),
3559 pair_start,
3560 )
3561 });
3562
3563 // Comment extension on newline is allowed only for cursor selections
3564 let comment_delimiter = maybe!({
3565 if !selection_is_empty {
3566 return None;
3567 }
3568
3569 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3570 return None;
3571 }
3572
3573 let delimiters = language.line_comment_prefixes();
3574 let max_len_of_delimiter =
3575 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3576 let (snapshot, range) =
3577 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3578
3579 let mut index_of_first_non_whitespace = 0;
3580 let comment_candidate = snapshot
3581 .chars_for_range(range)
3582 .skip_while(|c| {
3583 let should_skip = c.is_whitespace();
3584 if should_skip {
3585 index_of_first_non_whitespace += 1;
3586 }
3587 should_skip
3588 })
3589 .take(max_len_of_delimiter)
3590 .collect::<String>();
3591 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3592 comment_candidate.starts_with(comment_prefix.as_ref())
3593 })?;
3594 let cursor_is_placed_after_comment_marker =
3595 index_of_first_non_whitespace + comment_prefix.len()
3596 <= start_point.column as usize;
3597 if cursor_is_placed_after_comment_marker {
3598 Some(comment_prefix.clone())
3599 } else {
3600 None
3601 }
3602 });
3603 (comment_delimiter, insert_extra_newline)
3604 } else {
3605 (None, false)
3606 };
3607
3608 let capacity_for_delimiter = comment_delimiter
3609 .as_deref()
3610 .map(str::len)
3611 .unwrap_or_default();
3612 let mut new_text =
3613 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3614 new_text.push('\n');
3615 new_text.extend(indent.chars());
3616 if let Some(delimiter) = &comment_delimiter {
3617 new_text.push_str(delimiter);
3618 }
3619 if insert_extra_newline {
3620 new_text = new_text.repeat(2);
3621 }
3622
3623 let anchor = buffer.anchor_after(end);
3624 let new_selection = selection.map(|_| anchor);
3625 (
3626 (start..end, new_text),
3627 (insert_extra_newline, new_selection),
3628 )
3629 })
3630 .unzip()
3631 };
3632
3633 this.edit_with_autoindent(edits, cx);
3634 let buffer = this.buffer.read(cx).snapshot(cx);
3635 let new_selections = selection_fixup_info
3636 .into_iter()
3637 .map(|(extra_newline_inserted, new_selection)| {
3638 let mut cursor = new_selection.end.to_point(&buffer);
3639 if extra_newline_inserted {
3640 cursor.row -= 1;
3641 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3642 }
3643 new_selection.map(|_| cursor)
3644 })
3645 .collect();
3646
3647 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3648 this.refresh_inline_completion(true, false, cx);
3649 });
3650 }
3651
3652 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3653 let buffer = self.buffer.read(cx);
3654 let snapshot = buffer.snapshot(cx);
3655
3656 let mut edits = Vec::new();
3657 let mut rows = Vec::new();
3658
3659 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3660 let cursor = selection.head();
3661 let row = cursor.row;
3662
3663 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3664
3665 let newline = "\n".to_string();
3666 edits.push((start_of_line..start_of_line, newline));
3667
3668 rows.push(row + rows_inserted as u32);
3669 }
3670
3671 self.transact(cx, |editor, cx| {
3672 editor.edit(edits, cx);
3673
3674 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3675 let mut index = 0;
3676 s.move_cursors_with(|map, _, _| {
3677 let row = rows[index];
3678 index += 1;
3679
3680 let point = Point::new(row, 0);
3681 let boundary = map.next_line_boundary(point).1;
3682 let clipped = map.clip_point(boundary, Bias::Left);
3683
3684 (clipped, SelectionGoal::None)
3685 });
3686 });
3687
3688 let mut indent_edits = Vec::new();
3689 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3690 for row in rows {
3691 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3692 for (row, indent) in indents {
3693 if indent.len == 0 {
3694 continue;
3695 }
3696
3697 let text = match indent.kind {
3698 IndentKind::Space => " ".repeat(indent.len as usize),
3699 IndentKind::Tab => "\t".repeat(indent.len as usize),
3700 };
3701 let point = Point::new(row.0, 0);
3702 indent_edits.push((point..point, text));
3703 }
3704 }
3705 editor.edit(indent_edits, cx);
3706 });
3707 }
3708
3709 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3710 let buffer = self.buffer.read(cx);
3711 let snapshot = buffer.snapshot(cx);
3712
3713 let mut edits = Vec::new();
3714 let mut rows = Vec::new();
3715 let mut rows_inserted = 0;
3716
3717 for selection in self.selections.all_adjusted(cx) {
3718 let cursor = selection.head();
3719 let row = cursor.row;
3720
3721 let point = Point::new(row + 1, 0);
3722 let start_of_line = snapshot.clip_point(point, Bias::Left);
3723
3724 let newline = "\n".to_string();
3725 edits.push((start_of_line..start_of_line, newline));
3726
3727 rows_inserted += 1;
3728 rows.push(row + rows_inserted);
3729 }
3730
3731 self.transact(cx, |editor, cx| {
3732 editor.edit(edits, cx);
3733
3734 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3735 let mut index = 0;
3736 s.move_cursors_with(|map, _, _| {
3737 let row = rows[index];
3738 index += 1;
3739
3740 let point = Point::new(row, 0);
3741 let boundary = map.next_line_boundary(point).1;
3742 let clipped = map.clip_point(boundary, Bias::Left);
3743
3744 (clipped, SelectionGoal::None)
3745 });
3746 });
3747
3748 let mut indent_edits = Vec::new();
3749 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3750 for row in rows {
3751 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3752 for (row, indent) in indents {
3753 if indent.len == 0 {
3754 continue;
3755 }
3756
3757 let text = match indent.kind {
3758 IndentKind::Space => " ".repeat(indent.len as usize),
3759 IndentKind::Tab => "\t".repeat(indent.len as usize),
3760 };
3761 let point = Point::new(row.0, 0);
3762 indent_edits.push((point..point, text));
3763 }
3764 }
3765 editor.edit(indent_edits, cx);
3766 });
3767 }
3768
3769 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3770 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3771 original_indent_columns: Vec::new(),
3772 });
3773 self.insert_with_autoindent_mode(text, autoindent, cx);
3774 }
3775
3776 fn insert_with_autoindent_mode(
3777 &mut self,
3778 text: &str,
3779 autoindent_mode: Option<AutoindentMode>,
3780 cx: &mut ViewContext<Self>,
3781 ) {
3782 if self.read_only(cx) {
3783 return;
3784 }
3785
3786 let text: Arc<str> = text.into();
3787 self.transact(cx, |this, cx| {
3788 let old_selections = this.selections.all_adjusted(cx);
3789 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3790 let anchors = {
3791 let snapshot = buffer.read(cx);
3792 old_selections
3793 .iter()
3794 .map(|s| {
3795 let anchor = snapshot.anchor_after(s.head());
3796 s.map(|_| anchor)
3797 })
3798 .collect::<Vec<_>>()
3799 };
3800 buffer.edit(
3801 old_selections
3802 .iter()
3803 .map(|s| (s.start..s.end, text.clone())),
3804 autoindent_mode,
3805 cx,
3806 );
3807 anchors
3808 });
3809
3810 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3811 s.select_anchors(selection_anchors);
3812 })
3813 });
3814 }
3815
3816 fn trigger_completion_on_input(
3817 &mut self,
3818 text: &str,
3819 trigger_in_words: bool,
3820 cx: &mut ViewContext<Self>,
3821 ) {
3822 if self.is_completion_trigger(text, trigger_in_words, cx) {
3823 self.show_completions(
3824 &ShowCompletions {
3825 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3826 },
3827 cx,
3828 );
3829 } else {
3830 self.hide_context_menu(cx);
3831 }
3832 }
3833
3834 fn is_completion_trigger(
3835 &self,
3836 text: &str,
3837 trigger_in_words: bool,
3838 cx: &mut ViewContext<Self>,
3839 ) -> bool {
3840 let position = self.selections.newest_anchor().head();
3841 let multibuffer = self.buffer.read(cx);
3842 let Some(buffer) = position
3843 .buffer_id
3844 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3845 else {
3846 return false;
3847 };
3848
3849 if let Some(completion_provider) = &self.completion_provider {
3850 completion_provider.is_completion_trigger(
3851 &buffer,
3852 position.text_anchor,
3853 text,
3854 trigger_in_words,
3855 cx,
3856 )
3857 } else {
3858 false
3859 }
3860 }
3861
3862 /// If any empty selections is touching the start of its innermost containing autoclose
3863 /// region, expand it to select the brackets.
3864 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3865 let selections = self.selections.all::<usize>(cx);
3866 let buffer = self.buffer.read(cx).read(cx);
3867 let new_selections = self
3868 .selections_with_autoclose_regions(selections, &buffer)
3869 .map(|(mut selection, region)| {
3870 if !selection.is_empty() {
3871 return selection;
3872 }
3873
3874 if let Some(region) = region {
3875 let mut range = region.range.to_offset(&buffer);
3876 if selection.start == range.start && range.start >= region.pair.start.len() {
3877 range.start -= region.pair.start.len();
3878 if buffer.contains_str_at(range.start, ®ion.pair.start)
3879 && buffer.contains_str_at(range.end, ®ion.pair.end)
3880 {
3881 range.end += region.pair.end.len();
3882 selection.start = range.start;
3883 selection.end = range.end;
3884
3885 return selection;
3886 }
3887 }
3888 }
3889
3890 let always_treat_brackets_as_autoclosed = buffer
3891 .settings_at(selection.start, cx)
3892 .always_treat_brackets_as_autoclosed;
3893
3894 if !always_treat_brackets_as_autoclosed {
3895 return selection;
3896 }
3897
3898 if let Some(scope) = buffer.language_scope_at(selection.start) {
3899 for (pair, enabled) in scope.brackets() {
3900 if !enabled || !pair.close {
3901 continue;
3902 }
3903
3904 if buffer.contains_str_at(selection.start, &pair.end) {
3905 let pair_start_len = pair.start.len();
3906 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3907 {
3908 selection.start -= pair_start_len;
3909 selection.end += pair.end.len();
3910
3911 return selection;
3912 }
3913 }
3914 }
3915 }
3916
3917 selection
3918 })
3919 .collect();
3920
3921 drop(buffer);
3922 self.change_selections(None, cx, |selections| selections.select(new_selections));
3923 }
3924
3925 /// Iterate the given selections, and for each one, find the smallest surrounding
3926 /// autoclose region. This uses the ordering of the selections and the autoclose
3927 /// regions to avoid repeated comparisons.
3928 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3929 &'a self,
3930 selections: impl IntoIterator<Item = Selection<D>>,
3931 buffer: &'a MultiBufferSnapshot,
3932 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3933 let mut i = 0;
3934 let mut regions = self.autoclose_regions.as_slice();
3935 selections.into_iter().map(move |selection| {
3936 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3937
3938 let mut enclosing = None;
3939 while let Some(pair_state) = regions.get(i) {
3940 if pair_state.range.end.to_offset(buffer) < range.start {
3941 regions = ®ions[i + 1..];
3942 i = 0;
3943 } else if pair_state.range.start.to_offset(buffer) > range.end {
3944 break;
3945 } else {
3946 if pair_state.selection_id == selection.id {
3947 enclosing = Some(pair_state);
3948 }
3949 i += 1;
3950 }
3951 }
3952
3953 (selection.clone(), enclosing)
3954 })
3955 }
3956
3957 /// Remove any autoclose regions that no longer contain their selection.
3958 fn invalidate_autoclose_regions(
3959 &mut self,
3960 mut selections: &[Selection<Anchor>],
3961 buffer: &MultiBufferSnapshot,
3962 ) {
3963 self.autoclose_regions.retain(|state| {
3964 let mut i = 0;
3965 while let Some(selection) = selections.get(i) {
3966 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3967 selections = &selections[1..];
3968 continue;
3969 }
3970 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3971 break;
3972 }
3973 if selection.id == state.selection_id {
3974 return true;
3975 } else {
3976 i += 1;
3977 }
3978 }
3979 false
3980 });
3981 }
3982
3983 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3984 let offset = position.to_offset(buffer);
3985 let (word_range, kind) = buffer.surrounding_word(offset, true);
3986 if offset > word_range.start && kind == Some(CharKind::Word) {
3987 Some(
3988 buffer
3989 .text_for_range(word_range.start..offset)
3990 .collect::<String>(),
3991 )
3992 } else {
3993 None
3994 }
3995 }
3996
3997 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3998 self.refresh_inlay_hints(
3999 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
4000 cx,
4001 );
4002 }
4003
4004 pub fn inlay_hints_enabled(&self) -> bool {
4005 self.inlay_hint_cache.enabled
4006 }
4007
4008 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
4009 if self.project.is_none() || self.mode != EditorMode::Full {
4010 return;
4011 }
4012
4013 let reason_description = reason.description();
4014 let ignore_debounce = matches!(
4015 reason,
4016 InlayHintRefreshReason::SettingsChange(_)
4017 | InlayHintRefreshReason::Toggle(_)
4018 | InlayHintRefreshReason::ExcerptsRemoved(_)
4019 );
4020 let (invalidate_cache, required_languages) = match reason {
4021 InlayHintRefreshReason::Toggle(enabled) => {
4022 self.inlay_hint_cache.enabled = enabled;
4023 if enabled {
4024 (InvalidationStrategy::RefreshRequested, None)
4025 } else {
4026 self.inlay_hint_cache.clear();
4027 self.splice_inlays(
4028 self.visible_inlay_hints(cx)
4029 .iter()
4030 .map(|inlay| inlay.id)
4031 .collect(),
4032 Vec::new(),
4033 cx,
4034 );
4035 return;
4036 }
4037 }
4038 InlayHintRefreshReason::SettingsChange(new_settings) => {
4039 match self.inlay_hint_cache.update_settings(
4040 &self.buffer,
4041 new_settings,
4042 self.visible_inlay_hints(cx),
4043 cx,
4044 ) {
4045 ControlFlow::Break(Some(InlaySplice {
4046 to_remove,
4047 to_insert,
4048 })) => {
4049 self.splice_inlays(to_remove, to_insert, cx);
4050 return;
4051 }
4052 ControlFlow::Break(None) => return,
4053 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4054 }
4055 }
4056 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4057 if let Some(InlaySplice {
4058 to_remove,
4059 to_insert,
4060 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4061 {
4062 self.splice_inlays(to_remove, to_insert, cx);
4063 }
4064 return;
4065 }
4066 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4067 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4068 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4069 }
4070 InlayHintRefreshReason::RefreshRequested => {
4071 (InvalidationStrategy::RefreshRequested, None)
4072 }
4073 };
4074
4075 if let Some(InlaySplice {
4076 to_remove,
4077 to_insert,
4078 }) = self.inlay_hint_cache.spawn_hint_refresh(
4079 reason_description,
4080 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4081 invalidate_cache,
4082 ignore_debounce,
4083 cx,
4084 ) {
4085 self.splice_inlays(to_remove, to_insert, cx);
4086 }
4087 }
4088
4089 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4090 self.display_map
4091 .read(cx)
4092 .current_inlays()
4093 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4094 .cloned()
4095 .collect()
4096 }
4097
4098 pub fn excerpts_for_inlay_hints_query(
4099 &self,
4100 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4101 cx: &mut ViewContext<Editor>,
4102 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4103 let Some(project) = self.project.as_ref() else {
4104 return HashMap::default();
4105 };
4106 let project = project.read(cx);
4107 let multi_buffer = self.buffer().read(cx);
4108 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4109 let multi_buffer_visible_start = self
4110 .scroll_manager
4111 .anchor()
4112 .anchor
4113 .to_point(&multi_buffer_snapshot);
4114 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4115 multi_buffer_visible_start
4116 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4117 Bias::Left,
4118 );
4119 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4120 multi_buffer
4121 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4122 .into_iter()
4123 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4124 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4125 let buffer = buffer_handle.read(cx);
4126 let buffer_file = project::File::from_dyn(buffer.file())?;
4127 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4128 let worktree_entry = buffer_worktree
4129 .read(cx)
4130 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4131 if worktree_entry.is_ignored {
4132 return None;
4133 }
4134
4135 let language = buffer.language()?;
4136 if let Some(restrict_to_languages) = restrict_to_languages {
4137 if !restrict_to_languages.contains(language) {
4138 return None;
4139 }
4140 }
4141 Some((
4142 excerpt_id,
4143 (
4144 buffer_handle,
4145 buffer.version().clone(),
4146 excerpt_visible_range,
4147 ),
4148 ))
4149 })
4150 .collect()
4151 }
4152
4153 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4154 TextLayoutDetails {
4155 text_system: cx.text_system().clone(),
4156 editor_style: self.style.clone().unwrap(),
4157 rem_size: cx.rem_size(),
4158 scroll_anchor: self.scroll_manager.anchor(),
4159 visible_rows: self.visible_line_count(),
4160 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4161 }
4162 }
4163
4164 fn splice_inlays(
4165 &self,
4166 to_remove: Vec<InlayId>,
4167 to_insert: Vec<Inlay>,
4168 cx: &mut ViewContext<Self>,
4169 ) {
4170 self.display_map.update(cx, |display_map, cx| {
4171 display_map.splice_inlays(to_remove, to_insert, cx);
4172 });
4173 cx.notify();
4174 }
4175
4176 fn trigger_on_type_formatting(
4177 &self,
4178 input: String,
4179 cx: &mut ViewContext<Self>,
4180 ) -> Option<Task<Result<()>>> {
4181 if input.len() != 1 {
4182 return None;
4183 }
4184
4185 let project = self.project.as_ref()?;
4186 let position = self.selections.newest_anchor().head();
4187 let (buffer, buffer_position) = self
4188 .buffer
4189 .read(cx)
4190 .text_anchor_for_position(position, cx)?;
4191
4192 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4193 // hence we do LSP request & edit on host side only — add formats to host's history.
4194 let push_to_lsp_host_history = true;
4195 // If this is not the host, append its history with new edits.
4196 let push_to_client_history = project.read(cx).is_via_collab();
4197
4198 let on_type_formatting = project.update(cx, |project, cx| {
4199 project.on_type_format(
4200 buffer.clone(),
4201 buffer_position,
4202 input,
4203 push_to_lsp_host_history,
4204 cx,
4205 )
4206 });
4207 Some(cx.spawn(|editor, mut cx| async move {
4208 if let Some(transaction) = on_type_formatting.await? {
4209 if push_to_client_history {
4210 buffer
4211 .update(&mut cx, |buffer, _| {
4212 buffer.push_transaction(transaction, Instant::now());
4213 })
4214 .ok();
4215 }
4216 editor.update(&mut cx, |editor, cx| {
4217 editor.refresh_document_highlights(cx);
4218 })?;
4219 }
4220 Ok(())
4221 }))
4222 }
4223
4224 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4225 if self.pending_rename.is_some() {
4226 return;
4227 }
4228
4229 let Some(provider) = self.completion_provider.as_ref() else {
4230 return;
4231 };
4232
4233 let position = self.selections.newest_anchor().head();
4234 let (buffer, buffer_position) =
4235 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4236 output
4237 } else {
4238 return;
4239 };
4240
4241 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4242 let is_followup_invoke = {
4243 let context_menu_state = self.context_menu.read();
4244 matches!(
4245 context_menu_state.deref(),
4246 Some(ContextMenu::Completions(_))
4247 )
4248 };
4249 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4250 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4251 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
4252 CompletionTriggerKind::TRIGGER_CHARACTER
4253 }
4254
4255 _ => CompletionTriggerKind::INVOKED,
4256 };
4257 let completion_context = CompletionContext {
4258 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4259 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4260 Some(String::from(trigger))
4261 } else {
4262 None
4263 }
4264 }),
4265 trigger_kind,
4266 };
4267 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4268 let sort_completions = provider.sort_completions();
4269
4270 let id = post_inc(&mut self.next_completion_id);
4271 let task = cx.spawn(|this, mut cx| {
4272 async move {
4273 this.update(&mut cx, |this, _| {
4274 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4275 })?;
4276 let completions = completions.await.log_err();
4277 let menu = if let Some(completions) = completions {
4278 let mut menu = CompletionsMenu {
4279 id,
4280 sort_completions,
4281 initial_position: position,
4282 match_candidates: completions
4283 .iter()
4284 .enumerate()
4285 .map(|(id, completion)| {
4286 StringMatchCandidate::new(
4287 id,
4288 completion.label.text[completion.label.filter_range.clone()]
4289 .into(),
4290 )
4291 })
4292 .collect(),
4293 buffer: buffer.clone(),
4294 completions: Arc::new(RwLock::new(completions.into())),
4295 matches: Vec::new().into(),
4296 selected_item: 0,
4297 scroll_handle: UniformListScrollHandle::new(),
4298 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4299 DebouncedDelay::new(),
4300 )),
4301 };
4302 menu.filter(query.as_deref(), cx.background_executor().clone())
4303 .await;
4304
4305 if menu.matches.is_empty() {
4306 None
4307 } else {
4308 this.update(&mut cx, |editor, cx| {
4309 let completions = menu.completions.clone();
4310 let matches = menu.matches.clone();
4311
4312 let delay_ms = EditorSettings::get_global(cx)
4313 .completion_documentation_secondary_query_debounce;
4314 let delay = Duration::from_millis(delay_ms);
4315 editor
4316 .completion_documentation_pre_resolve_debounce
4317 .fire_new(delay, cx, |editor, cx| {
4318 CompletionsMenu::pre_resolve_completion_documentation(
4319 buffer,
4320 completions,
4321 matches,
4322 editor,
4323 cx,
4324 )
4325 });
4326 })
4327 .ok();
4328 Some(menu)
4329 }
4330 } else {
4331 None
4332 };
4333
4334 this.update(&mut cx, |this, cx| {
4335 let mut context_menu = this.context_menu.write();
4336 match context_menu.as_ref() {
4337 None => {}
4338
4339 Some(ContextMenu::Completions(prev_menu)) => {
4340 if prev_menu.id > id {
4341 return;
4342 }
4343 }
4344
4345 _ => return,
4346 }
4347
4348 if this.focus_handle.is_focused(cx) && menu.is_some() {
4349 let menu = menu.unwrap();
4350 *context_menu = Some(ContextMenu::Completions(menu));
4351 drop(context_menu);
4352 this.discard_inline_completion(false, cx);
4353 cx.notify();
4354 } else if this.completion_tasks.len() <= 1 {
4355 // If there are no more completion tasks and the last menu was
4356 // empty, we should hide it. If it was already hidden, we should
4357 // also show the copilot completion when available.
4358 drop(context_menu);
4359 if this.hide_context_menu(cx).is_none() {
4360 this.update_visible_inline_completion(cx);
4361 }
4362 }
4363 })?;
4364
4365 Ok::<_, anyhow::Error>(())
4366 }
4367 .log_err()
4368 });
4369
4370 self.completion_tasks.push((id, task));
4371 }
4372
4373 pub fn confirm_completion(
4374 &mut self,
4375 action: &ConfirmCompletion,
4376 cx: &mut ViewContext<Self>,
4377 ) -> Option<Task<Result<()>>> {
4378 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4379 }
4380
4381 pub fn compose_completion(
4382 &mut self,
4383 action: &ComposeCompletion,
4384 cx: &mut ViewContext<Self>,
4385 ) -> Option<Task<Result<()>>> {
4386 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4387 }
4388
4389 fn do_completion(
4390 &mut self,
4391 item_ix: Option<usize>,
4392 intent: CompletionIntent,
4393 cx: &mut ViewContext<Editor>,
4394 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4395 use language::ToOffset as _;
4396
4397 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4398 menu
4399 } else {
4400 return None;
4401 };
4402
4403 let mat = completions_menu
4404 .matches
4405 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4406 let buffer_handle = completions_menu.buffer;
4407 let completions = completions_menu.completions.read();
4408 let completion = completions.get(mat.candidate_id)?;
4409 cx.stop_propagation();
4410
4411 let snippet;
4412 let text;
4413
4414 if completion.is_snippet() {
4415 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4416 text = snippet.as_ref().unwrap().text.clone();
4417 } else {
4418 snippet = None;
4419 text = completion.new_text.clone();
4420 };
4421 let selections = self.selections.all::<usize>(cx);
4422 let buffer = buffer_handle.read(cx);
4423 let old_range = completion.old_range.to_offset(buffer);
4424 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4425
4426 let newest_selection = self.selections.newest_anchor();
4427 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4428 return None;
4429 }
4430
4431 let lookbehind = newest_selection
4432 .start
4433 .text_anchor
4434 .to_offset(buffer)
4435 .saturating_sub(old_range.start);
4436 let lookahead = old_range
4437 .end
4438 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4439 let mut common_prefix_len = old_text
4440 .bytes()
4441 .zip(text.bytes())
4442 .take_while(|(a, b)| a == b)
4443 .count();
4444
4445 let snapshot = self.buffer.read(cx).snapshot(cx);
4446 let mut range_to_replace: Option<Range<isize>> = None;
4447 let mut ranges = Vec::new();
4448 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4449 for selection in &selections {
4450 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4451 let start = selection.start.saturating_sub(lookbehind);
4452 let end = selection.end + lookahead;
4453 if selection.id == newest_selection.id {
4454 range_to_replace = Some(
4455 ((start + common_prefix_len) as isize - selection.start as isize)
4456 ..(end as isize - selection.start as isize),
4457 );
4458 }
4459 ranges.push(start + common_prefix_len..end);
4460 } else {
4461 common_prefix_len = 0;
4462 ranges.clear();
4463 ranges.extend(selections.iter().map(|s| {
4464 if s.id == newest_selection.id {
4465 range_to_replace = Some(
4466 old_range.start.to_offset_utf16(&snapshot).0 as isize
4467 - selection.start as isize
4468 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4469 - selection.start as isize,
4470 );
4471 old_range.clone()
4472 } else {
4473 s.start..s.end
4474 }
4475 }));
4476 break;
4477 }
4478 if !self.linked_edit_ranges.is_empty() {
4479 let start_anchor = snapshot.anchor_before(selection.head());
4480 let end_anchor = snapshot.anchor_after(selection.tail());
4481 if let Some(ranges) = self
4482 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4483 {
4484 for (buffer, edits) in ranges {
4485 linked_edits.entry(buffer.clone()).or_default().extend(
4486 edits
4487 .into_iter()
4488 .map(|range| (range, text[common_prefix_len..].to_owned())),
4489 );
4490 }
4491 }
4492 }
4493 }
4494 let text = &text[common_prefix_len..];
4495
4496 cx.emit(EditorEvent::InputHandled {
4497 utf16_range_to_replace: range_to_replace,
4498 text: text.into(),
4499 });
4500
4501 self.transact(cx, |this, cx| {
4502 if let Some(mut snippet) = snippet {
4503 snippet.text = text.to_string();
4504 for tabstop in snippet.tabstops.iter_mut().flatten() {
4505 tabstop.start -= common_prefix_len as isize;
4506 tabstop.end -= common_prefix_len as isize;
4507 }
4508
4509 this.insert_snippet(&ranges, snippet, cx).log_err();
4510 } else {
4511 this.buffer.update(cx, |buffer, cx| {
4512 buffer.edit(
4513 ranges.iter().map(|range| (range.clone(), text)),
4514 this.autoindent_mode.clone(),
4515 cx,
4516 );
4517 });
4518 }
4519 for (buffer, edits) in linked_edits {
4520 buffer.update(cx, |buffer, cx| {
4521 let snapshot = buffer.snapshot();
4522 let edits = edits
4523 .into_iter()
4524 .map(|(range, text)| {
4525 use text::ToPoint as TP;
4526 let end_point = TP::to_point(&range.end, &snapshot);
4527 let start_point = TP::to_point(&range.start, &snapshot);
4528 (start_point..end_point, text)
4529 })
4530 .sorted_by_key(|(range, _)| range.start)
4531 .collect::<Vec<_>>();
4532 buffer.edit(edits, None, cx);
4533 })
4534 }
4535
4536 this.refresh_inline_completion(true, false, cx);
4537 });
4538
4539 let show_new_completions_on_confirm = completion
4540 .confirm
4541 .as_ref()
4542 .map_or(false, |confirm| confirm(intent, cx));
4543 if show_new_completions_on_confirm {
4544 self.show_completions(&ShowCompletions { trigger: None }, cx);
4545 }
4546
4547 let provider = self.completion_provider.as_ref()?;
4548 let apply_edits = provider.apply_additional_edits_for_completion(
4549 buffer_handle,
4550 completion.clone(),
4551 true,
4552 cx,
4553 );
4554
4555 let editor_settings = EditorSettings::get_global(cx);
4556 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4557 // After the code completion is finished, users often want to know what signatures are needed.
4558 // so we should automatically call signature_help
4559 self.show_signature_help(&ShowSignatureHelp, cx);
4560 }
4561
4562 Some(cx.foreground_executor().spawn(async move {
4563 apply_edits.await?;
4564 Ok(())
4565 }))
4566 }
4567
4568 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4569 let mut context_menu = self.context_menu.write();
4570 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4571 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4572 // Toggle if we're selecting the same one
4573 *context_menu = None;
4574 cx.notify();
4575 return;
4576 } else {
4577 // Otherwise, clear it and start a new one
4578 *context_menu = None;
4579 cx.notify();
4580 }
4581 }
4582 drop(context_menu);
4583 let snapshot = self.snapshot(cx);
4584 let deployed_from_indicator = action.deployed_from_indicator;
4585 let mut task = self.code_actions_task.take();
4586 let action = action.clone();
4587 cx.spawn(|editor, mut cx| async move {
4588 while let Some(prev_task) = task {
4589 prev_task.await.log_err();
4590 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4591 }
4592
4593 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4594 if editor.focus_handle.is_focused(cx) {
4595 let multibuffer_point = action
4596 .deployed_from_indicator
4597 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4598 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4599 let (buffer, buffer_row) = snapshot
4600 .buffer_snapshot
4601 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4602 .and_then(|(buffer_snapshot, range)| {
4603 editor
4604 .buffer
4605 .read(cx)
4606 .buffer(buffer_snapshot.remote_id())
4607 .map(|buffer| (buffer, range.start.row))
4608 })?;
4609 let (_, code_actions) = editor
4610 .available_code_actions
4611 .clone()
4612 .and_then(|(location, code_actions)| {
4613 let snapshot = location.buffer.read(cx).snapshot();
4614 let point_range = location.range.to_point(&snapshot);
4615 let point_range = point_range.start.row..=point_range.end.row;
4616 if point_range.contains(&buffer_row) {
4617 Some((location, code_actions))
4618 } else {
4619 None
4620 }
4621 })
4622 .unzip();
4623 let buffer_id = buffer.read(cx).remote_id();
4624 let tasks = editor
4625 .tasks
4626 .get(&(buffer_id, buffer_row))
4627 .map(|t| Arc::new(t.to_owned()));
4628 if tasks.is_none() && code_actions.is_none() {
4629 return None;
4630 }
4631
4632 editor.completion_tasks.clear();
4633 editor.discard_inline_completion(false, cx);
4634 let task_context =
4635 tasks
4636 .as_ref()
4637 .zip(editor.project.clone())
4638 .map(|(tasks, project)| {
4639 let position = Point::new(buffer_row, tasks.column);
4640 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4641 let location = Location {
4642 buffer: buffer.clone(),
4643 range: range_start..range_start,
4644 };
4645 // Fill in the environmental variables from the tree-sitter captures
4646 let mut captured_task_variables = TaskVariables::default();
4647 for (capture_name, value) in tasks.extra_variables.clone() {
4648 captured_task_variables.insert(
4649 task::VariableName::Custom(capture_name.into()),
4650 value.clone(),
4651 );
4652 }
4653 project.update(cx, |project, cx| {
4654 project.task_context_for_location(
4655 captured_task_variables,
4656 location,
4657 cx,
4658 )
4659 })
4660 });
4661
4662 Some(cx.spawn(|editor, mut cx| async move {
4663 let task_context = match task_context {
4664 Some(task_context) => task_context.await,
4665 None => None,
4666 };
4667 let resolved_tasks =
4668 tasks.zip(task_context).map(|(tasks, task_context)| {
4669 Arc::new(ResolvedTasks {
4670 templates: tasks
4671 .templates
4672 .iter()
4673 .filter_map(|(kind, template)| {
4674 template
4675 .resolve_task(&kind.to_id_base(), &task_context)
4676 .map(|task| (kind.clone(), task))
4677 })
4678 .collect(),
4679 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4680 multibuffer_point.row,
4681 tasks.column,
4682 )),
4683 })
4684 });
4685 let spawn_straight_away = resolved_tasks
4686 .as_ref()
4687 .map_or(false, |tasks| tasks.templates.len() == 1)
4688 && code_actions
4689 .as_ref()
4690 .map_or(true, |actions| actions.is_empty());
4691 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4692 *editor.context_menu.write() =
4693 Some(ContextMenu::CodeActions(CodeActionsMenu {
4694 buffer,
4695 actions: CodeActionContents {
4696 tasks: resolved_tasks,
4697 actions: code_actions,
4698 },
4699 selected_item: Default::default(),
4700 scroll_handle: UniformListScrollHandle::default(),
4701 deployed_from_indicator,
4702 }));
4703 if spawn_straight_away {
4704 if let Some(task) = editor.confirm_code_action(
4705 &ConfirmCodeAction { item_ix: Some(0) },
4706 cx,
4707 ) {
4708 cx.notify();
4709 return task;
4710 }
4711 }
4712 cx.notify();
4713 Task::ready(Ok(()))
4714 }) {
4715 task.await
4716 } else {
4717 Ok(())
4718 }
4719 }))
4720 } else {
4721 Some(Task::ready(Ok(())))
4722 }
4723 })?;
4724 if let Some(task) = spawned_test_task {
4725 task.await?;
4726 }
4727
4728 Ok::<_, anyhow::Error>(())
4729 })
4730 .detach_and_log_err(cx);
4731 }
4732
4733 pub fn confirm_code_action(
4734 &mut self,
4735 action: &ConfirmCodeAction,
4736 cx: &mut ViewContext<Self>,
4737 ) -> Option<Task<Result<()>>> {
4738 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4739 menu
4740 } else {
4741 return None;
4742 };
4743 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4744 let action = actions_menu.actions.get(action_ix)?;
4745 let title = action.label();
4746 let buffer = actions_menu.buffer;
4747 let workspace = self.workspace()?;
4748
4749 match action {
4750 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4751 workspace.update(cx, |workspace, cx| {
4752 workspace::tasks::schedule_resolved_task(
4753 workspace,
4754 task_source_kind,
4755 resolved_task,
4756 false,
4757 cx,
4758 );
4759
4760 Some(Task::ready(Ok(())))
4761 })
4762 }
4763 CodeActionsItem::CodeAction {
4764 excerpt_id,
4765 action,
4766 provider,
4767 } => {
4768 let apply_code_action =
4769 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4770 let workspace = workspace.downgrade();
4771 Some(cx.spawn(|editor, cx| async move {
4772 let project_transaction = apply_code_action.await?;
4773 Self::open_project_transaction(
4774 &editor,
4775 workspace,
4776 project_transaction,
4777 title,
4778 cx,
4779 )
4780 .await
4781 }))
4782 }
4783 }
4784 }
4785
4786 pub async fn open_project_transaction(
4787 this: &WeakView<Editor>,
4788 workspace: WeakView<Workspace>,
4789 transaction: ProjectTransaction,
4790 title: String,
4791 mut cx: AsyncWindowContext,
4792 ) -> Result<()> {
4793 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4794 cx.update(|cx| {
4795 entries.sort_unstable_by_key(|(buffer, _)| {
4796 buffer.read(cx).file().map(|f| f.path().clone())
4797 });
4798 })?;
4799
4800 // If the project transaction's edits are all contained within this editor, then
4801 // avoid opening a new editor to display them.
4802
4803 if let Some((buffer, transaction)) = entries.first() {
4804 if entries.len() == 1 {
4805 let excerpt = this.update(&mut cx, |editor, cx| {
4806 editor
4807 .buffer()
4808 .read(cx)
4809 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4810 })?;
4811 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4812 if excerpted_buffer == *buffer {
4813 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4814 let excerpt_range = excerpt_range.to_offset(buffer);
4815 buffer
4816 .edited_ranges_for_transaction::<usize>(transaction)
4817 .all(|range| {
4818 excerpt_range.start <= range.start
4819 && excerpt_range.end >= range.end
4820 })
4821 })?;
4822
4823 if all_edits_within_excerpt {
4824 return Ok(());
4825 }
4826 }
4827 }
4828 }
4829 } else {
4830 return Ok(());
4831 }
4832
4833 let mut ranges_to_highlight = Vec::new();
4834 let excerpt_buffer = cx.new_model(|cx| {
4835 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4836 for (buffer_handle, transaction) in &entries {
4837 let buffer = buffer_handle.read(cx);
4838 ranges_to_highlight.extend(
4839 multibuffer.push_excerpts_with_context_lines(
4840 buffer_handle.clone(),
4841 buffer
4842 .edited_ranges_for_transaction::<usize>(transaction)
4843 .collect(),
4844 DEFAULT_MULTIBUFFER_CONTEXT,
4845 cx,
4846 ),
4847 );
4848 }
4849 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4850 multibuffer
4851 })?;
4852
4853 workspace.update(&mut cx, |workspace, cx| {
4854 let project = workspace.project().clone();
4855 let editor =
4856 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4857 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4858 editor.update(cx, |editor, cx| {
4859 editor.highlight_background::<Self>(
4860 &ranges_to_highlight,
4861 |theme| theme.editor_highlighted_line_background,
4862 cx,
4863 );
4864 });
4865 })?;
4866
4867 Ok(())
4868 }
4869
4870 pub fn push_code_action_provider(
4871 &mut self,
4872 provider: Arc<dyn CodeActionProvider>,
4873 cx: &mut ViewContext<Self>,
4874 ) {
4875 self.code_action_providers.push(provider);
4876 self.refresh_code_actions(cx);
4877 }
4878
4879 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4880 let buffer = self.buffer.read(cx);
4881 let newest_selection = self.selections.newest_anchor().clone();
4882 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4883 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4884 if start_buffer != end_buffer {
4885 return None;
4886 }
4887
4888 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4889 cx.background_executor()
4890 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4891 .await;
4892
4893 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4894 let providers = this.code_action_providers.clone();
4895 let tasks = this
4896 .code_action_providers
4897 .iter()
4898 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4899 .collect::<Vec<_>>();
4900 (providers, tasks)
4901 })?;
4902
4903 let mut actions = Vec::new();
4904 for (provider, provider_actions) in
4905 providers.into_iter().zip(future::join_all(tasks).await)
4906 {
4907 if let Some(provider_actions) = provider_actions.log_err() {
4908 actions.extend(provider_actions.into_iter().map(|action| {
4909 AvailableCodeAction {
4910 excerpt_id: newest_selection.start.excerpt_id,
4911 action,
4912 provider: provider.clone(),
4913 }
4914 }));
4915 }
4916 }
4917
4918 this.update(&mut cx, |this, cx| {
4919 this.available_code_actions = if actions.is_empty() {
4920 None
4921 } else {
4922 Some((
4923 Location {
4924 buffer: start_buffer,
4925 range: start..end,
4926 },
4927 actions.into(),
4928 ))
4929 };
4930 cx.notify();
4931 })
4932 }));
4933 None
4934 }
4935
4936 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4937 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4938 self.show_git_blame_inline = false;
4939
4940 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4941 cx.background_executor().timer(delay).await;
4942
4943 this.update(&mut cx, |this, cx| {
4944 this.show_git_blame_inline = true;
4945 cx.notify();
4946 })
4947 .log_err();
4948 }));
4949 }
4950 }
4951
4952 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4953 if self.pending_rename.is_some() {
4954 return None;
4955 }
4956
4957 let project = self.project.clone()?;
4958 let buffer = self.buffer.read(cx);
4959 let newest_selection = self.selections.newest_anchor().clone();
4960 let cursor_position = newest_selection.head();
4961 let (cursor_buffer, cursor_buffer_position) =
4962 buffer.text_anchor_for_position(cursor_position, cx)?;
4963 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4964 if cursor_buffer != tail_buffer {
4965 return None;
4966 }
4967
4968 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4969 cx.background_executor()
4970 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
4971 .await;
4972
4973 let highlights = if let Some(highlights) = project
4974 .update(&mut cx, |project, cx| {
4975 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4976 })
4977 .log_err()
4978 {
4979 highlights.await.log_err()
4980 } else {
4981 None
4982 };
4983
4984 if let Some(highlights) = highlights {
4985 this.update(&mut cx, |this, cx| {
4986 if this.pending_rename.is_some() {
4987 return;
4988 }
4989
4990 let buffer_id = cursor_position.buffer_id;
4991 let buffer = this.buffer.read(cx);
4992 if !buffer
4993 .text_anchor_for_position(cursor_position, cx)
4994 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4995 {
4996 return;
4997 }
4998
4999 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5000 let mut write_ranges = Vec::new();
5001 let mut read_ranges = Vec::new();
5002 for highlight in highlights {
5003 for (excerpt_id, excerpt_range) in
5004 buffer.excerpts_for_buffer(&cursor_buffer, cx)
5005 {
5006 let start = highlight
5007 .range
5008 .start
5009 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5010 let end = highlight
5011 .range
5012 .end
5013 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5014 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5015 continue;
5016 }
5017
5018 let range = Anchor {
5019 buffer_id,
5020 excerpt_id,
5021 text_anchor: start,
5022 }..Anchor {
5023 buffer_id,
5024 excerpt_id,
5025 text_anchor: end,
5026 };
5027 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5028 write_ranges.push(range);
5029 } else {
5030 read_ranges.push(range);
5031 }
5032 }
5033 }
5034
5035 this.highlight_background::<DocumentHighlightRead>(
5036 &read_ranges,
5037 |theme| theme.editor_document_highlight_read_background,
5038 cx,
5039 );
5040 this.highlight_background::<DocumentHighlightWrite>(
5041 &write_ranges,
5042 |theme| theme.editor_document_highlight_write_background,
5043 cx,
5044 );
5045 cx.notify();
5046 })
5047 .log_err();
5048 }
5049 }));
5050 None
5051 }
5052
5053 pub fn refresh_inline_completion(
5054 &mut self,
5055 debounce: bool,
5056 user_requested: bool,
5057 cx: &mut ViewContext<Self>,
5058 ) -> Option<()> {
5059 let provider = self.inline_completion_provider()?;
5060 let cursor = self.selections.newest_anchor().head();
5061 let (buffer, cursor_buffer_position) =
5062 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5063
5064 if !user_requested
5065 && (!self.enable_inline_completions
5066 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
5067 {
5068 self.discard_inline_completion(false, cx);
5069 return None;
5070 }
5071
5072 self.update_visible_inline_completion(cx);
5073 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
5074 Some(())
5075 }
5076
5077 fn cycle_inline_completion(
5078 &mut self,
5079 direction: Direction,
5080 cx: &mut ViewContext<Self>,
5081 ) -> Option<()> {
5082 let provider = self.inline_completion_provider()?;
5083 let cursor = self.selections.newest_anchor().head();
5084 let (buffer, cursor_buffer_position) =
5085 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5086 if !self.enable_inline_completions
5087 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5088 {
5089 return None;
5090 }
5091
5092 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5093 self.update_visible_inline_completion(cx);
5094
5095 Some(())
5096 }
5097
5098 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5099 if !self.has_active_inline_completion(cx) {
5100 self.refresh_inline_completion(false, true, cx);
5101 return;
5102 }
5103
5104 self.update_visible_inline_completion(cx);
5105 }
5106
5107 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5108 self.show_cursor_names(cx);
5109 }
5110
5111 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5112 self.show_cursor_names = true;
5113 cx.notify();
5114 cx.spawn(|this, mut cx| async move {
5115 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5116 this.update(&mut cx, |this, cx| {
5117 this.show_cursor_names = false;
5118 cx.notify()
5119 })
5120 .ok()
5121 })
5122 .detach();
5123 }
5124
5125 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5126 if self.has_active_inline_completion(cx) {
5127 self.cycle_inline_completion(Direction::Next, cx);
5128 } else {
5129 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5130 if is_copilot_disabled {
5131 cx.propagate();
5132 }
5133 }
5134 }
5135
5136 pub fn previous_inline_completion(
5137 &mut self,
5138 _: &PreviousInlineCompletion,
5139 cx: &mut ViewContext<Self>,
5140 ) {
5141 if self.has_active_inline_completion(cx) {
5142 self.cycle_inline_completion(Direction::Prev, cx);
5143 } else {
5144 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5145 if is_copilot_disabled {
5146 cx.propagate();
5147 }
5148 }
5149 }
5150
5151 pub fn accept_inline_completion(
5152 &mut self,
5153 _: &AcceptInlineCompletion,
5154 cx: &mut ViewContext<Self>,
5155 ) {
5156 let Some(completion) = self.take_active_inline_completion(cx) else {
5157 return;
5158 };
5159 if let Some(provider) = self.inline_completion_provider() {
5160 provider.accept(cx);
5161 }
5162
5163 cx.emit(EditorEvent::InputHandled {
5164 utf16_range_to_replace: None,
5165 text: completion.text.to_string().into(),
5166 });
5167
5168 if let Some(range) = completion.delete_range {
5169 self.change_selections(None, cx, |s| s.select_ranges([range]))
5170 }
5171 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5172 self.refresh_inline_completion(true, true, cx);
5173 cx.notify();
5174 }
5175
5176 pub fn accept_partial_inline_completion(
5177 &mut self,
5178 _: &AcceptPartialInlineCompletion,
5179 cx: &mut ViewContext<Self>,
5180 ) {
5181 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5182 if let Some(completion) = self.take_active_inline_completion(cx) {
5183 let mut partial_completion = completion
5184 .text
5185 .chars()
5186 .by_ref()
5187 .take_while(|c| c.is_alphabetic())
5188 .collect::<String>();
5189 if partial_completion.is_empty() {
5190 partial_completion = completion
5191 .text
5192 .chars()
5193 .by_ref()
5194 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5195 .collect::<String>();
5196 }
5197
5198 cx.emit(EditorEvent::InputHandled {
5199 utf16_range_to_replace: None,
5200 text: partial_completion.clone().into(),
5201 });
5202
5203 if let Some(range) = completion.delete_range {
5204 self.change_selections(None, cx, |s| s.select_ranges([range]))
5205 }
5206 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5207
5208 self.refresh_inline_completion(true, true, cx);
5209 cx.notify();
5210 }
5211 }
5212 }
5213
5214 fn discard_inline_completion(
5215 &mut self,
5216 should_report_inline_completion_event: bool,
5217 cx: &mut ViewContext<Self>,
5218 ) -> bool {
5219 if let Some(provider) = self.inline_completion_provider() {
5220 provider.discard(should_report_inline_completion_event, cx);
5221 }
5222
5223 self.take_active_inline_completion(cx).is_some()
5224 }
5225
5226 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5227 if let Some(completion) = self.active_inline_completion.as_ref() {
5228 let buffer = self.buffer.read(cx).read(cx);
5229 completion.position.is_valid(&buffer)
5230 } else {
5231 false
5232 }
5233 }
5234
5235 fn take_active_inline_completion(
5236 &mut self,
5237 cx: &mut ViewContext<Self>,
5238 ) -> Option<CompletionState> {
5239 let completion = self.active_inline_completion.take()?;
5240 let render_inlay_ids = completion.render_inlay_ids.clone();
5241 self.display_map.update(cx, |map, cx| {
5242 map.splice_inlays(render_inlay_ids, Default::default(), cx);
5243 });
5244 let buffer = self.buffer.read(cx).read(cx);
5245
5246 if completion.position.is_valid(&buffer) {
5247 Some(completion)
5248 } else {
5249 None
5250 }
5251 }
5252
5253 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5254 let selection = self.selections.newest_anchor();
5255 let cursor = selection.head();
5256
5257 let excerpt_id = cursor.excerpt_id;
5258
5259 if self.context_menu.read().is_none()
5260 && self.completion_tasks.is_empty()
5261 && selection.start == selection.end
5262 {
5263 if let Some(provider) = self.inline_completion_provider() {
5264 if let Some((buffer, cursor_buffer_position)) =
5265 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5266 {
5267 if let Some(proposal) =
5268 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5269 {
5270 let mut to_remove = Vec::new();
5271 if let Some(completion) = self.active_inline_completion.take() {
5272 to_remove.extend(completion.render_inlay_ids.iter());
5273 }
5274
5275 let to_add = proposal
5276 .inlays
5277 .iter()
5278 .filter_map(|inlay| {
5279 let snapshot = self.buffer.read(cx).snapshot(cx);
5280 let id = post_inc(&mut self.next_inlay_id);
5281 match inlay {
5282 InlayProposal::Hint(position, hint) => {
5283 let position =
5284 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5285 Some(Inlay::hint(id, position, hint))
5286 }
5287 InlayProposal::Suggestion(position, text) => {
5288 let position =
5289 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5290 Some(Inlay::suggestion(id, position, text.clone()))
5291 }
5292 }
5293 })
5294 .collect_vec();
5295
5296 self.active_inline_completion = Some(CompletionState {
5297 position: cursor,
5298 text: proposal.text,
5299 delete_range: proposal.delete_range.and_then(|range| {
5300 let snapshot = self.buffer.read(cx).snapshot(cx);
5301 let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
5302 let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
5303 Some(start?..end?)
5304 }),
5305 render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
5306 });
5307
5308 self.display_map
5309 .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
5310
5311 cx.notify();
5312 return;
5313 }
5314 }
5315 }
5316 }
5317
5318 self.discard_inline_completion(false, cx);
5319 }
5320
5321 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5322 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5323 }
5324
5325 fn render_code_actions_indicator(
5326 &self,
5327 _style: &EditorStyle,
5328 row: DisplayRow,
5329 is_active: bool,
5330 cx: &mut ViewContext<Self>,
5331 ) -> Option<IconButton> {
5332 if self.available_code_actions.is_some() {
5333 Some(
5334 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5335 .shape(ui::IconButtonShape::Square)
5336 .icon_size(IconSize::XSmall)
5337 .icon_color(Color::Muted)
5338 .selected(is_active)
5339 .on_click(cx.listener(move |editor, _e, cx| {
5340 editor.focus(cx);
5341 editor.toggle_code_actions(
5342 &ToggleCodeActions {
5343 deployed_from_indicator: Some(row),
5344 },
5345 cx,
5346 );
5347 })),
5348 )
5349 } else {
5350 None
5351 }
5352 }
5353
5354 fn clear_tasks(&mut self) {
5355 self.tasks.clear()
5356 }
5357
5358 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5359 if self.tasks.insert(key, value).is_some() {
5360 // This case should hopefully be rare, but just in case...
5361 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5362 }
5363 }
5364
5365 fn render_run_indicator(
5366 &self,
5367 _style: &EditorStyle,
5368 is_active: bool,
5369 row: DisplayRow,
5370 cx: &mut ViewContext<Self>,
5371 ) -> IconButton {
5372 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5373 .shape(ui::IconButtonShape::Square)
5374 .icon_size(IconSize::XSmall)
5375 .icon_color(Color::Muted)
5376 .selected(is_active)
5377 .on_click(cx.listener(move |editor, _e, cx| {
5378 editor.focus(cx);
5379 editor.toggle_code_actions(
5380 &ToggleCodeActions {
5381 deployed_from_indicator: Some(row),
5382 },
5383 cx,
5384 );
5385 }))
5386 }
5387
5388 pub fn context_menu_visible(&self) -> bool {
5389 self.context_menu
5390 .read()
5391 .as_ref()
5392 .map_or(false, |menu| menu.visible())
5393 }
5394
5395 fn render_context_menu(
5396 &self,
5397 cursor_position: DisplayPoint,
5398 style: &EditorStyle,
5399 max_height: Pixels,
5400 cx: &mut ViewContext<Editor>,
5401 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5402 self.context_menu.read().as_ref().map(|menu| {
5403 menu.render(
5404 cursor_position,
5405 style,
5406 max_height,
5407 self.workspace.as_ref().map(|(w, _)| w.clone()),
5408 cx,
5409 )
5410 })
5411 }
5412
5413 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5414 cx.notify();
5415 self.completion_tasks.clear();
5416 let context_menu = self.context_menu.write().take();
5417 if context_menu.is_some() {
5418 self.update_visible_inline_completion(cx);
5419 }
5420 context_menu
5421 }
5422
5423 pub fn insert_snippet(
5424 &mut self,
5425 insertion_ranges: &[Range<usize>],
5426 snippet: Snippet,
5427 cx: &mut ViewContext<Self>,
5428 ) -> Result<()> {
5429 struct Tabstop<T> {
5430 is_end_tabstop: bool,
5431 ranges: Vec<Range<T>>,
5432 }
5433
5434 let tabstops = self.buffer.update(cx, |buffer, cx| {
5435 let snippet_text: Arc<str> = snippet.text.clone().into();
5436 buffer.edit(
5437 insertion_ranges
5438 .iter()
5439 .cloned()
5440 .map(|range| (range, snippet_text.clone())),
5441 Some(AutoindentMode::EachLine),
5442 cx,
5443 );
5444
5445 let snapshot = &*buffer.read(cx);
5446 let snippet = &snippet;
5447 snippet
5448 .tabstops
5449 .iter()
5450 .map(|tabstop| {
5451 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5452 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5453 });
5454 let mut tabstop_ranges = tabstop
5455 .iter()
5456 .flat_map(|tabstop_range| {
5457 let mut delta = 0_isize;
5458 insertion_ranges.iter().map(move |insertion_range| {
5459 let insertion_start = insertion_range.start as isize + delta;
5460 delta +=
5461 snippet.text.len() as isize - insertion_range.len() as isize;
5462
5463 let start = ((insertion_start + tabstop_range.start) as usize)
5464 .min(snapshot.len());
5465 let end = ((insertion_start + tabstop_range.end) as usize)
5466 .min(snapshot.len());
5467 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5468 })
5469 })
5470 .collect::<Vec<_>>();
5471 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5472
5473 Tabstop {
5474 is_end_tabstop,
5475 ranges: tabstop_ranges,
5476 }
5477 })
5478 .collect::<Vec<_>>()
5479 });
5480 if let Some(tabstop) = tabstops.first() {
5481 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5482 s.select_ranges(tabstop.ranges.iter().cloned());
5483 });
5484
5485 // If we're already at the last tabstop and it's at the end of the snippet,
5486 // we're done, we don't need to keep the state around.
5487 if !tabstop.is_end_tabstop {
5488 let ranges = tabstops
5489 .into_iter()
5490 .map(|tabstop| tabstop.ranges)
5491 .collect::<Vec<_>>();
5492 self.snippet_stack.push(SnippetState {
5493 active_index: 0,
5494 ranges,
5495 });
5496 }
5497
5498 // Check whether the just-entered snippet ends with an auto-closable bracket.
5499 if self.autoclose_regions.is_empty() {
5500 let snapshot = self.buffer.read(cx).snapshot(cx);
5501 for selection in &mut self.selections.all::<Point>(cx) {
5502 let selection_head = selection.head();
5503 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5504 continue;
5505 };
5506
5507 let mut bracket_pair = None;
5508 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5509 let prev_chars = snapshot
5510 .reversed_chars_at(selection_head)
5511 .collect::<String>();
5512 for (pair, enabled) in scope.brackets() {
5513 if enabled
5514 && pair.close
5515 && prev_chars.starts_with(pair.start.as_str())
5516 && next_chars.starts_with(pair.end.as_str())
5517 {
5518 bracket_pair = Some(pair.clone());
5519 break;
5520 }
5521 }
5522 if let Some(pair) = bracket_pair {
5523 let start = snapshot.anchor_after(selection_head);
5524 let end = snapshot.anchor_after(selection_head);
5525 self.autoclose_regions.push(AutocloseRegion {
5526 selection_id: selection.id,
5527 range: start..end,
5528 pair,
5529 });
5530 }
5531 }
5532 }
5533 }
5534 Ok(())
5535 }
5536
5537 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5538 self.move_to_snippet_tabstop(Bias::Right, cx)
5539 }
5540
5541 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5542 self.move_to_snippet_tabstop(Bias::Left, cx)
5543 }
5544
5545 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5546 if let Some(mut snippet) = self.snippet_stack.pop() {
5547 match bias {
5548 Bias::Left => {
5549 if snippet.active_index > 0 {
5550 snippet.active_index -= 1;
5551 } else {
5552 self.snippet_stack.push(snippet);
5553 return false;
5554 }
5555 }
5556 Bias::Right => {
5557 if snippet.active_index + 1 < snippet.ranges.len() {
5558 snippet.active_index += 1;
5559 } else {
5560 self.snippet_stack.push(snippet);
5561 return false;
5562 }
5563 }
5564 }
5565 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5566 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5567 s.select_anchor_ranges(current_ranges.iter().cloned())
5568 });
5569 // If snippet state is not at the last tabstop, push it back on the stack
5570 if snippet.active_index + 1 < snippet.ranges.len() {
5571 self.snippet_stack.push(snippet);
5572 }
5573 return true;
5574 }
5575 }
5576
5577 false
5578 }
5579
5580 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5581 self.transact(cx, |this, cx| {
5582 this.select_all(&SelectAll, cx);
5583 this.insert("", cx);
5584 });
5585 }
5586
5587 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5588 self.transact(cx, |this, cx| {
5589 this.select_autoclose_pair(cx);
5590 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5591 if !this.linked_edit_ranges.is_empty() {
5592 let selections = this.selections.all::<MultiBufferPoint>(cx);
5593 let snapshot = this.buffer.read(cx).snapshot(cx);
5594
5595 for selection in selections.iter() {
5596 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5597 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5598 if selection_start.buffer_id != selection_end.buffer_id {
5599 continue;
5600 }
5601 if let Some(ranges) =
5602 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5603 {
5604 for (buffer, entries) in ranges {
5605 linked_ranges.entry(buffer).or_default().extend(entries);
5606 }
5607 }
5608 }
5609 }
5610
5611 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5612 if !this.selections.line_mode {
5613 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5614 for selection in &mut selections {
5615 if selection.is_empty() {
5616 let old_head = selection.head();
5617 let mut new_head =
5618 movement::left(&display_map, old_head.to_display_point(&display_map))
5619 .to_point(&display_map);
5620 if let Some((buffer, line_buffer_range)) = display_map
5621 .buffer_snapshot
5622 .buffer_line_for_row(MultiBufferRow(old_head.row))
5623 {
5624 let indent_size =
5625 buffer.indent_size_for_line(line_buffer_range.start.row);
5626 let indent_len = match indent_size.kind {
5627 IndentKind::Space => {
5628 buffer.settings_at(line_buffer_range.start, cx).tab_size
5629 }
5630 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5631 };
5632 if old_head.column <= indent_size.len && old_head.column > 0 {
5633 let indent_len = indent_len.get();
5634 new_head = cmp::min(
5635 new_head,
5636 MultiBufferPoint::new(
5637 old_head.row,
5638 ((old_head.column - 1) / indent_len) * indent_len,
5639 ),
5640 );
5641 }
5642 }
5643
5644 selection.set_head(new_head, SelectionGoal::None);
5645 }
5646 }
5647 }
5648
5649 this.signature_help_state.set_backspace_pressed(true);
5650 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5651 this.insert("", cx);
5652 let empty_str: Arc<str> = Arc::from("");
5653 for (buffer, edits) in linked_ranges {
5654 let snapshot = buffer.read(cx).snapshot();
5655 use text::ToPoint as TP;
5656
5657 let edits = edits
5658 .into_iter()
5659 .map(|range| {
5660 let end_point = TP::to_point(&range.end, &snapshot);
5661 let mut start_point = TP::to_point(&range.start, &snapshot);
5662
5663 if end_point == start_point {
5664 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5665 .saturating_sub(1);
5666 start_point = TP::to_point(&offset, &snapshot);
5667 };
5668
5669 (start_point..end_point, empty_str.clone())
5670 })
5671 .sorted_by_key(|(range, _)| range.start)
5672 .collect::<Vec<_>>();
5673 buffer.update(cx, |this, cx| {
5674 this.edit(edits, None, cx);
5675 })
5676 }
5677 this.refresh_inline_completion(true, false, cx);
5678 linked_editing_ranges::refresh_linked_ranges(this, cx);
5679 });
5680 }
5681
5682 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5683 self.transact(cx, |this, cx| {
5684 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5685 let line_mode = s.line_mode;
5686 s.move_with(|map, selection| {
5687 if selection.is_empty() && !line_mode {
5688 let cursor = movement::right(map, selection.head());
5689 selection.end = cursor;
5690 selection.reversed = true;
5691 selection.goal = SelectionGoal::None;
5692 }
5693 })
5694 });
5695 this.insert("", cx);
5696 this.refresh_inline_completion(true, false, cx);
5697 });
5698 }
5699
5700 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5701 if self.move_to_prev_snippet_tabstop(cx) {
5702 return;
5703 }
5704
5705 self.outdent(&Outdent, cx);
5706 }
5707
5708 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5709 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5710 return;
5711 }
5712
5713 let mut selections = self.selections.all_adjusted(cx);
5714 let buffer = self.buffer.read(cx);
5715 let snapshot = buffer.snapshot(cx);
5716 let rows_iter = selections.iter().map(|s| s.head().row);
5717 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5718
5719 let mut edits = Vec::new();
5720 let mut prev_edited_row = 0;
5721 let mut row_delta = 0;
5722 for selection in &mut selections {
5723 if selection.start.row != prev_edited_row {
5724 row_delta = 0;
5725 }
5726 prev_edited_row = selection.end.row;
5727
5728 // If the selection is non-empty, then increase the indentation of the selected lines.
5729 if !selection.is_empty() {
5730 row_delta =
5731 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5732 continue;
5733 }
5734
5735 // If the selection is empty and the cursor is in the leading whitespace before the
5736 // suggested indentation, then auto-indent the line.
5737 let cursor = selection.head();
5738 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5739 if let Some(suggested_indent) =
5740 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5741 {
5742 if cursor.column < suggested_indent.len
5743 && cursor.column <= current_indent.len
5744 && current_indent.len <= suggested_indent.len
5745 {
5746 selection.start = Point::new(cursor.row, suggested_indent.len);
5747 selection.end = selection.start;
5748 if row_delta == 0 {
5749 edits.extend(Buffer::edit_for_indent_size_adjustment(
5750 cursor.row,
5751 current_indent,
5752 suggested_indent,
5753 ));
5754 row_delta = suggested_indent.len - current_indent.len;
5755 }
5756 continue;
5757 }
5758 }
5759
5760 // Otherwise, insert a hard or soft tab.
5761 let settings = buffer.settings_at(cursor, cx);
5762 let tab_size = if settings.hard_tabs {
5763 IndentSize::tab()
5764 } else {
5765 let tab_size = settings.tab_size.get();
5766 let char_column = snapshot
5767 .text_for_range(Point::new(cursor.row, 0)..cursor)
5768 .flat_map(str::chars)
5769 .count()
5770 + row_delta as usize;
5771 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5772 IndentSize::spaces(chars_to_next_tab_stop)
5773 };
5774 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5775 selection.end = selection.start;
5776 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5777 row_delta += tab_size.len;
5778 }
5779
5780 self.transact(cx, |this, cx| {
5781 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5782 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5783 this.refresh_inline_completion(true, false, cx);
5784 });
5785 }
5786
5787 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5788 if self.read_only(cx) {
5789 return;
5790 }
5791 let mut selections = self.selections.all::<Point>(cx);
5792 let mut prev_edited_row = 0;
5793 let mut row_delta = 0;
5794 let mut edits = Vec::new();
5795 let buffer = self.buffer.read(cx);
5796 let snapshot = buffer.snapshot(cx);
5797 for selection in &mut selections {
5798 if selection.start.row != prev_edited_row {
5799 row_delta = 0;
5800 }
5801 prev_edited_row = selection.end.row;
5802
5803 row_delta =
5804 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5805 }
5806
5807 self.transact(cx, |this, cx| {
5808 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5809 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5810 });
5811 }
5812
5813 fn indent_selection(
5814 buffer: &MultiBuffer,
5815 snapshot: &MultiBufferSnapshot,
5816 selection: &mut Selection<Point>,
5817 edits: &mut Vec<(Range<Point>, String)>,
5818 delta_for_start_row: u32,
5819 cx: &AppContext,
5820 ) -> u32 {
5821 let settings = buffer.settings_at(selection.start, cx);
5822 let tab_size = settings.tab_size.get();
5823 let indent_kind = if settings.hard_tabs {
5824 IndentKind::Tab
5825 } else {
5826 IndentKind::Space
5827 };
5828 let mut start_row = selection.start.row;
5829 let mut end_row = selection.end.row + 1;
5830
5831 // If a selection ends at the beginning of a line, don't indent
5832 // that last line.
5833 if selection.end.column == 0 && selection.end.row > selection.start.row {
5834 end_row -= 1;
5835 }
5836
5837 // Avoid re-indenting a row that has already been indented by a
5838 // previous selection, but still update this selection's column
5839 // to reflect that indentation.
5840 if delta_for_start_row > 0 {
5841 start_row += 1;
5842 selection.start.column += delta_for_start_row;
5843 if selection.end.row == selection.start.row {
5844 selection.end.column += delta_for_start_row;
5845 }
5846 }
5847
5848 let mut delta_for_end_row = 0;
5849 let has_multiple_rows = start_row + 1 != end_row;
5850 for row in start_row..end_row {
5851 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5852 let indent_delta = match (current_indent.kind, indent_kind) {
5853 (IndentKind::Space, IndentKind::Space) => {
5854 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5855 IndentSize::spaces(columns_to_next_tab_stop)
5856 }
5857 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5858 (_, IndentKind::Tab) => IndentSize::tab(),
5859 };
5860
5861 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5862 0
5863 } else {
5864 selection.start.column
5865 };
5866 let row_start = Point::new(row, start);
5867 edits.push((
5868 row_start..row_start,
5869 indent_delta.chars().collect::<String>(),
5870 ));
5871
5872 // Update this selection's endpoints to reflect the indentation.
5873 if row == selection.start.row {
5874 selection.start.column += indent_delta.len;
5875 }
5876 if row == selection.end.row {
5877 selection.end.column += indent_delta.len;
5878 delta_for_end_row = indent_delta.len;
5879 }
5880 }
5881
5882 if selection.start.row == selection.end.row {
5883 delta_for_start_row + delta_for_end_row
5884 } else {
5885 delta_for_end_row
5886 }
5887 }
5888
5889 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5890 if self.read_only(cx) {
5891 return;
5892 }
5893 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5894 let selections = self.selections.all::<Point>(cx);
5895 let mut deletion_ranges = Vec::new();
5896 let mut last_outdent = None;
5897 {
5898 let buffer = self.buffer.read(cx);
5899 let snapshot = buffer.snapshot(cx);
5900 for selection in &selections {
5901 let settings = buffer.settings_at(selection.start, cx);
5902 let tab_size = settings.tab_size.get();
5903 let mut rows = selection.spanned_rows(false, &display_map);
5904
5905 // Avoid re-outdenting a row that has already been outdented by a
5906 // previous selection.
5907 if let Some(last_row) = last_outdent {
5908 if last_row == rows.start {
5909 rows.start = rows.start.next_row();
5910 }
5911 }
5912 let has_multiple_rows = rows.len() > 1;
5913 for row in rows.iter_rows() {
5914 let indent_size = snapshot.indent_size_for_line(row);
5915 if indent_size.len > 0 {
5916 let deletion_len = match indent_size.kind {
5917 IndentKind::Space => {
5918 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5919 if columns_to_prev_tab_stop == 0 {
5920 tab_size
5921 } else {
5922 columns_to_prev_tab_stop
5923 }
5924 }
5925 IndentKind::Tab => 1,
5926 };
5927 let start = if has_multiple_rows
5928 || deletion_len > selection.start.column
5929 || indent_size.len < selection.start.column
5930 {
5931 0
5932 } else {
5933 selection.start.column - deletion_len
5934 };
5935 deletion_ranges.push(
5936 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5937 );
5938 last_outdent = Some(row);
5939 }
5940 }
5941 }
5942 }
5943
5944 self.transact(cx, |this, cx| {
5945 this.buffer.update(cx, |buffer, cx| {
5946 let empty_str: Arc<str> = Arc::default();
5947 buffer.edit(
5948 deletion_ranges
5949 .into_iter()
5950 .map(|range| (range, empty_str.clone())),
5951 None,
5952 cx,
5953 );
5954 });
5955 let selections = this.selections.all::<usize>(cx);
5956 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5957 });
5958 }
5959
5960 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5961 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5962 let selections = self.selections.all::<Point>(cx);
5963
5964 let mut new_cursors = Vec::new();
5965 let mut edit_ranges = Vec::new();
5966 let mut selections = selections.iter().peekable();
5967 while let Some(selection) = selections.next() {
5968 let mut rows = selection.spanned_rows(false, &display_map);
5969 let goal_display_column = selection.head().to_display_point(&display_map).column();
5970
5971 // Accumulate contiguous regions of rows that we want to delete.
5972 while let Some(next_selection) = selections.peek() {
5973 let next_rows = next_selection.spanned_rows(false, &display_map);
5974 if next_rows.start <= rows.end {
5975 rows.end = next_rows.end;
5976 selections.next().unwrap();
5977 } else {
5978 break;
5979 }
5980 }
5981
5982 let buffer = &display_map.buffer_snapshot;
5983 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5984 let edit_end;
5985 let cursor_buffer_row;
5986 if buffer.max_point().row >= rows.end.0 {
5987 // If there's a line after the range, delete the \n from the end of the row range
5988 // and position the cursor on the next line.
5989 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5990 cursor_buffer_row = rows.end;
5991 } else {
5992 // If there isn't a line after the range, delete the \n from the line before the
5993 // start of the row range and position the cursor there.
5994 edit_start = edit_start.saturating_sub(1);
5995 edit_end = buffer.len();
5996 cursor_buffer_row = rows.start.previous_row();
5997 }
5998
5999 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6000 *cursor.column_mut() =
6001 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6002
6003 new_cursors.push((
6004 selection.id,
6005 buffer.anchor_after(cursor.to_point(&display_map)),
6006 ));
6007 edit_ranges.push(edit_start..edit_end);
6008 }
6009
6010 self.transact(cx, |this, cx| {
6011 let buffer = this.buffer.update(cx, |buffer, cx| {
6012 let empty_str: Arc<str> = Arc::default();
6013 buffer.edit(
6014 edit_ranges
6015 .into_iter()
6016 .map(|range| (range, empty_str.clone())),
6017 None,
6018 cx,
6019 );
6020 buffer.snapshot(cx)
6021 });
6022 let new_selections = new_cursors
6023 .into_iter()
6024 .map(|(id, cursor)| {
6025 let cursor = cursor.to_point(&buffer);
6026 Selection {
6027 id,
6028 start: cursor,
6029 end: cursor,
6030 reversed: false,
6031 goal: SelectionGoal::None,
6032 }
6033 })
6034 .collect();
6035
6036 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6037 s.select(new_selections);
6038 });
6039 });
6040 }
6041
6042 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6043 if self.read_only(cx) {
6044 return;
6045 }
6046 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6047 for selection in self.selections.all::<Point>(cx) {
6048 let start = MultiBufferRow(selection.start.row);
6049 let end = if selection.start.row == selection.end.row {
6050 MultiBufferRow(selection.start.row + 1)
6051 } else {
6052 MultiBufferRow(selection.end.row)
6053 };
6054
6055 if let Some(last_row_range) = row_ranges.last_mut() {
6056 if start <= last_row_range.end {
6057 last_row_range.end = end;
6058 continue;
6059 }
6060 }
6061 row_ranges.push(start..end);
6062 }
6063
6064 let snapshot = self.buffer.read(cx).snapshot(cx);
6065 let mut cursor_positions = Vec::new();
6066 for row_range in &row_ranges {
6067 let anchor = snapshot.anchor_before(Point::new(
6068 row_range.end.previous_row().0,
6069 snapshot.line_len(row_range.end.previous_row()),
6070 ));
6071 cursor_positions.push(anchor..anchor);
6072 }
6073
6074 self.transact(cx, |this, cx| {
6075 for row_range in row_ranges.into_iter().rev() {
6076 for row in row_range.iter_rows().rev() {
6077 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6078 let next_line_row = row.next_row();
6079 let indent = snapshot.indent_size_for_line(next_line_row);
6080 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6081
6082 let replace = if snapshot.line_len(next_line_row) > indent.len {
6083 " "
6084 } else {
6085 ""
6086 };
6087
6088 this.buffer.update(cx, |buffer, cx| {
6089 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6090 });
6091 }
6092 }
6093
6094 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6095 s.select_anchor_ranges(cursor_positions)
6096 });
6097 });
6098 }
6099
6100 pub fn sort_lines_case_sensitive(
6101 &mut self,
6102 _: &SortLinesCaseSensitive,
6103 cx: &mut ViewContext<Self>,
6104 ) {
6105 self.manipulate_lines(cx, |lines| lines.sort())
6106 }
6107
6108 pub fn sort_lines_case_insensitive(
6109 &mut self,
6110 _: &SortLinesCaseInsensitive,
6111 cx: &mut ViewContext<Self>,
6112 ) {
6113 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6114 }
6115
6116 pub fn unique_lines_case_insensitive(
6117 &mut self,
6118 _: &UniqueLinesCaseInsensitive,
6119 cx: &mut ViewContext<Self>,
6120 ) {
6121 self.manipulate_lines(cx, |lines| {
6122 let mut seen = HashSet::default();
6123 lines.retain(|line| seen.insert(line.to_lowercase()));
6124 })
6125 }
6126
6127 pub fn unique_lines_case_sensitive(
6128 &mut self,
6129 _: &UniqueLinesCaseSensitive,
6130 cx: &mut ViewContext<Self>,
6131 ) {
6132 self.manipulate_lines(cx, |lines| {
6133 let mut seen = HashSet::default();
6134 lines.retain(|line| seen.insert(*line));
6135 })
6136 }
6137
6138 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6139 let mut revert_changes = HashMap::default();
6140 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6141 for hunk in hunks_for_rows(
6142 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6143 &multi_buffer_snapshot,
6144 ) {
6145 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6146 }
6147 if !revert_changes.is_empty() {
6148 self.transact(cx, |editor, cx| {
6149 editor.revert(revert_changes, cx);
6150 });
6151 }
6152 }
6153
6154 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6155 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6156 if !revert_changes.is_empty() {
6157 self.transact(cx, |editor, cx| {
6158 editor.revert(revert_changes, cx);
6159 });
6160 }
6161 }
6162
6163 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6164 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6165 let project_path = buffer.read(cx).project_path(cx)?;
6166 let project = self.project.as_ref()?.read(cx);
6167 let entry = project.entry_for_path(&project_path, cx)?;
6168 let abs_path = project.absolute_path(&project_path, cx)?;
6169 let parent = if entry.is_symlink {
6170 abs_path.canonicalize().ok()?
6171 } else {
6172 abs_path
6173 }
6174 .parent()?
6175 .to_path_buf();
6176 Some(parent)
6177 }) {
6178 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6179 }
6180 }
6181
6182 fn gather_revert_changes(
6183 &mut self,
6184 selections: &[Selection<Anchor>],
6185 cx: &mut ViewContext<'_, Editor>,
6186 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6187 let mut revert_changes = HashMap::default();
6188 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6189 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6190 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6191 }
6192 revert_changes
6193 }
6194
6195 pub fn prepare_revert_change(
6196 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6197 multi_buffer: &Model<MultiBuffer>,
6198 hunk: &MultiBufferDiffHunk,
6199 cx: &AppContext,
6200 ) -> Option<()> {
6201 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6202 let buffer = buffer.read(cx);
6203 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6204 let buffer_snapshot = buffer.snapshot();
6205 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6206 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6207 probe
6208 .0
6209 .start
6210 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6211 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6212 }) {
6213 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6214 Some(())
6215 } else {
6216 None
6217 }
6218 }
6219
6220 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6221 self.manipulate_lines(cx, |lines| lines.reverse())
6222 }
6223
6224 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6225 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6226 }
6227
6228 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6229 where
6230 Fn: FnMut(&mut Vec<&str>),
6231 {
6232 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6233 let buffer = self.buffer.read(cx).snapshot(cx);
6234
6235 let mut edits = Vec::new();
6236
6237 let selections = self.selections.all::<Point>(cx);
6238 let mut selections = selections.iter().peekable();
6239 let mut contiguous_row_selections = Vec::new();
6240 let mut new_selections = Vec::new();
6241 let mut added_lines = 0;
6242 let mut removed_lines = 0;
6243
6244 while let Some(selection) = selections.next() {
6245 let (start_row, end_row) = consume_contiguous_rows(
6246 &mut contiguous_row_selections,
6247 selection,
6248 &display_map,
6249 &mut selections,
6250 );
6251
6252 let start_point = Point::new(start_row.0, 0);
6253 let end_point = Point::new(
6254 end_row.previous_row().0,
6255 buffer.line_len(end_row.previous_row()),
6256 );
6257 let text = buffer
6258 .text_for_range(start_point..end_point)
6259 .collect::<String>();
6260
6261 let mut lines = text.split('\n').collect_vec();
6262
6263 let lines_before = lines.len();
6264 callback(&mut lines);
6265 let lines_after = lines.len();
6266
6267 edits.push((start_point..end_point, lines.join("\n")));
6268
6269 // Selections must change based on added and removed line count
6270 let start_row =
6271 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6272 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6273 new_selections.push(Selection {
6274 id: selection.id,
6275 start: start_row,
6276 end: end_row,
6277 goal: SelectionGoal::None,
6278 reversed: selection.reversed,
6279 });
6280
6281 if lines_after > lines_before {
6282 added_lines += lines_after - lines_before;
6283 } else if lines_before > lines_after {
6284 removed_lines += lines_before - lines_after;
6285 }
6286 }
6287
6288 self.transact(cx, |this, cx| {
6289 let buffer = this.buffer.update(cx, |buffer, cx| {
6290 buffer.edit(edits, None, cx);
6291 buffer.snapshot(cx)
6292 });
6293
6294 // Recalculate offsets on newly edited buffer
6295 let new_selections = new_selections
6296 .iter()
6297 .map(|s| {
6298 let start_point = Point::new(s.start.0, 0);
6299 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6300 Selection {
6301 id: s.id,
6302 start: buffer.point_to_offset(start_point),
6303 end: buffer.point_to_offset(end_point),
6304 goal: s.goal,
6305 reversed: s.reversed,
6306 }
6307 })
6308 .collect();
6309
6310 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6311 s.select(new_selections);
6312 });
6313
6314 this.request_autoscroll(Autoscroll::fit(), cx);
6315 });
6316 }
6317
6318 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6319 self.manipulate_text(cx, |text| text.to_uppercase())
6320 }
6321
6322 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6323 self.manipulate_text(cx, |text| text.to_lowercase())
6324 }
6325
6326 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6327 self.manipulate_text(cx, |text| {
6328 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6329 // https://github.com/rutrum/convert-case/issues/16
6330 text.split('\n')
6331 .map(|line| line.to_case(Case::Title))
6332 .join("\n")
6333 })
6334 }
6335
6336 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6337 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6338 }
6339
6340 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6341 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6342 }
6343
6344 pub fn convert_to_upper_camel_case(
6345 &mut self,
6346 _: &ConvertToUpperCamelCase,
6347 cx: &mut ViewContext<Self>,
6348 ) {
6349 self.manipulate_text(cx, |text| {
6350 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6351 // https://github.com/rutrum/convert-case/issues/16
6352 text.split('\n')
6353 .map(|line| line.to_case(Case::UpperCamel))
6354 .join("\n")
6355 })
6356 }
6357
6358 pub fn convert_to_lower_camel_case(
6359 &mut self,
6360 _: &ConvertToLowerCamelCase,
6361 cx: &mut ViewContext<Self>,
6362 ) {
6363 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6364 }
6365
6366 pub fn convert_to_opposite_case(
6367 &mut self,
6368 _: &ConvertToOppositeCase,
6369 cx: &mut ViewContext<Self>,
6370 ) {
6371 self.manipulate_text(cx, |text| {
6372 text.chars()
6373 .fold(String::with_capacity(text.len()), |mut t, c| {
6374 if c.is_uppercase() {
6375 t.extend(c.to_lowercase());
6376 } else {
6377 t.extend(c.to_uppercase());
6378 }
6379 t
6380 })
6381 })
6382 }
6383
6384 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6385 where
6386 Fn: FnMut(&str) -> String,
6387 {
6388 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6389 let buffer = self.buffer.read(cx).snapshot(cx);
6390
6391 let mut new_selections = Vec::new();
6392 let mut edits = Vec::new();
6393 let mut selection_adjustment = 0i32;
6394
6395 for selection in self.selections.all::<usize>(cx) {
6396 let selection_is_empty = selection.is_empty();
6397
6398 let (start, end) = if selection_is_empty {
6399 let word_range = movement::surrounding_word(
6400 &display_map,
6401 selection.start.to_display_point(&display_map),
6402 );
6403 let start = word_range.start.to_offset(&display_map, Bias::Left);
6404 let end = word_range.end.to_offset(&display_map, Bias::Left);
6405 (start, end)
6406 } else {
6407 (selection.start, selection.end)
6408 };
6409
6410 let text = buffer.text_for_range(start..end).collect::<String>();
6411 let old_length = text.len() as i32;
6412 let text = callback(&text);
6413
6414 new_selections.push(Selection {
6415 start: (start as i32 - selection_adjustment) as usize,
6416 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6417 goal: SelectionGoal::None,
6418 ..selection
6419 });
6420
6421 selection_adjustment += old_length - text.len() as i32;
6422
6423 edits.push((start..end, text));
6424 }
6425
6426 self.transact(cx, |this, cx| {
6427 this.buffer.update(cx, |buffer, cx| {
6428 buffer.edit(edits, None, cx);
6429 });
6430
6431 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6432 s.select(new_selections);
6433 });
6434
6435 this.request_autoscroll(Autoscroll::fit(), cx);
6436 });
6437 }
6438
6439 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6440 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6441 let buffer = &display_map.buffer_snapshot;
6442 let selections = self.selections.all::<Point>(cx);
6443
6444 let mut edits = Vec::new();
6445 let mut selections_iter = selections.iter().peekable();
6446 while let Some(selection) = selections_iter.next() {
6447 // Avoid duplicating the same lines twice.
6448 let mut rows = selection.spanned_rows(false, &display_map);
6449
6450 while let Some(next_selection) = selections_iter.peek() {
6451 let next_rows = next_selection.spanned_rows(false, &display_map);
6452 if next_rows.start < rows.end {
6453 rows.end = next_rows.end;
6454 selections_iter.next().unwrap();
6455 } else {
6456 break;
6457 }
6458 }
6459
6460 // Copy the text from the selected row region and splice it either at the start
6461 // or end of the region.
6462 let start = Point::new(rows.start.0, 0);
6463 let end = Point::new(
6464 rows.end.previous_row().0,
6465 buffer.line_len(rows.end.previous_row()),
6466 );
6467 let text = buffer
6468 .text_for_range(start..end)
6469 .chain(Some("\n"))
6470 .collect::<String>();
6471 let insert_location = if upwards {
6472 Point::new(rows.end.0, 0)
6473 } else {
6474 start
6475 };
6476 edits.push((insert_location..insert_location, text));
6477 }
6478
6479 self.transact(cx, |this, cx| {
6480 this.buffer.update(cx, |buffer, cx| {
6481 buffer.edit(edits, None, cx);
6482 });
6483
6484 this.request_autoscroll(Autoscroll::fit(), cx);
6485 });
6486 }
6487
6488 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6489 self.duplicate_line(true, cx);
6490 }
6491
6492 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6493 self.duplicate_line(false, cx);
6494 }
6495
6496 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6497 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6498 let buffer = self.buffer.read(cx).snapshot(cx);
6499
6500 let mut edits = Vec::new();
6501 let mut unfold_ranges = Vec::new();
6502 let mut refold_ranges = Vec::new();
6503
6504 let selections = self.selections.all::<Point>(cx);
6505 let mut selections = selections.iter().peekable();
6506 let mut contiguous_row_selections = Vec::new();
6507 let mut new_selections = Vec::new();
6508
6509 while let Some(selection) = selections.next() {
6510 // Find all the selections that span a contiguous row range
6511 let (start_row, end_row) = consume_contiguous_rows(
6512 &mut contiguous_row_selections,
6513 selection,
6514 &display_map,
6515 &mut selections,
6516 );
6517
6518 // Move the text spanned by the row range to be before the line preceding the row range
6519 if start_row.0 > 0 {
6520 let range_to_move = Point::new(
6521 start_row.previous_row().0,
6522 buffer.line_len(start_row.previous_row()),
6523 )
6524 ..Point::new(
6525 end_row.previous_row().0,
6526 buffer.line_len(end_row.previous_row()),
6527 );
6528 let insertion_point = display_map
6529 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6530 .0;
6531
6532 // Don't move lines across excerpts
6533 if buffer
6534 .excerpt_boundaries_in_range((
6535 Bound::Excluded(insertion_point),
6536 Bound::Included(range_to_move.end),
6537 ))
6538 .next()
6539 .is_none()
6540 {
6541 let text = buffer
6542 .text_for_range(range_to_move.clone())
6543 .flat_map(|s| s.chars())
6544 .skip(1)
6545 .chain(['\n'])
6546 .collect::<String>();
6547
6548 edits.push((
6549 buffer.anchor_after(range_to_move.start)
6550 ..buffer.anchor_before(range_to_move.end),
6551 String::new(),
6552 ));
6553 let insertion_anchor = buffer.anchor_after(insertion_point);
6554 edits.push((insertion_anchor..insertion_anchor, text));
6555
6556 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6557
6558 // Move selections up
6559 new_selections.extend(contiguous_row_selections.drain(..).map(
6560 |mut selection| {
6561 selection.start.row -= row_delta;
6562 selection.end.row -= row_delta;
6563 selection
6564 },
6565 ));
6566
6567 // Move folds up
6568 unfold_ranges.push(range_to_move.clone());
6569 for fold in display_map.folds_in_range(
6570 buffer.anchor_before(range_to_move.start)
6571 ..buffer.anchor_after(range_to_move.end),
6572 ) {
6573 let mut start = fold.range.start.to_point(&buffer);
6574 let mut end = fold.range.end.to_point(&buffer);
6575 start.row -= row_delta;
6576 end.row -= row_delta;
6577 refold_ranges.push((start..end, fold.placeholder.clone()));
6578 }
6579 }
6580 }
6581
6582 // If we didn't move line(s), preserve the existing selections
6583 new_selections.append(&mut contiguous_row_selections);
6584 }
6585
6586 self.transact(cx, |this, cx| {
6587 this.unfold_ranges(unfold_ranges, true, true, cx);
6588 this.buffer.update(cx, |buffer, cx| {
6589 for (range, text) in edits {
6590 buffer.edit([(range, text)], None, cx);
6591 }
6592 });
6593 this.fold_ranges(refold_ranges, true, cx);
6594 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6595 s.select(new_selections);
6596 })
6597 });
6598 }
6599
6600 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6601 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6602 let buffer = self.buffer.read(cx).snapshot(cx);
6603
6604 let mut edits = Vec::new();
6605 let mut unfold_ranges = Vec::new();
6606 let mut refold_ranges = Vec::new();
6607
6608 let selections = self.selections.all::<Point>(cx);
6609 let mut selections = selections.iter().peekable();
6610 let mut contiguous_row_selections = Vec::new();
6611 let mut new_selections = Vec::new();
6612
6613 while let Some(selection) = selections.next() {
6614 // Find all the selections that span a contiguous row range
6615 let (start_row, end_row) = consume_contiguous_rows(
6616 &mut contiguous_row_selections,
6617 selection,
6618 &display_map,
6619 &mut selections,
6620 );
6621
6622 // Move the text spanned by the row range to be after the last line of the row range
6623 if end_row.0 <= buffer.max_point().row {
6624 let range_to_move =
6625 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6626 let insertion_point = display_map
6627 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6628 .0;
6629
6630 // Don't move lines across excerpt boundaries
6631 if buffer
6632 .excerpt_boundaries_in_range((
6633 Bound::Excluded(range_to_move.start),
6634 Bound::Included(insertion_point),
6635 ))
6636 .next()
6637 .is_none()
6638 {
6639 let mut text = String::from("\n");
6640 text.extend(buffer.text_for_range(range_to_move.clone()));
6641 text.pop(); // Drop trailing newline
6642 edits.push((
6643 buffer.anchor_after(range_to_move.start)
6644 ..buffer.anchor_before(range_to_move.end),
6645 String::new(),
6646 ));
6647 let insertion_anchor = buffer.anchor_after(insertion_point);
6648 edits.push((insertion_anchor..insertion_anchor, text));
6649
6650 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6651
6652 // Move selections down
6653 new_selections.extend(contiguous_row_selections.drain(..).map(
6654 |mut selection| {
6655 selection.start.row += row_delta;
6656 selection.end.row += row_delta;
6657 selection
6658 },
6659 ));
6660
6661 // Move folds down
6662 unfold_ranges.push(range_to_move.clone());
6663 for fold in display_map.folds_in_range(
6664 buffer.anchor_before(range_to_move.start)
6665 ..buffer.anchor_after(range_to_move.end),
6666 ) {
6667 let mut start = fold.range.start.to_point(&buffer);
6668 let mut end = fold.range.end.to_point(&buffer);
6669 start.row += row_delta;
6670 end.row += row_delta;
6671 refold_ranges.push((start..end, fold.placeholder.clone()));
6672 }
6673 }
6674 }
6675
6676 // If we didn't move line(s), preserve the existing selections
6677 new_selections.append(&mut contiguous_row_selections);
6678 }
6679
6680 self.transact(cx, |this, cx| {
6681 this.unfold_ranges(unfold_ranges, true, true, cx);
6682 this.buffer.update(cx, |buffer, cx| {
6683 for (range, text) in edits {
6684 buffer.edit([(range, text)], None, cx);
6685 }
6686 });
6687 this.fold_ranges(refold_ranges, true, cx);
6688 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6689 });
6690 }
6691
6692 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6693 let text_layout_details = &self.text_layout_details(cx);
6694 self.transact(cx, |this, cx| {
6695 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6696 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6697 let line_mode = s.line_mode;
6698 s.move_with(|display_map, selection| {
6699 if !selection.is_empty() || line_mode {
6700 return;
6701 }
6702
6703 let mut head = selection.head();
6704 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6705 if head.column() == display_map.line_len(head.row()) {
6706 transpose_offset = display_map
6707 .buffer_snapshot
6708 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6709 }
6710
6711 if transpose_offset == 0 {
6712 return;
6713 }
6714
6715 *head.column_mut() += 1;
6716 head = display_map.clip_point(head, Bias::Right);
6717 let goal = SelectionGoal::HorizontalPosition(
6718 display_map
6719 .x_for_display_point(head, text_layout_details)
6720 .into(),
6721 );
6722 selection.collapse_to(head, goal);
6723
6724 let transpose_start = display_map
6725 .buffer_snapshot
6726 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6727 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6728 let transpose_end = display_map
6729 .buffer_snapshot
6730 .clip_offset(transpose_offset + 1, Bias::Right);
6731 if let Some(ch) =
6732 display_map.buffer_snapshot.chars_at(transpose_start).next()
6733 {
6734 edits.push((transpose_start..transpose_offset, String::new()));
6735 edits.push((transpose_end..transpose_end, ch.to_string()));
6736 }
6737 }
6738 });
6739 edits
6740 });
6741 this.buffer
6742 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6743 let selections = this.selections.all::<usize>(cx);
6744 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6745 s.select(selections);
6746 });
6747 });
6748 }
6749
6750 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6751 self.rewrap_impl(true, cx)
6752 }
6753
6754 pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
6755 let buffer = self.buffer.read(cx).snapshot(cx);
6756 let selections = self.selections.all::<Point>(cx);
6757 let mut selections = selections.iter().peekable();
6758
6759 let mut edits = Vec::new();
6760 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6761
6762 while let Some(selection) = selections.next() {
6763 let mut start_row = selection.start.row;
6764 let mut end_row = selection.end.row;
6765
6766 // Skip selections that overlap with a range that has already been rewrapped.
6767 let selection_range = start_row..end_row;
6768 if rewrapped_row_ranges
6769 .iter()
6770 .any(|range| range.overlaps(&selection_range))
6771 {
6772 continue;
6773 }
6774
6775 let mut should_rewrap = !only_text;
6776
6777 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6778 match language_scope.language_name().0.as_ref() {
6779 "Markdown" | "Plain Text" => {
6780 should_rewrap = true;
6781 }
6782 _ => {}
6783 }
6784 }
6785
6786 // Since not all lines in the selection may be at the same indent
6787 // level, choose the indent size that is the most common between all
6788 // of the lines.
6789 //
6790 // If there is a tie, we use the deepest indent.
6791 let (indent_size, indent_end) = {
6792 let mut indent_size_occurrences = HashMap::default();
6793 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6794
6795 for row in start_row..=end_row {
6796 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6797 rows_by_indent_size.entry(indent).or_default().push(row);
6798 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6799 }
6800
6801 let indent_size = indent_size_occurrences
6802 .into_iter()
6803 .max_by_key(|(indent, count)| (*count, indent.len))
6804 .map(|(indent, _)| indent)
6805 .unwrap_or_default();
6806 let row = rows_by_indent_size[&indent_size][0];
6807 let indent_end = Point::new(row, indent_size.len);
6808
6809 (indent_size, indent_end)
6810 };
6811
6812 let mut line_prefix = indent_size.chars().collect::<String>();
6813
6814 if let Some(comment_prefix) =
6815 buffer
6816 .language_scope_at(selection.head())
6817 .and_then(|language| {
6818 language
6819 .line_comment_prefixes()
6820 .iter()
6821 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6822 .cloned()
6823 })
6824 {
6825 line_prefix.push_str(&comment_prefix);
6826 should_rewrap = true;
6827 }
6828
6829 if selection.is_empty() {
6830 'expand_upwards: while start_row > 0 {
6831 let prev_row = start_row - 1;
6832 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6833 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6834 {
6835 start_row = prev_row;
6836 } else {
6837 break 'expand_upwards;
6838 }
6839 }
6840
6841 'expand_downwards: while end_row < buffer.max_point().row {
6842 let next_row = end_row + 1;
6843 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6844 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6845 {
6846 end_row = next_row;
6847 } else {
6848 break 'expand_downwards;
6849 }
6850 }
6851 }
6852
6853 if !should_rewrap {
6854 continue;
6855 }
6856
6857 let start = Point::new(start_row, 0);
6858 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6859 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6860 let Some(lines_without_prefixes) = selection_text
6861 .lines()
6862 .map(|line| {
6863 line.strip_prefix(&line_prefix)
6864 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6865 .ok_or_else(|| {
6866 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6867 })
6868 })
6869 .collect::<Result<Vec<_>, _>>()
6870 .log_err()
6871 else {
6872 continue;
6873 };
6874
6875 let unwrapped_text = lines_without_prefixes.join(" ");
6876 let wrap_column = buffer
6877 .settings_at(Point::new(start_row, 0), cx)
6878 .preferred_line_length as usize;
6879 let mut wrapped_text = String::new();
6880 let mut current_line = line_prefix.clone();
6881 for word in unwrapped_text.split_whitespace() {
6882 if current_line.len() + word.len() >= wrap_column {
6883 wrapped_text.push_str(¤t_line);
6884 wrapped_text.push('\n');
6885 current_line.truncate(line_prefix.len());
6886 }
6887
6888 if current_line.len() > line_prefix.len() {
6889 current_line.push(' ');
6890 }
6891
6892 current_line.push_str(word);
6893 }
6894
6895 if !current_line.is_empty() {
6896 wrapped_text.push_str(¤t_line);
6897 }
6898
6899 let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
6900 let mut offset = start.to_offset(&buffer);
6901 let mut moved_since_edit = true;
6902
6903 for change in diff.iter_all_changes() {
6904 let value = change.value();
6905 match change.tag() {
6906 ChangeTag::Equal => {
6907 offset += value.len();
6908 moved_since_edit = true;
6909 }
6910 ChangeTag::Delete => {
6911 let start = buffer.anchor_after(offset);
6912 let end = buffer.anchor_before(offset + value.len());
6913
6914 if moved_since_edit {
6915 edits.push((start..end, String::new()));
6916 } else {
6917 edits.last_mut().unwrap().0.end = end;
6918 }
6919
6920 offset += value.len();
6921 moved_since_edit = false;
6922 }
6923 ChangeTag::Insert => {
6924 if moved_since_edit {
6925 let anchor = buffer.anchor_after(offset);
6926 edits.push((anchor..anchor, value.to_string()));
6927 } else {
6928 edits.last_mut().unwrap().1.push_str(value);
6929 }
6930
6931 moved_since_edit = false;
6932 }
6933 }
6934 }
6935
6936 rewrapped_row_ranges.push(start_row..=end_row);
6937 }
6938
6939 self.buffer
6940 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6941 }
6942
6943 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6944 let mut text = String::new();
6945 let buffer = self.buffer.read(cx).snapshot(cx);
6946 let mut selections = self.selections.all::<Point>(cx);
6947 let mut clipboard_selections = Vec::with_capacity(selections.len());
6948 {
6949 let max_point = buffer.max_point();
6950 let mut is_first = true;
6951 for selection in &mut selections {
6952 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6953 if is_entire_line {
6954 selection.start = Point::new(selection.start.row, 0);
6955 if !selection.is_empty() && selection.end.column == 0 {
6956 selection.end = cmp::min(max_point, selection.end);
6957 } else {
6958 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6959 }
6960 selection.goal = SelectionGoal::None;
6961 }
6962 if is_first {
6963 is_first = false;
6964 } else {
6965 text += "\n";
6966 }
6967 let mut len = 0;
6968 for chunk in buffer.text_for_range(selection.start..selection.end) {
6969 text.push_str(chunk);
6970 len += chunk.len();
6971 }
6972 clipboard_selections.push(ClipboardSelection {
6973 len,
6974 is_entire_line,
6975 first_line_indent: buffer
6976 .indent_size_for_line(MultiBufferRow(selection.start.row))
6977 .len,
6978 });
6979 }
6980 }
6981
6982 self.transact(cx, |this, cx| {
6983 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6984 s.select(selections);
6985 });
6986 this.insert("", cx);
6987 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6988 text,
6989 clipboard_selections,
6990 ));
6991 });
6992 }
6993
6994 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6995 let selections = self.selections.all::<Point>(cx);
6996 let buffer = self.buffer.read(cx).read(cx);
6997 let mut text = String::new();
6998
6999 let mut clipboard_selections = Vec::with_capacity(selections.len());
7000 {
7001 let max_point = buffer.max_point();
7002 let mut is_first = true;
7003 for selection in selections.iter() {
7004 let mut start = selection.start;
7005 let mut end = selection.end;
7006 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7007 if is_entire_line {
7008 start = Point::new(start.row, 0);
7009 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7010 }
7011 if is_first {
7012 is_first = false;
7013 } else {
7014 text += "\n";
7015 }
7016 let mut len = 0;
7017 for chunk in buffer.text_for_range(start..end) {
7018 text.push_str(chunk);
7019 len += chunk.len();
7020 }
7021 clipboard_selections.push(ClipboardSelection {
7022 len,
7023 is_entire_line,
7024 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7025 });
7026 }
7027 }
7028
7029 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7030 text,
7031 clipboard_selections,
7032 ));
7033 }
7034
7035 pub fn do_paste(
7036 &mut self,
7037 text: &String,
7038 clipboard_selections: Option<Vec<ClipboardSelection>>,
7039 handle_entire_lines: bool,
7040 cx: &mut ViewContext<Self>,
7041 ) {
7042 if self.read_only(cx) {
7043 return;
7044 }
7045
7046 let clipboard_text = Cow::Borrowed(text);
7047
7048 self.transact(cx, |this, cx| {
7049 if let Some(mut clipboard_selections) = clipboard_selections {
7050 let old_selections = this.selections.all::<usize>(cx);
7051 let all_selections_were_entire_line =
7052 clipboard_selections.iter().all(|s| s.is_entire_line);
7053 let first_selection_indent_column =
7054 clipboard_selections.first().map(|s| s.first_line_indent);
7055 if clipboard_selections.len() != old_selections.len() {
7056 clipboard_selections.drain(..);
7057 }
7058
7059 this.buffer.update(cx, |buffer, cx| {
7060 let snapshot = buffer.read(cx);
7061 let mut start_offset = 0;
7062 let mut edits = Vec::new();
7063 let mut original_indent_columns = Vec::new();
7064 for (ix, selection) in old_selections.iter().enumerate() {
7065 let to_insert;
7066 let entire_line;
7067 let original_indent_column;
7068 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7069 let end_offset = start_offset + clipboard_selection.len;
7070 to_insert = &clipboard_text[start_offset..end_offset];
7071 entire_line = clipboard_selection.is_entire_line;
7072 start_offset = end_offset + 1;
7073 original_indent_column = Some(clipboard_selection.first_line_indent);
7074 } else {
7075 to_insert = clipboard_text.as_str();
7076 entire_line = all_selections_were_entire_line;
7077 original_indent_column = first_selection_indent_column
7078 }
7079
7080 // If the corresponding selection was empty when this slice of the
7081 // clipboard text was written, then the entire line containing the
7082 // selection was copied. If this selection is also currently empty,
7083 // then paste the line before the current line of the buffer.
7084 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7085 let column = selection.start.to_point(&snapshot).column as usize;
7086 let line_start = selection.start - column;
7087 line_start..line_start
7088 } else {
7089 selection.range()
7090 };
7091
7092 edits.push((range, to_insert));
7093 original_indent_columns.extend(original_indent_column);
7094 }
7095 drop(snapshot);
7096
7097 buffer.edit(
7098 edits,
7099 Some(AutoindentMode::Block {
7100 original_indent_columns,
7101 }),
7102 cx,
7103 );
7104 });
7105
7106 let selections = this.selections.all::<usize>(cx);
7107 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7108 } else {
7109 this.insert(&clipboard_text, cx);
7110 }
7111 });
7112 }
7113
7114 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7115 if let Some(item) = cx.read_from_clipboard() {
7116 let entries = item.entries();
7117
7118 match entries.first() {
7119 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7120 // of all the pasted entries.
7121 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7122 .do_paste(
7123 clipboard_string.text(),
7124 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7125 true,
7126 cx,
7127 ),
7128 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7129 }
7130 }
7131 }
7132
7133 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7134 if self.read_only(cx) {
7135 return;
7136 }
7137
7138 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7139 if let Some((selections, _)) =
7140 self.selection_history.transaction(transaction_id).cloned()
7141 {
7142 self.change_selections(None, cx, |s| {
7143 s.select_anchors(selections.to_vec());
7144 });
7145 }
7146 self.request_autoscroll(Autoscroll::fit(), cx);
7147 self.unmark_text(cx);
7148 self.refresh_inline_completion(true, false, cx);
7149 cx.emit(EditorEvent::Edited { transaction_id });
7150 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7151 }
7152 }
7153
7154 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7155 if self.read_only(cx) {
7156 return;
7157 }
7158
7159 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7160 if let Some((_, Some(selections))) =
7161 self.selection_history.transaction(transaction_id).cloned()
7162 {
7163 self.change_selections(None, cx, |s| {
7164 s.select_anchors(selections.to_vec());
7165 });
7166 }
7167 self.request_autoscroll(Autoscroll::fit(), cx);
7168 self.unmark_text(cx);
7169 self.refresh_inline_completion(true, false, cx);
7170 cx.emit(EditorEvent::Edited { transaction_id });
7171 }
7172 }
7173
7174 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7175 self.buffer
7176 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7177 }
7178
7179 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7180 self.buffer
7181 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7182 }
7183
7184 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7185 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7186 let line_mode = s.line_mode;
7187 s.move_with(|map, selection| {
7188 let cursor = if selection.is_empty() && !line_mode {
7189 movement::left(map, selection.start)
7190 } else {
7191 selection.start
7192 };
7193 selection.collapse_to(cursor, SelectionGoal::None);
7194 });
7195 })
7196 }
7197
7198 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7199 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7200 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7201 })
7202 }
7203
7204 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7205 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7206 let line_mode = s.line_mode;
7207 s.move_with(|map, selection| {
7208 let cursor = if selection.is_empty() && !line_mode {
7209 movement::right(map, selection.end)
7210 } else {
7211 selection.end
7212 };
7213 selection.collapse_to(cursor, SelectionGoal::None)
7214 });
7215 })
7216 }
7217
7218 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7219 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7220 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7221 })
7222 }
7223
7224 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7225 if self.take_rename(true, cx).is_some() {
7226 return;
7227 }
7228
7229 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7230 cx.propagate();
7231 return;
7232 }
7233
7234 let text_layout_details = &self.text_layout_details(cx);
7235 let selection_count = self.selections.count();
7236 let first_selection = self.selections.first_anchor();
7237
7238 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7239 let line_mode = s.line_mode;
7240 s.move_with(|map, selection| {
7241 if !selection.is_empty() && !line_mode {
7242 selection.goal = SelectionGoal::None;
7243 }
7244 let (cursor, goal) = movement::up(
7245 map,
7246 selection.start,
7247 selection.goal,
7248 false,
7249 text_layout_details,
7250 );
7251 selection.collapse_to(cursor, goal);
7252 });
7253 });
7254
7255 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7256 {
7257 cx.propagate();
7258 }
7259 }
7260
7261 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7262 if self.take_rename(true, cx).is_some() {
7263 return;
7264 }
7265
7266 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7267 cx.propagate();
7268 return;
7269 }
7270
7271 let text_layout_details = &self.text_layout_details(cx);
7272
7273 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7274 let line_mode = s.line_mode;
7275 s.move_with(|map, selection| {
7276 if !selection.is_empty() && !line_mode {
7277 selection.goal = SelectionGoal::None;
7278 }
7279 let (cursor, goal) = movement::up_by_rows(
7280 map,
7281 selection.start,
7282 action.lines,
7283 selection.goal,
7284 false,
7285 text_layout_details,
7286 );
7287 selection.collapse_to(cursor, goal);
7288 });
7289 })
7290 }
7291
7292 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7293 if self.take_rename(true, cx).is_some() {
7294 return;
7295 }
7296
7297 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7298 cx.propagate();
7299 return;
7300 }
7301
7302 let text_layout_details = &self.text_layout_details(cx);
7303
7304 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7305 let line_mode = s.line_mode;
7306 s.move_with(|map, selection| {
7307 if !selection.is_empty() && !line_mode {
7308 selection.goal = SelectionGoal::None;
7309 }
7310 let (cursor, goal) = movement::down_by_rows(
7311 map,
7312 selection.start,
7313 action.lines,
7314 selection.goal,
7315 false,
7316 text_layout_details,
7317 );
7318 selection.collapse_to(cursor, goal);
7319 });
7320 })
7321 }
7322
7323 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7324 let text_layout_details = &self.text_layout_details(cx);
7325 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7326 s.move_heads_with(|map, head, goal| {
7327 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7328 })
7329 })
7330 }
7331
7332 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7333 let text_layout_details = &self.text_layout_details(cx);
7334 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7335 s.move_heads_with(|map, head, goal| {
7336 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7337 })
7338 })
7339 }
7340
7341 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7342 let Some(row_count) = self.visible_row_count() else {
7343 return;
7344 };
7345
7346 let text_layout_details = &self.text_layout_details(cx);
7347
7348 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7349 s.move_heads_with(|map, head, goal| {
7350 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7351 })
7352 })
7353 }
7354
7355 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7356 if self.take_rename(true, cx).is_some() {
7357 return;
7358 }
7359
7360 if self
7361 .context_menu
7362 .write()
7363 .as_mut()
7364 .map(|menu| menu.select_first(self.project.as_ref(), cx))
7365 .unwrap_or(false)
7366 {
7367 return;
7368 }
7369
7370 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7371 cx.propagate();
7372 return;
7373 }
7374
7375 let Some(row_count) = self.visible_row_count() else {
7376 return;
7377 };
7378
7379 let autoscroll = if action.center_cursor {
7380 Autoscroll::center()
7381 } else {
7382 Autoscroll::fit()
7383 };
7384
7385 let text_layout_details = &self.text_layout_details(cx);
7386
7387 self.change_selections(Some(autoscroll), cx, |s| {
7388 let line_mode = s.line_mode;
7389 s.move_with(|map, selection| {
7390 if !selection.is_empty() && !line_mode {
7391 selection.goal = SelectionGoal::None;
7392 }
7393 let (cursor, goal) = movement::up_by_rows(
7394 map,
7395 selection.end,
7396 row_count,
7397 selection.goal,
7398 false,
7399 text_layout_details,
7400 );
7401 selection.collapse_to(cursor, goal);
7402 });
7403 });
7404 }
7405
7406 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7407 let text_layout_details = &self.text_layout_details(cx);
7408 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7409 s.move_heads_with(|map, head, goal| {
7410 movement::up(map, head, goal, false, text_layout_details)
7411 })
7412 })
7413 }
7414
7415 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7416 self.take_rename(true, cx);
7417
7418 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7419 cx.propagate();
7420 return;
7421 }
7422
7423 let text_layout_details = &self.text_layout_details(cx);
7424 let selection_count = self.selections.count();
7425 let first_selection = self.selections.first_anchor();
7426
7427 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7428 let line_mode = s.line_mode;
7429 s.move_with(|map, selection| {
7430 if !selection.is_empty() && !line_mode {
7431 selection.goal = SelectionGoal::None;
7432 }
7433 let (cursor, goal) = movement::down(
7434 map,
7435 selection.end,
7436 selection.goal,
7437 false,
7438 text_layout_details,
7439 );
7440 selection.collapse_to(cursor, goal);
7441 });
7442 });
7443
7444 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7445 {
7446 cx.propagate();
7447 }
7448 }
7449
7450 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7451 let Some(row_count) = self.visible_row_count() else {
7452 return;
7453 };
7454
7455 let text_layout_details = &self.text_layout_details(cx);
7456
7457 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7458 s.move_heads_with(|map, head, goal| {
7459 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7460 })
7461 })
7462 }
7463
7464 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7465 if self.take_rename(true, cx).is_some() {
7466 return;
7467 }
7468
7469 if self
7470 .context_menu
7471 .write()
7472 .as_mut()
7473 .map(|menu| menu.select_last(self.project.as_ref(), cx))
7474 .unwrap_or(false)
7475 {
7476 return;
7477 }
7478
7479 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7480 cx.propagate();
7481 return;
7482 }
7483
7484 let Some(row_count) = self.visible_row_count() else {
7485 return;
7486 };
7487
7488 let autoscroll = if action.center_cursor {
7489 Autoscroll::center()
7490 } else {
7491 Autoscroll::fit()
7492 };
7493
7494 let text_layout_details = &self.text_layout_details(cx);
7495 self.change_selections(Some(autoscroll), cx, |s| {
7496 let line_mode = s.line_mode;
7497 s.move_with(|map, selection| {
7498 if !selection.is_empty() && !line_mode {
7499 selection.goal = SelectionGoal::None;
7500 }
7501 let (cursor, goal) = movement::down_by_rows(
7502 map,
7503 selection.end,
7504 row_count,
7505 selection.goal,
7506 false,
7507 text_layout_details,
7508 );
7509 selection.collapse_to(cursor, goal);
7510 });
7511 });
7512 }
7513
7514 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7515 let text_layout_details = &self.text_layout_details(cx);
7516 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7517 s.move_heads_with(|map, head, goal| {
7518 movement::down(map, head, goal, false, text_layout_details)
7519 })
7520 });
7521 }
7522
7523 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7524 if let Some(context_menu) = self.context_menu.write().as_mut() {
7525 context_menu.select_first(self.project.as_ref(), cx);
7526 }
7527 }
7528
7529 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7530 if let Some(context_menu) = self.context_menu.write().as_mut() {
7531 context_menu.select_prev(self.project.as_ref(), cx);
7532 }
7533 }
7534
7535 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7536 if let Some(context_menu) = self.context_menu.write().as_mut() {
7537 context_menu.select_next(self.project.as_ref(), cx);
7538 }
7539 }
7540
7541 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7542 if let Some(context_menu) = self.context_menu.write().as_mut() {
7543 context_menu.select_last(self.project.as_ref(), cx);
7544 }
7545 }
7546
7547 pub fn move_to_previous_word_start(
7548 &mut self,
7549 _: &MoveToPreviousWordStart,
7550 cx: &mut ViewContext<Self>,
7551 ) {
7552 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7553 s.move_cursors_with(|map, head, _| {
7554 (
7555 movement::previous_word_start(map, head),
7556 SelectionGoal::None,
7557 )
7558 });
7559 })
7560 }
7561
7562 pub fn move_to_previous_subword_start(
7563 &mut self,
7564 _: &MoveToPreviousSubwordStart,
7565 cx: &mut ViewContext<Self>,
7566 ) {
7567 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7568 s.move_cursors_with(|map, head, _| {
7569 (
7570 movement::previous_subword_start(map, head),
7571 SelectionGoal::None,
7572 )
7573 });
7574 })
7575 }
7576
7577 pub fn select_to_previous_word_start(
7578 &mut self,
7579 _: &SelectToPreviousWordStart,
7580 cx: &mut ViewContext<Self>,
7581 ) {
7582 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7583 s.move_heads_with(|map, head, _| {
7584 (
7585 movement::previous_word_start(map, head),
7586 SelectionGoal::None,
7587 )
7588 });
7589 })
7590 }
7591
7592 pub fn select_to_previous_subword_start(
7593 &mut self,
7594 _: &SelectToPreviousSubwordStart,
7595 cx: &mut ViewContext<Self>,
7596 ) {
7597 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7598 s.move_heads_with(|map, head, _| {
7599 (
7600 movement::previous_subword_start(map, head),
7601 SelectionGoal::None,
7602 )
7603 });
7604 })
7605 }
7606
7607 pub fn delete_to_previous_word_start(
7608 &mut self,
7609 action: &DeleteToPreviousWordStart,
7610 cx: &mut ViewContext<Self>,
7611 ) {
7612 self.transact(cx, |this, cx| {
7613 this.select_autoclose_pair(cx);
7614 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7615 let line_mode = s.line_mode;
7616 s.move_with(|map, selection| {
7617 if selection.is_empty() && !line_mode {
7618 let cursor = if action.ignore_newlines {
7619 movement::previous_word_start(map, selection.head())
7620 } else {
7621 movement::previous_word_start_or_newline(map, selection.head())
7622 };
7623 selection.set_head(cursor, SelectionGoal::None);
7624 }
7625 });
7626 });
7627 this.insert("", cx);
7628 });
7629 }
7630
7631 pub fn delete_to_previous_subword_start(
7632 &mut self,
7633 _: &DeleteToPreviousSubwordStart,
7634 cx: &mut ViewContext<Self>,
7635 ) {
7636 self.transact(cx, |this, cx| {
7637 this.select_autoclose_pair(cx);
7638 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7639 let line_mode = s.line_mode;
7640 s.move_with(|map, selection| {
7641 if selection.is_empty() && !line_mode {
7642 let cursor = movement::previous_subword_start(map, selection.head());
7643 selection.set_head(cursor, SelectionGoal::None);
7644 }
7645 });
7646 });
7647 this.insert("", cx);
7648 });
7649 }
7650
7651 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7652 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7653 s.move_cursors_with(|map, head, _| {
7654 (movement::next_word_end(map, head), SelectionGoal::None)
7655 });
7656 })
7657 }
7658
7659 pub fn move_to_next_subword_end(
7660 &mut self,
7661 _: &MoveToNextSubwordEnd,
7662 cx: &mut ViewContext<Self>,
7663 ) {
7664 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7665 s.move_cursors_with(|map, head, _| {
7666 (movement::next_subword_end(map, head), SelectionGoal::None)
7667 });
7668 })
7669 }
7670
7671 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7672 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7673 s.move_heads_with(|map, head, _| {
7674 (movement::next_word_end(map, head), SelectionGoal::None)
7675 });
7676 })
7677 }
7678
7679 pub fn select_to_next_subword_end(
7680 &mut self,
7681 _: &SelectToNextSubwordEnd,
7682 cx: &mut ViewContext<Self>,
7683 ) {
7684 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7685 s.move_heads_with(|map, head, _| {
7686 (movement::next_subword_end(map, head), SelectionGoal::None)
7687 });
7688 })
7689 }
7690
7691 pub fn delete_to_next_word_end(
7692 &mut self,
7693 action: &DeleteToNextWordEnd,
7694 cx: &mut ViewContext<Self>,
7695 ) {
7696 self.transact(cx, |this, cx| {
7697 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7698 let line_mode = s.line_mode;
7699 s.move_with(|map, selection| {
7700 if selection.is_empty() && !line_mode {
7701 let cursor = if action.ignore_newlines {
7702 movement::next_word_end(map, selection.head())
7703 } else {
7704 movement::next_word_end_or_newline(map, selection.head())
7705 };
7706 selection.set_head(cursor, SelectionGoal::None);
7707 }
7708 });
7709 });
7710 this.insert("", cx);
7711 });
7712 }
7713
7714 pub fn delete_to_next_subword_end(
7715 &mut self,
7716 _: &DeleteToNextSubwordEnd,
7717 cx: &mut ViewContext<Self>,
7718 ) {
7719 self.transact(cx, |this, cx| {
7720 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7721 s.move_with(|map, selection| {
7722 if selection.is_empty() {
7723 let cursor = movement::next_subword_end(map, selection.head());
7724 selection.set_head(cursor, SelectionGoal::None);
7725 }
7726 });
7727 });
7728 this.insert("", cx);
7729 });
7730 }
7731
7732 pub fn move_to_beginning_of_line(
7733 &mut self,
7734 action: &MoveToBeginningOfLine,
7735 cx: &mut ViewContext<Self>,
7736 ) {
7737 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7738 s.move_cursors_with(|map, head, _| {
7739 (
7740 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7741 SelectionGoal::None,
7742 )
7743 });
7744 })
7745 }
7746
7747 pub fn select_to_beginning_of_line(
7748 &mut self,
7749 action: &SelectToBeginningOfLine,
7750 cx: &mut ViewContext<Self>,
7751 ) {
7752 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7753 s.move_heads_with(|map, head, _| {
7754 (
7755 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7756 SelectionGoal::None,
7757 )
7758 });
7759 });
7760 }
7761
7762 pub fn delete_to_beginning_of_line(
7763 &mut self,
7764 _: &DeleteToBeginningOfLine,
7765 cx: &mut ViewContext<Self>,
7766 ) {
7767 self.transact(cx, |this, cx| {
7768 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7769 s.move_with(|_, selection| {
7770 selection.reversed = true;
7771 });
7772 });
7773
7774 this.select_to_beginning_of_line(
7775 &SelectToBeginningOfLine {
7776 stop_at_soft_wraps: false,
7777 },
7778 cx,
7779 );
7780 this.backspace(&Backspace, cx);
7781 });
7782 }
7783
7784 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7785 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7786 s.move_cursors_with(|map, head, _| {
7787 (
7788 movement::line_end(map, head, action.stop_at_soft_wraps),
7789 SelectionGoal::None,
7790 )
7791 });
7792 })
7793 }
7794
7795 pub fn select_to_end_of_line(
7796 &mut self,
7797 action: &SelectToEndOfLine,
7798 cx: &mut ViewContext<Self>,
7799 ) {
7800 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7801 s.move_heads_with(|map, head, _| {
7802 (
7803 movement::line_end(map, head, action.stop_at_soft_wraps),
7804 SelectionGoal::None,
7805 )
7806 });
7807 })
7808 }
7809
7810 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7811 self.transact(cx, |this, cx| {
7812 this.select_to_end_of_line(
7813 &SelectToEndOfLine {
7814 stop_at_soft_wraps: false,
7815 },
7816 cx,
7817 );
7818 this.delete(&Delete, cx);
7819 });
7820 }
7821
7822 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7823 self.transact(cx, |this, cx| {
7824 this.select_to_end_of_line(
7825 &SelectToEndOfLine {
7826 stop_at_soft_wraps: false,
7827 },
7828 cx,
7829 );
7830 this.cut(&Cut, cx);
7831 });
7832 }
7833
7834 pub fn move_to_start_of_paragraph(
7835 &mut self,
7836 _: &MoveToStartOfParagraph,
7837 cx: &mut ViewContext<Self>,
7838 ) {
7839 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7840 cx.propagate();
7841 return;
7842 }
7843
7844 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7845 s.move_with(|map, selection| {
7846 selection.collapse_to(
7847 movement::start_of_paragraph(map, selection.head(), 1),
7848 SelectionGoal::None,
7849 )
7850 });
7851 })
7852 }
7853
7854 pub fn move_to_end_of_paragraph(
7855 &mut self,
7856 _: &MoveToEndOfParagraph,
7857 cx: &mut ViewContext<Self>,
7858 ) {
7859 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7860 cx.propagate();
7861 return;
7862 }
7863
7864 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7865 s.move_with(|map, selection| {
7866 selection.collapse_to(
7867 movement::end_of_paragraph(map, selection.head(), 1),
7868 SelectionGoal::None,
7869 )
7870 });
7871 })
7872 }
7873
7874 pub fn select_to_start_of_paragraph(
7875 &mut self,
7876 _: &SelectToStartOfParagraph,
7877 cx: &mut ViewContext<Self>,
7878 ) {
7879 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7880 cx.propagate();
7881 return;
7882 }
7883
7884 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7885 s.move_heads_with(|map, head, _| {
7886 (
7887 movement::start_of_paragraph(map, head, 1),
7888 SelectionGoal::None,
7889 )
7890 });
7891 })
7892 }
7893
7894 pub fn select_to_end_of_paragraph(
7895 &mut self,
7896 _: &SelectToEndOfParagraph,
7897 cx: &mut ViewContext<Self>,
7898 ) {
7899 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7900 cx.propagate();
7901 return;
7902 }
7903
7904 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7905 s.move_heads_with(|map, head, _| {
7906 (
7907 movement::end_of_paragraph(map, head, 1),
7908 SelectionGoal::None,
7909 )
7910 });
7911 })
7912 }
7913
7914 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7915 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7916 cx.propagate();
7917 return;
7918 }
7919
7920 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7921 s.select_ranges(vec![0..0]);
7922 });
7923 }
7924
7925 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7926 let mut selection = self.selections.last::<Point>(cx);
7927 selection.set_head(Point::zero(), SelectionGoal::None);
7928
7929 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7930 s.select(vec![selection]);
7931 });
7932 }
7933
7934 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7935 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7936 cx.propagate();
7937 return;
7938 }
7939
7940 let cursor = self.buffer.read(cx).read(cx).len();
7941 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7942 s.select_ranges(vec![cursor..cursor])
7943 });
7944 }
7945
7946 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7947 self.nav_history = nav_history;
7948 }
7949
7950 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7951 self.nav_history.as_ref()
7952 }
7953
7954 fn push_to_nav_history(
7955 &mut self,
7956 cursor_anchor: Anchor,
7957 new_position: Option<Point>,
7958 cx: &mut ViewContext<Self>,
7959 ) {
7960 if let Some(nav_history) = self.nav_history.as_mut() {
7961 let buffer = self.buffer.read(cx).read(cx);
7962 let cursor_position = cursor_anchor.to_point(&buffer);
7963 let scroll_state = self.scroll_manager.anchor();
7964 let scroll_top_row = scroll_state.top_row(&buffer);
7965 drop(buffer);
7966
7967 if let Some(new_position) = new_position {
7968 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7969 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7970 return;
7971 }
7972 }
7973
7974 nav_history.push(
7975 Some(NavigationData {
7976 cursor_anchor,
7977 cursor_position,
7978 scroll_anchor: scroll_state,
7979 scroll_top_row,
7980 }),
7981 cx,
7982 );
7983 }
7984 }
7985
7986 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7987 let buffer = self.buffer.read(cx).snapshot(cx);
7988 let mut selection = self.selections.first::<usize>(cx);
7989 selection.set_head(buffer.len(), SelectionGoal::None);
7990 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7991 s.select(vec![selection]);
7992 });
7993 }
7994
7995 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7996 let end = self.buffer.read(cx).read(cx).len();
7997 self.change_selections(None, cx, |s| {
7998 s.select_ranges(vec![0..end]);
7999 });
8000 }
8001
8002 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8003 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8004 let mut selections = self.selections.all::<Point>(cx);
8005 let max_point = display_map.buffer_snapshot.max_point();
8006 for selection in &mut selections {
8007 let rows = selection.spanned_rows(true, &display_map);
8008 selection.start = Point::new(rows.start.0, 0);
8009 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8010 selection.reversed = false;
8011 }
8012 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8013 s.select(selections);
8014 });
8015 }
8016
8017 pub fn split_selection_into_lines(
8018 &mut self,
8019 _: &SplitSelectionIntoLines,
8020 cx: &mut ViewContext<Self>,
8021 ) {
8022 let mut to_unfold = Vec::new();
8023 let mut new_selection_ranges = Vec::new();
8024 {
8025 let selections = self.selections.all::<Point>(cx);
8026 let buffer = self.buffer.read(cx).read(cx);
8027 for selection in selections {
8028 for row in selection.start.row..selection.end.row {
8029 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8030 new_selection_ranges.push(cursor..cursor);
8031 }
8032 new_selection_ranges.push(selection.end..selection.end);
8033 to_unfold.push(selection.start..selection.end);
8034 }
8035 }
8036 self.unfold_ranges(to_unfold, true, true, cx);
8037 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8038 s.select_ranges(new_selection_ranges);
8039 });
8040 }
8041
8042 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8043 self.add_selection(true, cx);
8044 }
8045
8046 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8047 self.add_selection(false, cx);
8048 }
8049
8050 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8051 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8052 let mut selections = self.selections.all::<Point>(cx);
8053 let text_layout_details = self.text_layout_details(cx);
8054 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8055 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8056 let range = oldest_selection.display_range(&display_map).sorted();
8057
8058 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8059 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8060 let positions = start_x.min(end_x)..start_x.max(end_x);
8061
8062 selections.clear();
8063 let mut stack = Vec::new();
8064 for row in range.start.row().0..=range.end.row().0 {
8065 if let Some(selection) = self.selections.build_columnar_selection(
8066 &display_map,
8067 DisplayRow(row),
8068 &positions,
8069 oldest_selection.reversed,
8070 &text_layout_details,
8071 ) {
8072 stack.push(selection.id);
8073 selections.push(selection);
8074 }
8075 }
8076
8077 if above {
8078 stack.reverse();
8079 }
8080
8081 AddSelectionsState { above, stack }
8082 });
8083
8084 let last_added_selection = *state.stack.last().unwrap();
8085 let mut new_selections = Vec::new();
8086 if above == state.above {
8087 let end_row = if above {
8088 DisplayRow(0)
8089 } else {
8090 display_map.max_point().row()
8091 };
8092
8093 'outer: for selection in selections {
8094 if selection.id == last_added_selection {
8095 let range = selection.display_range(&display_map).sorted();
8096 debug_assert_eq!(range.start.row(), range.end.row());
8097 let mut row = range.start.row();
8098 let positions =
8099 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8100 px(start)..px(end)
8101 } else {
8102 let start_x =
8103 display_map.x_for_display_point(range.start, &text_layout_details);
8104 let end_x =
8105 display_map.x_for_display_point(range.end, &text_layout_details);
8106 start_x.min(end_x)..start_x.max(end_x)
8107 };
8108
8109 while row != end_row {
8110 if above {
8111 row.0 -= 1;
8112 } else {
8113 row.0 += 1;
8114 }
8115
8116 if let Some(new_selection) = self.selections.build_columnar_selection(
8117 &display_map,
8118 row,
8119 &positions,
8120 selection.reversed,
8121 &text_layout_details,
8122 ) {
8123 state.stack.push(new_selection.id);
8124 if above {
8125 new_selections.push(new_selection);
8126 new_selections.push(selection);
8127 } else {
8128 new_selections.push(selection);
8129 new_selections.push(new_selection);
8130 }
8131
8132 continue 'outer;
8133 }
8134 }
8135 }
8136
8137 new_selections.push(selection);
8138 }
8139 } else {
8140 new_selections = selections;
8141 new_selections.retain(|s| s.id != last_added_selection);
8142 state.stack.pop();
8143 }
8144
8145 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8146 s.select(new_selections);
8147 });
8148 if state.stack.len() > 1 {
8149 self.add_selections_state = Some(state);
8150 }
8151 }
8152
8153 pub fn select_next_match_internal(
8154 &mut self,
8155 display_map: &DisplaySnapshot,
8156 replace_newest: bool,
8157 autoscroll: Option<Autoscroll>,
8158 cx: &mut ViewContext<Self>,
8159 ) -> Result<()> {
8160 fn select_next_match_ranges(
8161 this: &mut Editor,
8162 range: Range<usize>,
8163 replace_newest: bool,
8164 auto_scroll: Option<Autoscroll>,
8165 cx: &mut ViewContext<Editor>,
8166 ) {
8167 this.unfold_ranges([range.clone()], false, true, cx);
8168 this.change_selections(auto_scroll, cx, |s| {
8169 if replace_newest {
8170 s.delete(s.newest_anchor().id);
8171 }
8172 s.insert_range(range.clone());
8173 });
8174 }
8175
8176 let buffer = &display_map.buffer_snapshot;
8177 let mut selections = self.selections.all::<usize>(cx);
8178 if let Some(mut select_next_state) = self.select_next_state.take() {
8179 let query = &select_next_state.query;
8180 if !select_next_state.done {
8181 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8182 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8183 let mut next_selected_range = None;
8184
8185 let bytes_after_last_selection =
8186 buffer.bytes_in_range(last_selection.end..buffer.len());
8187 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8188 let query_matches = query
8189 .stream_find_iter(bytes_after_last_selection)
8190 .map(|result| (last_selection.end, result))
8191 .chain(
8192 query
8193 .stream_find_iter(bytes_before_first_selection)
8194 .map(|result| (0, result)),
8195 );
8196
8197 for (start_offset, query_match) in query_matches {
8198 let query_match = query_match.unwrap(); // can only fail due to I/O
8199 let offset_range =
8200 start_offset + query_match.start()..start_offset + query_match.end();
8201 let display_range = offset_range.start.to_display_point(display_map)
8202 ..offset_range.end.to_display_point(display_map);
8203
8204 if !select_next_state.wordwise
8205 || (!movement::is_inside_word(display_map, display_range.start)
8206 && !movement::is_inside_word(display_map, display_range.end))
8207 {
8208 // TODO: This is n^2, because we might check all the selections
8209 if !selections
8210 .iter()
8211 .any(|selection| selection.range().overlaps(&offset_range))
8212 {
8213 next_selected_range = Some(offset_range);
8214 break;
8215 }
8216 }
8217 }
8218
8219 if let Some(next_selected_range) = next_selected_range {
8220 select_next_match_ranges(
8221 self,
8222 next_selected_range,
8223 replace_newest,
8224 autoscroll,
8225 cx,
8226 );
8227 } else {
8228 select_next_state.done = true;
8229 }
8230 }
8231
8232 self.select_next_state = Some(select_next_state);
8233 } else {
8234 let mut only_carets = true;
8235 let mut same_text_selected = true;
8236 let mut selected_text = None;
8237
8238 let mut selections_iter = selections.iter().peekable();
8239 while let Some(selection) = selections_iter.next() {
8240 if selection.start != selection.end {
8241 only_carets = false;
8242 }
8243
8244 if same_text_selected {
8245 if selected_text.is_none() {
8246 selected_text =
8247 Some(buffer.text_for_range(selection.range()).collect::<String>());
8248 }
8249
8250 if let Some(next_selection) = selections_iter.peek() {
8251 if next_selection.range().len() == selection.range().len() {
8252 let next_selected_text = buffer
8253 .text_for_range(next_selection.range())
8254 .collect::<String>();
8255 if Some(next_selected_text) != selected_text {
8256 same_text_selected = false;
8257 selected_text = None;
8258 }
8259 } else {
8260 same_text_selected = false;
8261 selected_text = None;
8262 }
8263 }
8264 }
8265 }
8266
8267 if only_carets {
8268 for selection in &mut selections {
8269 let word_range = movement::surrounding_word(
8270 display_map,
8271 selection.start.to_display_point(display_map),
8272 );
8273 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8274 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8275 selection.goal = SelectionGoal::None;
8276 selection.reversed = false;
8277 select_next_match_ranges(
8278 self,
8279 selection.start..selection.end,
8280 replace_newest,
8281 autoscroll,
8282 cx,
8283 );
8284 }
8285
8286 if selections.len() == 1 {
8287 let selection = selections
8288 .last()
8289 .expect("ensured that there's only one selection");
8290 let query = buffer
8291 .text_for_range(selection.start..selection.end)
8292 .collect::<String>();
8293 let is_empty = query.is_empty();
8294 let select_state = SelectNextState {
8295 query: AhoCorasick::new(&[query])?,
8296 wordwise: true,
8297 done: is_empty,
8298 };
8299 self.select_next_state = Some(select_state);
8300 } else {
8301 self.select_next_state = None;
8302 }
8303 } else if let Some(selected_text) = selected_text {
8304 self.select_next_state = Some(SelectNextState {
8305 query: AhoCorasick::new(&[selected_text])?,
8306 wordwise: false,
8307 done: false,
8308 });
8309 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8310 }
8311 }
8312 Ok(())
8313 }
8314
8315 pub fn select_all_matches(
8316 &mut self,
8317 _action: &SelectAllMatches,
8318 cx: &mut ViewContext<Self>,
8319 ) -> Result<()> {
8320 self.push_to_selection_history();
8321 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8322
8323 self.select_next_match_internal(&display_map, false, None, cx)?;
8324 let Some(select_next_state) = self.select_next_state.as_mut() else {
8325 return Ok(());
8326 };
8327 if select_next_state.done {
8328 return Ok(());
8329 }
8330
8331 let mut new_selections = self.selections.all::<usize>(cx);
8332
8333 let buffer = &display_map.buffer_snapshot;
8334 let query_matches = select_next_state
8335 .query
8336 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8337
8338 for query_match in query_matches {
8339 let query_match = query_match.unwrap(); // can only fail due to I/O
8340 let offset_range = query_match.start()..query_match.end();
8341 let display_range = offset_range.start.to_display_point(&display_map)
8342 ..offset_range.end.to_display_point(&display_map);
8343
8344 if !select_next_state.wordwise
8345 || (!movement::is_inside_word(&display_map, display_range.start)
8346 && !movement::is_inside_word(&display_map, display_range.end))
8347 {
8348 self.selections.change_with(cx, |selections| {
8349 new_selections.push(Selection {
8350 id: selections.new_selection_id(),
8351 start: offset_range.start,
8352 end: offset_range.end,
8353 reversed: false,
8354 goal: SelectionGoal::None,
8355 });
8356 });
8357 }
8358 }
8359
8360 new_selections.sort_by_key(|selection| selection.start);
8361 let mut ix = 0;
8362 while ix + 1 < new_selections.len() {
8363 let current_selection = &new_selections[ix];
8364 let next_selection = &new_selections[ix + 1];
8365 if current_selection.range().overlaps(&next_selection.range()) {
8366 if current_selection.id < next_selection.id {
8367 new_selections.remove(ix + 1);
8368 } else {
8369 new_selections.remove(ix);
8370 }
8371 } else {
8372 ix += 1;
8373 }
8374 }
8375
8376 select_next_state.done = true;
8377 self.unfold_ranges(
8378 new_selections.iter().map(|selection| selection.range()),
8379 false,
8380 false,
8381 cx,
8382 );
8383 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8384 selections.select(new_selections)
8385 });
8386
8387 Ok(())
8388 }
8389
8390 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8391 self.push_to_selection_history();
8392 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8393 self.select_next_match_internal(
8394 &display_map,
8395 action.replace_newest,
8396 Some(Autoscroll::newest()),
8397 cx,
8398 )?;
8399 Ok(())
8400 }
8401
8402 pub fn select_previous(
8403 &mut self,
8404 action: &SelectPrevious,
8405 cx: &mut ViewContext<Self>,
8406 ) -> Result<()> {
8407 self.push_to_selection_history();
8408 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8409 let buffer = &display_map.buffer_snapshot;
8410 let mut selections = self.selections.all::<usize>(cx);
8411 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8412 let query = &select_prev_state.query;
8413 if !select_prev_state.done {
8414 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8415 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8416 let mut next_selected_range = None;
8417 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8418 let bytes_before_last_selection =
8419 buffer.reversed_bytes_in_range(0..last_selection.start);
8420 let bytes_after_first_selection =
8421 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8422 let query_matches = query
8423 .stream_find_iter(bytes_before_last_selection)
8424 .map(|result| (last_selection.start, result))
8425 .chain(
8426 query
8427 .stream_find_iter(bytes_after_first_selection)
8428 .map(|result| (buffer.len(), result)),
8429 );
8430 for (end_offset, query_match) in query_matches {
8431 let query_match = query_match.unwrap(); // can only fail due to I/O
8432 let offset_range =
8433 end_offset - query_match.end()..end_offset - query_match.start();
8434 let display_range = offset_range.start.to_display_point(&display_map)
8435 ..offset_range.end.to_display_point(&display_map);
8436
8437 if !select_prev_state.wordwise
8438 || (!movement::is_inside_word(&display_map, display_range.start)
8439 && !movement::is_inside_word(&display_map, display_range.end))
8440 {
8441 next_selected_range = Some(offset_range);
8442 break;
8443 }
8444 }
8445
8446 if let Some(next_selected_range) = next_selected_range {
8447 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8448 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8449 if action.replace_newest {
8450 s.delete(s.newest_anchor().id);
8451 }
8452 s.insert_range(next_selected_range);
8453 });
8454 } else {
8455 select_prev_state.done = true;
8456 }
8457 }
8458
8459 self.select_prev_state = Some(select_prev_state);
8460 } else {
8461 let mut only_carets = true;
8462 let mut same_text_selected = true;
8463 let mut selected_text = None;
8464
8465 let mut selections_iter = selections.iter().peekable();
8466 while let Some(selection) = selections_iter.next() {
8467 if selection.start != selection.end {
8468 only_carets = false;
8469 }
8470
8471 if same_text_selected {
8472 if selected_text.is_none() {
8473 selected_text =
8474 Some(buffer.text_for_range(selection.range()).collect::<String>());
8475 }
8476
8477 if let Some(next_selection) = selections_iter.peek() {
8478 if next_selection.range().len() == selection.range().len() {
8479 let next_selected_text = buffer
8480 .text_for_range(next_selection.range())
8481 .collect::<String>();
8482 if Some(next_selected_text) != selected_text {
8483 same_text_selected = false;
8484 selected_text = None;
8485 }
8486 } else {
8487 same_text_selected = false;
8488 selected_text = None;
8489 }
8490 }
8491 }
8492 }
8493
8494 if only_carets {
8495 for selection in &mut selections {
8496 let word_range = movement::surrounding_word(
8497 &display_map,
8498 selection.start.to_display_point(&display_map),
8499 );
8500 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8501 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8502 selection.goal = SelectionGoal::None;
8503 selection.reversed = false;
8504 }
8505 if selections.len() == 1 {
8506 let selection = selections
8507 .last()
8508 .expect("ensured that there's only one selection");
8509 let query = buffer
8510 .text_for_range(selection.start..selection.end)
8511 .collect::<String>();
8512 let is_empty = query.is_empty();
8513 let select_state = SelectNextState {
8514 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8515 wordwise: true,
8516 done: is_empty,
8517 };
8518 self.select_prev_state = Some(select_state);
8519 } else {
8520 self.select_prev_state = None;
8521 }
8522
8523 self.unfold_ranges(
8524 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8525 false,
8526 true,
8527 cx,
8528 );
8529 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8530 s.select(selections);
8531 });
8532 } else if let Some(selected_text) = selected_text {
8533 self.select_prev_state = Some(SelectNextState {
8534 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8535 wordwise: false,
8536 done: false,
8537 });
8538 self.select_previous(action, cx)?;
8539 }
8540 }
8541 Ok(())
8542 }
8543
8544 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8545 let text_layout_details = &self.text_layout_details(cx);
8546 self.transact(cx, |this, cx| {
8547 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8548 let mut edits = Vec::new();
8549 let mut selection_edit_ranges = Vec::new();
8550 let mut last_toggled_row = None;
8551 let snapshot = this.buffer.read(cx).read(cx);
8552 let empty_str: Arc<str> = Arc::default();
8553 let mut suffixes_inserted = Vec::new();
8554
8555 fn comment_prefix_range(
8556 snapshot: &MultiBufferSnapshot,
8557 row: MultiBufferRow,
8558 comment_prefix: &str,
8559 comment_prefix_whitespace: &str,
8560 ) -> Range<Point> {
8561 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8562
8563 let mut line_bytes = snapshot
8564 .bytes_in_range(start..snapshot.max_point())
8565 .flatten()
8566 .copied();
8567
8568 // If this line currently begins with the line comment prefix, then record
8569 // the range containing the prefix.
8570 if line_bytes
8571 .by_ref()
8572 .take(comment_prefix.len())
8573 .eq(comment_prefix.bytes())
8574 {
8575 // Include any whitespace that matches the comment prefix.
8576 let matching_whitespace_len = line_bytes
8577 .zip(comment_prefix_whitespace.bytes())
8578 .take_while(|(a, b)| a == b)
8579 .count() as u32;
8580 let end = Point::new(
8581 start.row,
8582 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8583 );
8584 start..end
8585 } else {
8586 start..start
8587 }
8588 }
8589
8590 fn comment_suffix_range(
8591 snapshot: &MultiBufferSnapshot,
8592 row: MultiBufferRow,
8593 comment_suffix: &str,
8594 comment_suffix_has_leading_space: bool,
8595 ) -> Range<Point> {
8596 let end = Point::new(row.0, snapshot.line_len(row));
8597 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8598
8599 let mut line_end_bytes = snapshot
8600 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8601 .flatten()
8602 .copied();
8603
8604 let leading_space_len = if suffix_start_column > 0
8605 && line_end_bytes.next() == Some(b' ')
8606 && comment_suffix_has_leading_space
8607 {
8608 1
8609 } else {
8610 0
8611 };
8612
8613 // If this line currently begins with the line comment prefix, then record
8614 // the range containing the prefix.
8615 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8616 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8617 start..end
8618 } else {
8619 end..end
8620 }
8621 }
8622
8623 // TODO: Handle selections that cross excerpts
8624 for selection in &mut selections {
8625 let start_column = snapshot
8626 .indent_size_for_line(MultiBufferRow(selection.start.row))
8627 .len;
8628 let language = if let Some(language) =
8629 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8630 {
8631 language
8632 } else {
8633 continue;
8634 };
8635
8636 selection_edit_ranges.clear();
8637
8638 // If multiple selections contain a given row, avoid processing that
8639 // row more than once.
8640 let mut start_row = MultiBufferRow(selection.start.row);
8641 if last_toggled_row == Some(start_row) {
8642 start_row = start_row.next_row();
8643 }
8644 let end_row =
8645 if selection.end.row > selection.start.row && selection.end.column == 0 {
8646 MultiBufferRow(selection.end.row - 1)
8647 } else {
8648 MultiBufferRow(selection.end.row)
8649 };
8650 last_toggled_row = Some(end_row);
8651
8652 if start_row > end_row {
8653 continue;
8654 }
8655
8656 // If the language has line comments, toggle those.
8657 let full_comment_prefixes = language.line_comment_prefixes();
8658 if !full_comment_prefixes.is_empty() {
8659 let first_prefix = full_comment_prefixes
8660 .first()
8661 .expect("prefixes is non-empty");
8662 let prefix_trimmed_lengths = full_comment_prefixes
8663 .iter()
8664 .map(|p| p.trim_end_matches(' ').len())
8665 .collect::<SmallVec<[usize; 4]>>();
8666
8667 let mut all_selection_lines_are_comments = true;
8668
8669 for row in start_row.0..=end_row.0 {
8670 let row = MultiBufferRow(row);
8671 if start_row < end_row && snapshot.is_line_blank(row) {
8672 continue;
8673 }
8674
8675 let prefix_range = full_comment_prefixes
8676 .iter()
8677 .zip(prefix_trimmed_lengths.iter().copied())
8678 .map(|(prefix, trimmed_prefix_len)| {
8679 comment_prefix_range(
8680 snapshot.deref(),
8681 row,
8682 &prefix[..trimmed_prefix_len],
8683 &prefix[trimmed_prefix_len..],
8684 )
8685 })
8686 .max_by_key(|range| range.end.column - range.start.column)
8687 .expect("prefixes is non-empty");
8688
8689 if prefix_range.is_empty() {
8690 all_selection_lines_are_comments = false;
8691 }
8692
8693 selection_edit_ranges.push(prefix_range);
8694 }
8695
8696 if all_selection_lines_are_comments {
8697 edits.extend(
8698 selection_edit_ranges
8699 .iter()
8700 .cloned()
8701 .map(|range| (range, empty_str.clone())),
8702 );
8703 } else {
8704 let min_column = selection_edit_ranges
8705 .iter()
8706 .map(|range| range.start.column)
8707 .min()
8708 .unwrap_or(0);
8709 edits.extend(selection_edit_ranges.iter().map(|range| {
8710 let position = Point::new(range.start.row, min_column);
8711 (position..position, first_prefix.clone())
8712 }));
8713 }
8714 } else if let Some((full_comment_prefix, comment_suffix)) =
8715 language.block_comment_delimiters()
8716 {
8717 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8718 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8719 let prefix_range = comment_prefix_range(
8720 snapshot.deref(),
8721 start_row,
8722 comment_prefix,
8723 comment_prefix_whitespace,
8724 );
8725 let suffix_range = comment_suffix_range(
8726 snapshot.deref(),
8727 end_row,
8728 comment_suffix.trim_start_matches(' '),
8729 comment_suffix.starts_with(' '),
8730 );
8731
8732 if prefix_range.is_empty() || suffix_range.is_empty() {
8733 edits.push((
8734 prefix_range.start..prefix_range.start,
8735 full_comment_prefix.clone(),
8736 ));
8737 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8738 suffixes_inserted.push((end_row, comment_suffix.len()));
8739 } else {
8740 edits.push((prefix_range, empty_str.clone()));
8741 edits.push((suffix_range, empty_str.clone()));
8742 }
8743 } else {
8744 continue;
8745 }
8746 }
8747
8748 drop(snapshot);
8749 this.buffer.update(cx, |buffer, cx| {
8750 buffer.edit(edits, None, cx);
8751 });
8752
8753 // Adjust selections so that they end before any comment suffixes that
8754 // were inserted.
8755 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8756 let mut selections = this.selections.all::<Point>(cx);
8757 let snapshot = this.buffer.read(cx).read(cx);
8758 for selection in &mut selections {
8759 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8760 match row.cmp(&MultiBufferRow(selection.end.row)) {
8761 Ordering::Less => {
8762 suffixes_inserted.next();
8763 continue;
8764 }
8765 Ordering::Greater => break,
8766 Ordering::Equal => {
8767 if selection.end.column == snapshot.line_len(row) {
8768 if selection.is_empty() {
8769 selection.start.column -= suffix_len as u32;
8770 }
8771 selection.end.column -= suffix_len as u32;
8772 }
8773 break;
8774 }
8775 }
8776 }
8777 }
8778
8779 drop(snapshot);
8780 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8781
8782 let selections = this.selections.all::<Point>(cx);
8783 let selections_on_single_row = selections.windows(2).all(|selections| {
8784 selections[0].start.row == selections[1].start.row
8785 && selections[0].end.row == selections[1].end.row
8786 && selections[0].start.row == selections[0].end.row
8787 });
8788 let selections_selecting = selections
8789 .iter()
8790 .any(|selection| selection.start != selection.end);
8791 let advance_downwards = action.advance_downwards
8792 && selections_on_single_row
8793 && !selections_selecting
8794 && !matches!(this.mode, EditorMode::SingleLine { .. });
8795
8796 if advance_downwards {
8797 let snapshot = this.buffer.read(cx).snapshot(cx);
8798
8799 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8800 s.move_cursors_with(|display_snapshot, display_point, _| {
8801 let mut point = display_point.to_point(display_snapshot);
8802 point.row += 1;
8803 point = snapshot.clip_point(point, Bias::Left);
8804 let display_point = point.to_display_point(display_snapshot);
8805 let goal = SelectionGoal::HorizontalPosition(
8806 display_snapshot
8807 .x_for_display_point(display_point, text_layout_details)
8808 .into(),
8809 );
8810 (display_point, goal)
8811 })
8812 });
8813 }
8814 });
8815 }
8816
8817 pub fn select_enclosing_symbol(
8818 &mut self,
8819 _: &SelectEnclosingSymbol,
8820 cx: &mut ViewContext<Self>,
8821 ) {
8822 let buffer = self.buffer.read(cx).snapshot(cx);
8823 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8824
8825 fn update_selection(
8826 selection: &Selection<usize>,
8827 buffer_snap: &MultiBufferSnapshot,
8828 ) -> Option<Selection<usize>> {
8829 let cursor = selection.head();
8830 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8831 for symbol in symbols.iter().rev() {
8832 let start = symbol.range.start.to_offset(buffer_snap);
8833 let end = symbol.range.end.to_offset(buffer_snap);
8834 let new_range = start..end;
8835 if start < selection.start || end > selection.end {
8836 return Some(Selection {
8837 id: selection.id,
8838 start: new_range.start,
8839 end: new_range.end,
8840 goal: SelectionGoal::None,
8841 reversed: selection.reversed,
8842 });
8843 }
8844 }
8845 None
8846 }
8847
8848 let mut selected_larger_symbol = false;
8849 let new_selections = old_selections
8850 .iter()
8851 .map(|selection| match update_selection(selection, &buffer) {
8852 Some(new_selection) => {
8853 if new_selection.range() != selection.range() {
8854 selected_larger_symbol = true;
8855 }
8856 new_selection
8857 }
8858 None => selection.clone(),
8859 })
8860 .collect::<Vec<_>>();
8861
8862 if selected_larger_symbol {
8863 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8864 s.select(new_selections);
8865 });
8866 }
8867 }
8868
8869 pub fn select_larger_syntax_node(
8870 &mut self,
8871 _: &SelectLargerSyntaxNode,
8872 cx: &mut ViewContext<Self>,
8873 ) {
8874 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8875 let buffer = self.buffer.read(cx).snapshot(cx);
8876 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8877
8878 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8879 let mut selected_larger_node = false;
8880 let new_selections = old_selections
8881 .iter()
8882 .map(|selection| {
8883 let old_range = selection.start..selection.end;
8884 let mut new_range = old_range.clone();
8885 while let Some(containing_range) =
8886 buffer.range_for_syntax_ancestor(new_range.clone())
8887 {
8888 new_range = containing_range;
8889 if !display_map.intersects_fold(new_range.start)
8890 && !display_map.intersects_fold(new_range.end)
8891 {
8892 break;
8893 }
8894 }
8895
8896 selected_larger_node |= new_range != old_range;
8897 Selection {
8898 id: selection.id,
8899 start: new_range.start,
8900 end: new_range.end,
8901 goal: SelectionGoal::None,
8902 reversed: selection.reversed,
8903 }
8904 })
8905 .collect::<Vec<_>>();
8906
8907 if selected_larger_node {
8908 stack.push(old_selections);
8909 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8910 s.select(new_selections);
8911 });
8912 }
8913 self.select_larger_syntax_node_stack = stack;
8914 }
8915
8916 pub fn select_smaller_syntax_node(
8917 &mut self,
8918 _: &SelectSmallerSyntaxNode,
8919 cx: &mut ViewContext<Self>,
8920 ) {
8921 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8922 if let Some(selections) = stack.pop() {
8923 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8924 s.select(selections.to_vec());
8925 });
8926 }
8927 self.select_larger_syntax_node_stack = stack;
8928 }
8929
8930 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8931 if !EditorSettings::get_global(cx).gutter.runnables {
8932 self.clear_tasks();
8933 return Task::ready(());
8934 }
8935 let project = self.project.clone();
8936 cx.spawn(|this, mut cx| async move {
8937 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8938 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8939 }) else {
8940 return;
8941 };
8942
8943 let Some(project) = project else {
8944 return;
8945 };
8946
8947 let hide_runnables = project
8948 .update(&mut cx, |project, cx| {
8949 // Do not display any test indicators in non-dev server remote projects.
8950 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8951 })
8952 .unwrap_or(true);
8953 if hide_runnables {
8954 return;
8955 }
8956 let new_rows =
8957 cx.background_executor()
8958 .spawn({
8959 let snapshot = display_snapshot.clone();
8960 async move {
8961 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8962 }
8963 })
8964 .await;
8965 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8966
8967 this.update(&mut cx, |this, _| {
8968 this.clear_tasks();
8969 for (key, value) in rows {
8970 this.insert_tasks(key, value);
8971 }
8972 })
8973 .ok();
8974 })
8975 }
8976 fn fetch_runnable_ranges(
8977 snapshot: &DisplaySnapshot,
8978 range: Range<Anchor>,
8979 ) -> Vec<language::RunnableRange> {
8980 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8981 }
8982
8983 fn runnable_rows(
8984 project: Model<Project>,
8985 snapshot: DisplaySnapshot,
8986 runnable_ranges: Vec<RunnableRange>,
8987 mut cx: AsyncWindowContext,
8988 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8989 runnable_ranges
8990 .into_iter()
8991 .filter_map(|mut runnable| {
8992 let tasks = cx
8993 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8994 .ok()?;
8995 if tasks.is_empty() {
8996 return None;
8997 }
8998
8999 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9000
9001 let row = snapshot
9002 .buffer_snapshot
9003 .buffer_line_for_row(MultiBufferRow(point.row))?
9004 .1
9005 .start
9006 .row;
9007
9008 let context_range =
9009 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9010 Some((
9011 (runnable.buffer_id, row),
9012 RunnableTasks {
9013 templates: tasks,
9014 offset: MultiBufferOffset(runnable.run_range.start),
9015 context_range,
9016 column: point.column,
9017 extra_variables: runnable.extra_captures,
9018 },
9019 ))
9020 })
9021 .collect()
9022 }
9023
9024 fn templates_with_tags(
9025 project: &Model<Project>,
9026 runnable: &mut Runnable,
9027 cx: &WindowContext<'_>,
9028 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9029 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9030 let (worktree_id, file) = project
9031 .buffer_for_id(runnable.buffer, cx)
9032 .and_then(|buffer| buffer.read(cx).file())
9033 .map(|file| (file.worktree_id(cx), file.clone()))
9034 .unzip();
9035
9036 (project.task_inventory().clone(), worktree_id, file)
9037 });
9038
9039 let inventory = inventory.read(cx);
9040 let tags = mem::take(&mut runnable.tags);
9041 let mut tags: Vec<_> = tags
9042 .into_iter()
9043 .flat_map(|tag| {
9044 let tag = tag.0.clone();
9045 inventory
9046 .list_tasks(
9047 file.clone(),
9048 Some(runnable.language.clone()),
9049 worktree_id,
9050 cx,
9051 )
9052 .into_iter()
9053 .filter(move |(_, template)| {
9054 template.tags.iter().any(|source_tag| source_tag == &tag)
9055 })
9056 })
9057 .sorted_by_key(|(kind, _)| kind.to_owned())
9058 .collect();
9059 if let Some((leading_tag_source, _)) = tags.first() {
9060 // Strongest source wins; if we have worktree tag binding, prefer that to
9061 // global and language bindings;
9062 // if we have a global binding, prefer that to language binding.
9063 let first_mismatch = tags
9064 .iter()
9065 .position(|(tag_source, _)| tag_source != leading_tag_source);
9066 if let Some(index) = first_mismatch {
9067 tags.truncate(index);
9068 }
9069 }
9070
9071 tags
9072 }
9073
9074 pub fn move_to_enclosing_bracket(
9075 &mut self,
9076 _: &MoveToEnclosingBracket,
9077 cx: &mut ViewContext<Self>,
9078 ) {
9079 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9080 s.move_offsets_with(|snapshot, selection| {
9081 let Some(enclosing_bracket_ranges) =
9082 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9083 else {
9084 return;
9085 };
9086
9087 let mut best_length = usize::MAX;
9088 let mut best_inside = false;
9089 let mut best_in_bracket_range = false;
9090 let mut best_destination = None;
9091 for (open, close) in enclosing_bracket_ranges {
9092 let close = close.to_inclusive();
9093 let length = close.end() - open.start;
9094 let inside = selection.start >= open.end && selection.end <= *close.start();
9095 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9096 || close.contains(&selection.head());
9097
9098 // If best is next to a bracket and current isn't, skip
9099 if !in_bracket_range && best_in_bracket_range {
9100 continue;
9101 }
9102
9103 // Prefer smaller lengths unless best is inside and current isn't
9104 if length > best_length && (best_inside || !inside) {
9105 continue;
9106 }
9107
9108 best_length = length;
9109 best_inside = inside;
9110 best_in_bracket_range = in_bracket_range;
9111 best_destination = Some(
9112 if close.contains(&selection.start) && close.contains(&selection.end) {
9113 if inside {
9114 open.end
9115 } else {
9116 open.start
9117 }
9118 } else if inside {
9119 *close.start()
9120 } else {
9121 *close.end()
9122 },
9123 );
9124 }
9125
9126 if let Some(destination) = best_destination {
9127 selection.collapse_to(destination, SelectionGoal::None);
9128 }
9129 })
9130 });
9131 }
9132
9133 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9134 self.end_selection(cx);
9135 self.selection_history.mode = SelectionHistoryMode::Undoing;
9136 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9137 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9138 self.select_next_state = entry.select_next_state;
9139 self.select_prev_state = entry.select_prev_state;
9140 self.add_selections_state = entry.add_selections_state;
9141 self.request_autoscroll(Autoscroll::newest(), cx);
9142 }
9143 self.selection_history.mode = SelectionHistoryMode::Normal;
9144 }
9145
9146 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9147 self.end_selection(cx);
9148 self.selection_history.mode = SelectionHistoryMode::Redoing;
9149 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9150 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9151 self.select_next_state = entry.select_next_state;
9152 self.select_prev_state = entry.select_prev_state;
9153 self.add_selections_state = entry.add_selections_state;
9154 self.request_autoscroll(Autoscroll::newest(), cx);
9155 }
9156 self.selection_history.mode = SelectionHistoryMode::Normal;
9157 }
9158
9159 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9160 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9161 }
9162
9163 pub fn expand_excerpts_down(
9164 &mut self,
9165 action: &ExpandExcerptsDown,
9166 cx: &mut ViewContext<Self>,
9167 ) {
9168 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9169 }
9170
9171 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9172 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9173 }
9174
9175 pub fn expand_excerpts_for_direction(
9176 &mut self,
9177 lines: u32,
9178 direction: ExpandExcerptDirection,
9179 cx: &mut ViewContext<Self>,
9180 ) {
9181 let selections = self.selections.disjoint_anchors();
9182
9183 let lines = if lines == 0 {
9184 EditorSettings::get_global(cx).expand_excerpt_lines
9185 } else {
9186 lines
9187 };
9188
9189 self.buffer.update(cx, |buffer, cx| {
9190 buffer.expand_excerpts(
9191 selections
9192 .iter()
9193 .map(|selection| selection.head().excerpt_id)
9194 .dedup(),
9195 lines,
9196 direction,
9197 cx,
9198 )
9199 })
9200 }
9201
9202 pub fn expand_excerpt(
9203 &mut self,
9204 excerpt: ExcerptId,
9205 direction: ExpandExcerptDirection,
9206 cx: &mut ViewContext<Self>,
9207 ) {
9208 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9209 self.buffer.update(cx, |buffer, cx| {
9210 buffer.expand_excerpts([excerpt], lines, direction, cx)
9211 })
9212 }
9213
9214 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9215 self.go_to_diagnostic_impl(Direction::Next, cx)
9216 }
9217
9218 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9219 self.go_to_diagnostic_impl(Direction::Prev, cx)
9220 }
9221
9222 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9223 let buffer = self.buffer.read(cx).snapshot(cx);
9224 let selection = self.selections.newest::<usize>(cx);
9225
9226 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9227 if direction == Direction::Next {
9228 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9229 let (group_id, jump_to) = popover.activation_info();
9230 if self.activate_diagnostics(group_id, cx) {
9231 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9232 let mut new_selection = s.newest_anchor().clone();
9233 new_selection.collapse_to(jump_to, SelectionGoal::None);
9234 s.select_anchors(vec![new_selection.clone()]);
9235 });
9236 }
9237 return;
9238 }
9239 }
9240
9241 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9242 active_diagnostics
9243 .primary_range
9244 .to_offset(&buffer)
9245 .to_inclusive()
9246 });
9247 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9248 if active_primary_range.contains(&selection.head()) {
9249 *active_primary_range.start()
9250 } else {
9251 selection.head()
9252 }
9253 } else {
9254 selection.head()
9255 };
9256 let snapshot = self.snapshot(cx);
9257 loop {
9258 let diagnostics = if direction == Direction::Prev {
9259 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9260 } else {
9261 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9262 }
9263 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9264 let group = diagnostics
9265 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9266 // be sorted in a stable way
9267 // skip until we are at current active diagnostic, if it exists
9268 .skip_while(|entry| {
9269 (match direction {
9270 Direction::Prev => entry.range.start >= search_start,
9271 Direction::Next => entry.range.start <= search_start,
9272 }) && self
9273 .active_diagnostics
9274 .as_ref()
9275 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9276 })
9277 .find_map(|entry| {
9278 if entry.diagnostic.is_primary
9279 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9280 && !entry.range.is_empty()
9281 // if we match with the active diagnostic, skip it
9282 && Some(entry.diagnostic.group_id)
9283 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9284 {
9285 Some((entry.range, entry.diagnostic.group_id))
9286 } else {
9287 None
9288 }
9289 });
9290
9291 if let Some((primary_range, group_id)) = group {
9292 if self.activate_diagnostics(group_id, cx) {
9293 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9294 s.select(vec![Selection {
9295 id: selection.id,
9296 start: primary_range.start,
9297 end: primary_range.start,
9298 reversed: false,
9299 goal: SelectionGoal::None,
9300 }]);
9301 });
9302 }
9303 break;
9304 } else {
9305 // Cycle around to the start of the buffer, potentially moving back to the start of
9306 // the currently active diagnostic.
9307 active_primary_range.take();
9308 if direction == Direction::Prev {
9309 if search_start == buffer.len() {
9310 break;
9311 } else {
9312 search_start = buffer.len();
9313 }
9314 } else if search_start == 0 {
9315 break;
9316 } else {
9317 search_start = 0;
9318 }
9319 }
9320 }
9321 }
9322
9323 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9324 let snapshot = self
9325 .display_map
9326 .update(cx, |display_map, cx| display_map.snapshot(cx));
9327 let selection = self.selections.newest::<Point>(cx);
9328 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9329 }
9330
9331 fn go_to_hunk_after_position(
9332 &mut self,
9333 snapshot: &DisplaySnapshot,
9334 position: Point,
9335 cx: &mut ViewContext<'_, Editor>,
9336 ) -> Option<MultiBufferDiffHunk> {
9337 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9338 snapshot,
9339 position,
9340 false,
9341 snapshot
9342 .buffer_snapshot
9343 .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
9344 cx,
9345 ) {
9346 return Some(hunk);
9347 }
9348
9349 let wrapped_point = Point::zero();
9350 self.go_to_next_hunk_in_direction(
9351 snapshot,
9352 wrapped_point,
9353 true,
9354 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9355 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9356 ),
9357 cx,
9358 )
9359 }
9360
9361 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9362 let snapshot = self
9363 .display_map
9364 .update(cx, |display_map, cx| display_map.snapshot(cx));
9365 let selection = self.selections.newest::<Point>(cx);
9366
9367 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9368 }
9369
9370 fn go_to_hunk_before_position(
9371 &mut self,
9372 snapshot: &DisplaySnapshot,
9373 position: Point,
9374 cx: &mut ViewContext<'_, Editor>,
9375 ) -> Option<MultiBufferDiffHunk> {
9376 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9377 snapshot,
9378 position,
9379 false,
9380 snapshot
9381 .buffer_snapshot
9382 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
9383 cx,
9384 ) {
9385 return Some(hunk);
9386 }
9387
9388 let wrapped_point = snapshot.buffer_snapshot.max_point();
9389 self.go_to_next_hunk_in_direction(
9390 snapshot,
9391 wrapped_point,
9392 true,
9393 snapshot
9394 .buffer_snapshot
9395 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
9396 cx,
9397 )
9398 }
9399
9400 fn go_to_next_hunk_in_direction(
9401 &mut self,
9402 snapshot: &DisplaySnapshot,
9403 initial_point: Point,
9404 is_wrapped: bool,
9405 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9406 cx: &mut ViewContext<Editor>,
9407 ) -> Option<MultiBufferDiffHunk> {
9408 let display_point = initial_point.to_display_point(snapshot);
9409 let mut hunks = hunks
9410 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9411 .filter(|(display_hunk, _)| {
9412 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9413 })
9414 .dedup();
9415
9416 if let Some((display_hunk, hunk)) = hunks.next() {
9417 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9418 let row = display_hunk.start_display_row();
9419 let point = DisplayPoint::new(row, 0);
9420 s.select_display_ranges([point..point]);
9421 });
9422
9423 Some(hunk)
9424 } else {
9425 None
9426 }
9427 }
9428
9429 pub fn go_to_definition(
9430 &mut self,
9431 _: &GoToDefinition,
9432 cx: &mut ViewContext<Self>,
9433 ) -> Task<Result<Navigated>> {
9434 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9435 cx.spawn(|editor, mut cx| async move {
9436 if definition.await? == Navigated::Yes {
9437 return Ok(Navigated::Yes);
9438 }
9439 match editor.update(&mut cx, |editor, cx| {
9440 editor.find_all_references(&FindAllReferences, cx)
9441 })? {
9442 Some(references) => references.await,
9443 None => Ok(Navigated::No),
9444 }
9445 })
9446 }
9447
9448 pub fn go_to_declaration(
9449 &mut self,
9450 _: &GoToDeclaration,
9451 cx: &mut ViewContext<Self>,
9452 ) -> Task<Result<Navigated>> {
9453 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9454 }
9455
9456 pub fn go_to_declaration_split(
9457 &mut self,
9458 _: &GoToDeclaration,
9459 cx: &mut ViewContext<Self>,
9460 ) -> Task<Result<Navigated>> {
9461 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9462 }
9463
9464 pub fn go_to_implementation(
9465 &mut self,
9466 _: &GoToImplementation,
9467 cx: &mut ViewContext<Self>,
9468 ) -> Task<Result<Navigated>> {
9469 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9470 }
9471
9472 pub fn go_to_implementation_split(
9473 &mut self,
9474 _: &GoToImplementationSplit,
9475 cx: &mut ViewContext<Self>,
9476 ) -> Task<Result<Navigated>> {
9477 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9478 }
9479
9480 pub fn go_to_type_definition(
9481 &mut self,
9482 _: &GoToTypeDefinition,
9483 cx: &mut ViewContext<Self>,
9484 ) -> Task<Result<Navigated>> {
9485 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9486 }
9487
9488 pub fn go_to_definition_split(
9489 &mut self,
9490 _: &GoToDefinitionSplit,
9491 cx: &mut ViewContext<Self>,
9492 ) -> Task<Result<Navigated>> {
9493 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9494 }
9495
9496 pub fn go_to_type_definition_split(
9497 &mut self,
9498 _: &GoToTypeDefinitionSplit,
9499 cx: &mut ViewContext<Self>,
9500 ) -> Task<Result<Navigated>> {
9501 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9502 }
9503
9504 fn go_to_definition_of_kind(
9505 &mut self,
9506 kind: GotoDefinitionKind,
9507 split: bool,
9508 cx: &mut ViewContext<Self>,
9509 ) -> Task<Result<Navigated>> {
9510 let Some(workspace) = self.workspace() else {
9511 return Task::ready(Ok(Navigated::No));
9512 };
9513 let buffer = self.buffer.read(cx);
9514 let head = self.selections.newest::<usize>(cx).head();
9515 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9516 text_anchor
9517 } else {
9518 return Task::ready(Ok(Navigated::No));
9519 };
9520
9521 let project = workspace.read(cx).project().clone();
9522 let definitions = project.update(cx, |project, cx| match kind {
9523 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
9524 GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
9525 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
9526 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
9527 });
9528
9529 cx.spawn(|editor, mut cx| async move {
9530 let definitions = definitions.await?;
9531 let navigated = editor
9532 .update(&mut cx, |editor, cx| {
9533 editor.navigate_to_hover_links(
9534 Some(kind),
9535 definitions
9536 .into_iter()
9537 .filter(|location| {
9538 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9539 })
9540 .map(HoverLink::Text)
9541 .collect::<Vec<_>>(),
9542 split,
9543 cx,
9544 )
9545 })?
9546 .await?;
9547 anyhow::Ok(navigated)
9548 })
9549 }
9550
9551 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9552 let position = self.selections.newest_anchor().head();
9553 let Some((buffer, buffer_position)) =
9554 self.buffer.read(cx).text_anchor_for_position(position, cx)
9555 else {
9556 return;
9557 };
9558
9559 cx.spawn(|editor, mut cx| async move {
9560 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9561 editor.update(&mut cx, |_, cx| {
9562 cx.open_url(&url);
9563 })
9564 } else {
9565 Ok(())
9566 }
9567 })
9568 .detach();
9569 }
9570
9571 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9572 let Some(workspace) = self.workspace() else {
9573 return;
9574 };
9575
9576 let position = self.selections.newest_anchor().head();
9577
9578 let Some((buffer, buffer_position)) =
9579 self.buffer.read(cx).text_anchor_for_position(position, cx)
9580 else {
9581 return;
9582 };
9583
9584 let Some(project) = self.project.clone() else {
9585 return;
9586 };
9587
9588 cx.spawn(|_, mut cx| async move {
9589 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9590
9591 if let Some((_, path)) = result {
9592 workspace
9593 .update(&mut cx, |workspace, cx| {
9594 workspace.open_resolved_path(path, cx)
9595 })?
9596 .await?;
9597 }
9598 anyhow::Ok(())
9599 })
9600 .detach();
9601 }
9602
9603 pub(crate) fn navigate_to_hover_links(
9604 &mut self,
9605 kind: Option<GotoDefinitionKind>,
9606 mut definitions: Vec<HoverLink>,
9607 split: bool,
9608 cx: &mut ViewContext<Editor>,
9609 ) -> Task<Result<Navigated>> {
9610 // If there is one definition, just open it directly
9611 if definitions.len() == 1 {
9612 let definition = definitions.pop().unwrap();
9613
9614 enum TargetTaskResult {
9615 Location(Option<Location>),
9616 AlreadyNavigated,
9617 }
9618
9619 let target_task = match definition {
9620 HoverLink::Text(link) => {
9621 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9622 }
9623 HoverLink::InlayHint(lsp_location, server_id) => {
9624 let computation = self.compute_target_location(lsp_location, server_id, cx);
9625 cx.background_executor().spawn(async move {
9626 let location = computation.await?;
9627 Ok(TargetTaskResult::Location(location))
9628 })
9629 }
9630 HoverLink::Url(url) => {
9631 cx.open_url(&url);
9632 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9633 }
9634 HoverLink::File(path) => {
9635 if let Some(workspace) = self.workspace() {
9636 cx.spawn(|_, mut cx| async move {
9637 workspace
9638 .update(&mut cx, |workspace, cx| {
9639 workspace.open_resolved_path(path, cx)
9640 })?
9641 .await
9642 .map(|_| TargetTaskResult::AlreadyNavigated)
9643 })
9644 } else {
9645 Task::ready(Ok(TargetTaskResult::Location(None)))
9646 }
9647 }
9648 };
9649 cx.spawn(|editor, mut cx| async move {
9650 let target = match target_task.await.context("target resolution task")? {
9651 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9652 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9653 TargetTaskResult::Location(Some(target)) => target,
9654 };
9655
9656 editor.update(&mut cx, |editor, cx| {
9657 let Some(workspace) = editor.workspace() else {
9658 return Navigated::No;
9659 };
9660 let pane = workspace.read(cx).active_pane().clone();
9661
9662 let range = target.range.to_offset(target.buffer.read(cx));
9663 let range = editor.range_for_match(&range);
9664
9665 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9666 let buffer = target.buffer.read(cx);
9667 let range = check_multiline_range(buffer, range);
9668 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
9669 s.select_ranges([range]);
9670 });
9671 } else {
9672 cx.window_context().defer(move |cx| {
9673 let target_editor: View<Self> =
9674 workspace.update(cx, |workspace, cx| {
9675 let pane = if split {
9676 workspace.adjacent_pane(cx)
9677 } else {
9678 workspace.active_pane().clone()
9679 };
9680
9681 workspace.open_project_item(
9682 pane,
9683 target.buffer.clone(),
9684 true,
9685 true,
9686 cx,
9687 )
9688 });
9689 target_editor.update(cx, |target_editor, cx| {
9690 // When selecting a definition in a different buffer, disable the nav history
9691 // to avoid creating a history entry at the previous cursor location.
9692 pane.update(cx, |pane, _| pane.disable_history());
9693 let buffer = target.buffer.read(cx);
9694 let range = check_multiline_range(buffer, range);
9695 target_editor.change_selections(
9696 Some(Autoscroll::focused()),
9697 cx,
9698 |s| {
9699 s.select_ranges([range]);
9700 },
9701 );
9702 pane.update(cx, |pane, _| pane.enable_history());
9703 });
9704 });
9705 }
9706 Navigated::Yes
9707 })
9708 })
9709 } else if !definitions.is_empty() {
9710 cx.spawn(|editor, mut cx| async move {
9711 let (title, location_tasks, workspace) = editor
9712 .update(&mut cx, |editor, cx| {
9713 let tab_kind = match kind {
9714 Some(GotoDefinitionKind::Implementation) => "Implementations",
9715 _ => "Definitions",
9716 };
9717 let title = definitions
9718 .iter()
9719 .find_map(|definition| match definition {
9720 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9721 let buffer = origin.buffer.read(cx);
9722 format!(
9723 "{} for {}",
9724 tab_kind,
9725 buffer
9726 .text_for_range(origin.range.clone())
9727 .collect::<String>()
9728 )
9729 }),
9730 HoverLink::InlayHint(_, _) => None,
9731 HoverLink::Url(_) => None,
9732 HoverLink::File(_) => None,
9733 })
9734 .unwrap_or(tab_kind.to_string());
9735 let location_tasks = definitions
9736 .into_iter()
9737 .map(|definition| match definition {
9738 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9739 HoverLink::InlayHint(lsp_location, server_id) => {
9740 editor.compute_target_location(lsp_location, server_id, cx)
9741 }
9742 HoverLink::Url(_) => Task::ready(Ok(None)),
9743 HoverLink::File(_) => Task::ready(Ok(None)),
9744 })
9745 .collect::<Vec<_>>();
9746 (title, location_tasks, editor.workspace().clone())
9747 })
9748 .context("location tasks preparation")?;
9749
9750 let locations = future::join_all(location_tasks)
9751 .await
9752 .into_iter()
9753 .filter_map(|location| location.transpose())
9754 .collect::<Result<_>>()
9755 .context("location tasks")?;
9756
9757 let Some(workspace) = workspace else {
9758 return Ok(Navigated::No);
9759 };
9760 let opened = workspace
9761 .update(&mut cx, |workspace, cx| {
9762 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9763 })
9764 .ok();
9765
9766 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9767 })
9768 } else {
9769 Task::ready(Ok(Navigated::No))
9770 }
9771 }
9772
9773 fn compute_target_location(
9774 &self,
9775 lsp_location: lsp::Location,
9776 server_id: LanguageServerId,
9777 cx: &mut ViewContext<Editor>,
9778 ) -> Task<anyhow::Result<Option<Location>>> {
9779 let Some(project) = self.project.clone() else {
9780 return Task::Ready(Some(Ok(None)));
9781 };
9782
9783 cx.spawn(move |editor, mut cx| async move {
9784 let location_task = editor.update(&mut cx, |editor, cx| {
9785 project.update(cx, |project, cx| {
9786 let language_server_name =
9787 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9788 project
9789 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9790 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9791 });
9792 language_server_name.map(|language_server_name| {
9793 project.open_local_buffer_via_lsp(
9794 lsp_location.uri.clone(),
9795 server_id,
9796 language_server_name,
9797 cx,
9798 )
9799 })
9800 })
9801 })?;
9802 let location = match location_task {
9803 Some(task) => Some({
9804 let target_buffer_handle = task.await.context("open local buffer")?;
9805 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9806 let target_start = target_buffer
9807 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9808 let target_end = target_buffer
9809 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9810 target_buffer.anchor_after(target_start)
9811 ..target_buffer.anchor_before(target_end)
9812 })?;
9813 Location {
9814 buffer: target_buffer_handle,
9815 range,
9816 }
9817 }),
9818 None => None,
9819 };
9820 Ok(location)
9821 })
9822 }
9823
9824 pub fn find_all_references(
9825 &mut self,
9826 _: &FindAllReferences,
9827 cx: &mut ViewContext<Self>,
9828 ) -> Option<Task<Result<Navigated>>> {
9829 let multi_buffer = self.buffer.read(cx);
9830 let selection = self.selections.newest::<usize>(cx);
9831 let head = selection.head();
9832
9833 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9834 let head_anchor = multi_buffer_snapshot.anchor_at(
9835 head,
9836 if head < selection.tail() {
9837 Bias::Right
9838 } else {
9839 Bias::Left
9840 },
9841 );
9842
9843 match self
9844 .find_all_references_task_sources
9845 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9846 {
9847 Ok(_) => {
9848 log::info!(
9849 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9850 );
9851 return None;
9852 }
9853 Err(i) => {
9854 self.find_all_references_task_sources.insert(i, head_anchor);
9855 }
9856 }
9857
9858 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9859 let workspace = self.workspace()?;
9860 let project = workspace.read(cx).project().clone();
9861 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9862 Some(cx.spawn(|editor, mut cx| async move {
9863 let _cleanup = defer({
9864 let mut cx = cx.clone();
9865 move || {
9866 let _ = editor.update(&mut cx, |editor, _| {
9867 if let Ok(i) =
9868 editor
9869 .find_all_references_task_sources
9870 .binary_search_by(|anchor| {
9871 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9872 })
9873 {
9874 editor.find_all_references_task_sources.remove(i);
9875 }
9876 });
9877 }
9878 });
9879
9880 let locations = references.await?;
9881 if locations.is_empty() {
9882 return anyhow::Ok(Navigated::No);
9883 }
9884
9885 workspace.update(&mut cx, |workspace, cx| {
9886 let title = locations
9887 .first()
9888 .as_ref()
9889 .map(|location| {
9890 let buffer = location.buffer.read(cx);
9891 format!(
9892 "References to `{}`",
9893 buffer
9894 .text_for_range(location.range.clone())
9895 .collect::<String>()
9896 )
9897 })
9898 .unwrap();
9899 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9900 Navigated::Yes
9901 })
9902 }))
9903 }
9904
9905 /// Opens a multibuffer with the given project locations in it
9906 pub fn open_locations_in_multibuffer(
9907 workspace: &mut Workspace,
9908 mut locations: Vec<Location>,
9909 title: String,
9910 split: bool,
9911 cx: &mut ViewContext<Workspace>,
9912 ) {
9913 // If there are multiple definitions, open them in a multibuffer
9914 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9915 let mut locations = locations.into_iter().peekable();
9916 let mut ranges_to_highlight = Vec::new();
9917 let capability = workspace.project().read(cx).capability();
9918
9919 let excerpt_buffer = cx.new_model(|cx| {
9920 let mut multibuffer = MultiBuffer::new(capability);
9921 while let Some(location) = locations.next() {
9922 let buffer = location.buffer.read(cx);
9923 let mut ranges_for_buffer = Vec::new();
9924 let range = location.range.to_offset(buffer);
9925 ranges_for_buffer.push(range.clone());
9926
9927 while let Some(next_location) = locations.peek() {
9928 if next_location.buffer == location.buffer {
9929 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9930 locations.next();
9931 } else {
9932 break;
9933 }
9934 }
9935
9936 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9937 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9938 location.buffer.clone(),
9939 ranges_for_buffer,
9940 DEFAULT_MULTIBUFFER_CONTEXT,
9941 cx,
9942 ))
9943 }
9944
9945 multibuffer.with_title(title)
9946 });
9947
9948 let editor = cx.new_view(|cx| {
9949 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9950 });
9951 editor.update(cx, |editor, cx| {
9952 if let Some(first_range) = ranges_to_highlight.first() {
9953 editor.change_selections(None, cx, |selections| {
9954 selections.clear_disjoint();
9955 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9956 });
9957 }
9958 editor.highlight_background::<Self>(
9959 &ranges_to_highlight,
9960 |theme| theme.editor_highlighted_line_background,
9961 cx,
9962 );
9963 });
9964
9965 let item = Box::new(editor);
9966 let item_id = item.item_id();
9967
9968 if split {
9969 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9970 } else {
9971 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9972 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9973 pane.close_current_preview_item(cx)
9974 } else {
9975 None
9976 }
9977 });
9978 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9979 }
9980 workspace.active_pane().update(cx, |pane, cx| {
9981 pane.set_preview_item_id(Some(item_id), cx);
9982 });
9983 }
9984
9985 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9986 use language::ToOffset as _;
9987
9988 let project = self.project.clone()?;
9989 let selection = self.selections.newest_anchor().clone();
9990 let (cursor_buffer, cursor_buffer_position) = self
9991 .buffer
9992 .read(cx)
9993 .text_anchor_for_position(selection.head(), cx)?;
9994 let (tail_buffer, cursor_buffer_position_end) = self
9995 .buffer
9996 .read(cx)
9997 .text_anchor_for_position(selection.tail(), cx)?;
9998 if tail_buffer != cursor_buffer {
9999 return None;
10000 }
10001
10002 let snapshot = cursor_buffer.read(cx).snapshot();
10003 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10004 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10005 let prepare_rename = project.update(cx, |project, cx| {
10006 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
10007 });
10008 drop(snapshot);
10009
10010 Some(cx.spawn(|this, mut cx| async move {
10011 let rename_range = if let Some(range) = prepare_rename.await? {
10012 Some(range)
10013 } else {
10014 this.update(&mut cx, |this, cx| {
10015 let buffer = this.buffer.read(cx).snapshot(cx);
10016 let mut buffer_highlights = this
10017 .document_highlights_for_position(selection.head(), &buffer)
10018 .filter(|highlight| {
10019 highlight.start.excerpt_id == selection.head().excerpt_id
10020 && highlight.end.excerpt_id == selection.head().excerpt_id
10021 });
10022 buffer_highlights
10023 .next()
10024 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10025 })?
10026 };
10027 if let Some(rename_range) = rename_range {
10028 this.update(&mut cx, |this, cx| {
10029 let snapshot = cursor_buffer.read(cx).snapshot();
10030 let rename_buffer_range = rename_range.to_offset(&snapshot);
10031 let cursor_offset_in_rename_range =
10032 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10033 let cursor_offset_in_rename_range_end =
10034 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10035
10036 this.take_rename(false, cx);
10037 let buffer = this.buffer.read(cx).read(cx);
10038 let cursor_offset = selection.head().to_offset(&buffer);
10039 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10040 let rename_end = rename_start + rename_buffer_range.len();
10041 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10042 let mut old_highlight_id = None;
10043 let old_name: Arc<str> = buffer
10044 .chunks(rename_start..rename_end, true)
10045 .map(|chunk| {
10046 if old_highlight_id.is_none() {
10047 old_highlight_id = chunk.syntax_highlight_id;
10048 }
10049 chunk.text
10050 })
10051 .collect::<String>()
10052 .into();
10053
10054 drop(buffer);
10055
10056 // Position the selection in the rename editor so that it matches the current selection.
10057 this.show_local_selections = false;
10058 let rename_editor = cx.new_view(|cx| {
10059 let mut editor = Editor::single_line(cx);
10060 editor.buffer.update(cx, |buffer, cx| {
10061 buffer.edit([(0..0, old_name.clone())], None, cx)
10062 });
10063 let rename_selection_range = match cursor_offset_in_rename_range
10064 .cmp(&cursor_offset_in_rename_range_end)
10065 {
10066 Ordering::Equal => {
10067 editor.select_all(&SelectAll, cx);
10068 return editor;
10069 }
10070 Ordering::Less => {
10071 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10072 }
10073 Ordering::Greater => {
10074 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10075 }
10076 };
10077 if rename_selection_range.end > old_name.len() {
10078 editor.select_all(&SelectAll, cx);
10079 } else {
10080 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10081 s.select_ranges([rename_selection_range]);
10082 });
10083 }
10084 editor
10085 });
10086 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10087 if e == &EditorEvent::Focused {
10088 cx.emit(EditorEvent::FocusedIn)
10089 }
10090 })
10091 .detach();
10092
10093 let write_highlights =
10094 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10095 let read_highlights =
10096 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10097 let ranges = write_highlights
10098 .iter()
10099 .flat_map(|(_, ranges)| ranges.iter())
10100 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10101 .cloned()
10102 .collect();
10103
10104 this.highlight_text::<Rename>(
10105 ranges,
10106 HighlightStyle {
10107 fade_out: Some(0.6),
10108 ..Default::default()
10109 },
10110 cx,
10111 );
10112 let rename_focus_handle = rename_editor.focus_handle(cx);
10113 cx.focus(&rename_focus_handle);
10114 let block_id = this.insert_blocks(
10115 [BlockProperties {
10116 style: BlockStyle::Flex,
10117 position: range.start,
10118 height: 1,
10119 render: Box::new({
10120 let rename_editor = rename_editor.clone();
10121 move |cx: &mut BlockContext| {
10122 let mut text_style = cx.editor_style.text.clone();
10123 if let Some(highlight_style) = old_highlight_id
10124 .and_then(|h| h.style(&cx.editor_style.syntax))
10125 {
10126 text_style = text_style.highlight(highlight_style);
10127 }
10128 div()
10129 .pl(cx.anchor_x)
10130 .child(EditorElement::new(
10131 &rename_editor,
10132 EditorStyle {
10133 background: cx.theme().system().transparent,
10134 local_player: cx.editor_style.local_player,
10135 text: text_style,
10136 scrollbar_width: cx.editor_style.scrollbar_width,
10137 syntax: cx.editor_style.syntax.clone(),
10138 status: cx.editor_style.status.clone(),
10139 inlay_hints_style: HighlightStyle {
10140 font_weight: Some(FontWeight::BOLD),
10141 ..make_inlay_hints_style(cx)
10142 },
10143 suggestions_style: HighlightStyle {
10144 color: Some(cx.theme().status().predictive),
10145 ..HighlightStyle::default()
10146 },
10147 ..EditorStyle::default()
10148 },
10149 ))
10150 .into_any_element()
10151 }
10152 }),
10153 disposition: BlockDisposition::Below,
10154 priority: 0,
10155 }],
10156 Some(Autoscroll::fit()),
10157 cx,
10158 )[0];
10159 this.pending_rename = Some(RenameState {
10160 range,
10161 old_name,
10162 editor: rename_editor,
10163 block_id,
10164 });
10165 })?;
10166 }
10167
10168 Ok(())
10169 }))
10170 }
10171
10172 pub fn confirm_rename(
10173 &mut self,
10174 _: &ConfirmRename,
10175 cx: &mut ViewContext<Self>,
10176 ) -> Option<Task<Result<()>>> {
10177 let rename = self.take_rename(false, cx)?;
10178 let workspace = self.workspace()?;
10179 let (start_buffer, start) = self
10180 .buffer
10181 .read(cx)
10182 .text_anchor_for_position(rename.range.start, cx)?;
10183 let (end_buffer, end) = self
10184 .buffer
10185 .read(cx)
10186 .text_anchor_for_position(rename.range.end, cx)?;
10187 if start_buffer != end_buffer {
10188 return None;
10189 }
10190
10191 let buffer = start_buffer;
10192 let range = start..end;
10193 let old_name = rename.old_name;
10194 let new_name = rename.editor.read(cx).text(cx);
10195
10196 let rename = workspace
10197 .read(cx)
10198 .project()
10199 .clone()
10200 .update(cx, |project, cx| {
10201 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
10202 });
10203 let workspace = workspace.downgrade();
10204
10205 Some(cx.spawn(|editor, mut cx| async move {
10206 let project_transaction = rename.await?;
10207 Self::open_project_transaction(
10208 &editor,
10209 workspace,
10210 project_transaction,
10211 format!("Rename: {} → {}", old_name, new_name),
10212 cx.clone(),
10213 )
10214 .await?;
10215
10216 editor.update(&mut cx, |editor, cx| {
10217 editor.refresh_document_highlights(cx);
10218 })?;
10219 Ok(())
10220 }))
10221 }
10222
10223 fn take_rename(
10224 &mut self,
10225 moving_cursor: bool,
10226 cx: &mut ViewContext<Self>,
10227 ) -> Option<RenameState> {
10228 let rename = self.pending_rename.take()?;
10229 if rename.editor.focus_handle(cx).is_focused(cx) {
10230 cx.focus(&self.focus_handle);
10231 }
10232
10233 self.remove_blocks(
10234 [rename.block_id].into_iter().collect(),
10235 Some(Autoscroll::fit()),
10236 cx,
10237 );
10238 self.clear_highlights::<Rename>(cx);
10239 self.show_local_selections = true;
10240
10241 if moving_cursor {
10242 let rename_editor = rename.editor.read(cx);
10243 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10244
10245 // Update the selection to match the position of the selection inside
10246 // the rename editor.
10247 let snapshot = self.buffer.read(cx).read(cx);
10248 let rename_range = rename.range.to_offset(&snapshot);
10249 let cursor_in_editor = snapshot
10250 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10251 .min(rename_range.end);
10252 drop(snapshot);
10253
10254 self.change_selections(None, cx, |s| {
10255 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10256 });
10257 } else {
10258 self.refresh_document_highlights(cx);
10259 }
10260
10261 Some(rename)
10262 }
10263
10264 pub fn pending_rename(&self) -> Option<&RenameState> {
10265 self.pending_rename.as_ref()
10266 }
10267
10268 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10269 let project = match &self.project {
10270 Some(project) => project.clone(),
10271 None => return None,
10272 };
10273
10274 Some(self.perform_format(project, FormatTrigger::Manual, cx))
10275 }
10276
10277 fn perform_format(
10278 &mut self,
10279 project: Model<Project>,
10280 trigger: FormatTrigger,
10281 cx: &mut ViewContext<Self>,
10282 ) -> Task<Result<()>> {
10283 let buffer = self.buffer().clone();
10284 let mut buffers = buffer.read(cx).all_buffers();
10285 if trigger == FormatTrigger::Save {
10286 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10287 }
10288
10289 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10290 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
10291
10292 cx.spawn(|_, mut cx| async move {
10293 let transaction = futures::select_biased! {
10294 () = timeout => {
10295 log::warn!("timed out waiting for formatting");
10296 None
10297 }
10298 transaction = format.log_err().fuse() => transaction,
10299 };
10300
10301 buffer
10302 .update(&mut cx, |buffer, cx| {
10303 if let Some(transaction) = transaction {
10304 if !buffer.is_singleton() {
10305 buffer.push_transaction(&transaction.0, cx);
10306 }
10307 }
10308
10309 cx.notify();
10310 })
10311 .ok();
10312
10313 Ok(())
10314 })
10315 }
10316
10317 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10318 if let Some(project) = self.project.clone() {
10319 self.buffer.update(cx, |multi_buffer, cx| {
10320 project.update(cx, |project, cx| {
10321 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10322 });
10323 })
10324 }
10325 }
10326
10327 fn cancel_language_server_work(
10328 &mut self,
10329 _: &CancelLanguageServerWork,
10330 cx: &mut ViewContext<Self>,
10331 ) {
10332 if let Some(project) = self.project.clone() {
10333 self.buffer.update(cx, |multi_buffer, cx| {
10334 project.update(cx, |project, cx| {
10335 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10336 });
10337 })
10338 }
10339 }
10340
10341 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10342 cx.show_character_palette();
10343 }
10344
10345 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10346 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10347 let buffer = self.buffer.read(cx).snapshot(cx);
10348 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10349 let is_valid = buffer
10350 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10351 .any(|entry| {
10352 entry.diagnostic.is_primary
10353 && !entry.range.is_empty()
10354 && entry.range.start == primary_range_start
10355 && entry.diagnostic.message == active_diagnostics.primary_message
10356 });
10357
10358 if is_valid != active_diagnostics.is_valid {
10359 active_diagnostics.is_valid = is_valid;
10360 let mut new_styles = HashMap::default();
10361 for (block_id, diagnostic) in &active_diagnostics.blocks {
10362 new_styles.insert(
10363 *block_id,
10364 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10365 );
10366 }
10367 self.display_map.update(cx, |display_map, _cx| {
10368 display_map.replace_blocks(new_styles)
10369 });
10370 }
10371 }
10372 }
10373
10374 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10375 self.dismiss_diagnostics(cx);
10376 let snapshot = self.snapshot(cx);
10377 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10378 let buffer = self.buffer.read(cx).snapshot(cx);
10379
10380 let mut primary_range = None;
10381 let mut primary_message = None;
10382 let mut group_end = Point::zero();
10383 let diagnostic_group = buffer
10384 .diagnostic_group::<MultiBufferPoint>(group_id)
10385 .filter_map(|entry| {
10386 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10387 && (entry.range.start.row == entry.range.end.row
10388 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10389 {
10390 return None;
10391 }
10392 if entry.range.end > group_end {
10393 group_end = entry.range.end;
10394 }
10395 if entry.diagnostic.is_primary {
10396 primary_range = Some(entry.range.clone());
10397 primary_message = Some(entry.diagnostic.message.clone());
10398 }
10399 Some(entry)
10400 })
10401 .collect::<Vec<_>>();
10402 let primary_range = primary_range?;
10403 let primary_message = primary_message?;
10404 let primary_range =
10405 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10406
10407 let blocks = display_map
10408 .insert_blocks(
10409 diagnostic_group.iter().map(|entry| {
10410 let diagnostic = entry.diagnostic.clone();
10411 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10412 BlockProperties {
10413 style: BlockStyle::Fixed,
10414 position: buffer.anchor_after(entry.range.start),
10415 height: message_height,
10416 render: diagnostic_block_renderer(diagnostic, None, true, true),
10417 disposition: BlockDisposition::Below,
10418 priority: 0,
10419 }
10420 }),
10421 cx,
10422 )
10423 .into_iter()
10424 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10425 .collect();
10426
10427 Some(ActiveDiagnosticGroup {
10428 primary_range,
10429 primary_message,
10430 group_id,
10431 blocks,
10432 is_valid: true,
10433 })
10434 });
10435 self.active_diagnostics.is_some()
10436 }
10437
10438 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10439 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10440 self.display_map.update(cx, |display_map, cx| {
10441 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10442 });
10443 cx.notify();
10444 }
10445 }
10446
10447 pub fn set_selections_from_remote(
10448 &mut self,
10449 selections: Vec<Selection<Anchor>>,
10450 pending_selection: Option<Selection<Anchor>>,
10451 cx: &mut ViewContext<Self>,
10452 ) {
10453 let old_cursor_position = self.selections.newest_anchor().head();
10454 self.selections.change_with(cx, |s| {
10455 s.select_anchors(selections);
10456 if let Some(pending_selection) = pending_selection {
10457 s.set_pending(pending_selection, SelectMode::Character);
10458 } else {
10459 s.clear_pending();
10460 }
10461 });
10462 self.selections_did_change(false, &old_cursor_position, true, cx);
10463 }
10464
10465 fn push_to_selection_history(&mut self) {
10466 self.selection_history.push(SelectionHistoryEntry {
10467 selections: self.selections.disjoint_anchors(),
10468 select_next_state: self.select_next_state.clone(),
10469 select_prev_state: self.select_prev_state.clone(),
10470 add_selections_state: self.add_selections_state.clone(),
10471 });
10472 }
10473
10474 pub fn transact(
10475 &mut self,
10476 cx: &mut ViewContext<Self>,
10477 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10478 ) -> Option<TransactionId> {
10479 self.start_transaction_at(Instant::now(), cx);
10480 update(self, cx);
10481 self.end_transaction_at(Instant::now(), cx)
10482 }
10483
10484 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10485 self.end_selection(cx);
10486 if let Some(tx_id) = self
10487 .buffer
10488 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10489 {
10490 self.selection_history
10491 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10492 cx.emit(EditorEvent::TransactionBegun {
10493 transaction_id: tx_id,
10494 })
10495 }
10496 }
10497
10498 fn end_transaction_at(
10499 &mut self,
10500 now: Instant,
10501 cx: &mut ViewContext<Self>,
10502 ) -> Option<TransactionId> {
10503 if let Some(transaction_id) = self
10504 .buffer
10505 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10506 {
10507 if let Some((_, end_selections)) =
10508 self.selection_history.transaction_mut(transaction_id)
10509 {
10510 *end_selections = Some(self.selections.disjoint_anchors());
10511 } else {
10512 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10513 }
10514
10515 cx.emit(EditorEvent::Edited { transaction_id });
10516 Some(transaction_id)
10517 } else {
10518 None
10519 }
10520 }
10521
10522 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10523 let mut fold_ranges = Vec::new();
10524
10525 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10526
10527 let selections = self.selections.all_adjusted(cx);
10528 for selection in selections {
10529 let range = selection.range().sorted();
10530 let buffer_start_row = range.start.row;
10531
10532 for row in (0..=range.end.row).rev() {
10533 if let Some((foldable_range, fold_text)) =
10534 display_map.foldable_range(MultiBufferRow(row))
10535 {
10536 if foldable_range.end.row >= buffer_start_row {
10537 fold_ranges.push((foldable_range, fold_text));
10538 if row <= range.start.row {
10539 break;
10540 }
10541 }
10542 }
10543 }
10544 }
10545
10546 self.fold_ranges(fold_ranges, true, cx);
10547 }
10548
10549 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10550 let buffer_row = fold_at.buffer_row;
10551 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10552
10553 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10554 let autoscroll = self
10555 .selections
10556 .all::<Point>(cx)
10557 .iter()
10558 .any(|selection| fold_range.overlaps(&selection.range()));
10559
10560 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10561 }
10562 }
10563
10564 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10565 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10566 let buffer = &display_map.buffer_snapshot;
10567 let selections = self.selections.all::<Point>(cx);
10568 let ranges = selections
10569 .iter()
10570 .map(|s| {
10571 let range = s.display_range(&display_map).sorted();
10572 let mut start = range.start.to_point(&display_map);
10573 let mut end = range.end.to_point(&display_map);
10574 start.column = 0;
10575 end.column = buffer.line_len(MultiBufferRow(end.row));
10576 start..end
10577 })
10578 .collect::<Vec<_>>();
10579
10580 self.unfold_ranges(ranges, true, true, cx);
10581 }
10582
10583 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10584 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10585
10586 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10587 ..Point::new(
10588 unfold_at.buffer_row.0,
10589 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10590 );
10591
10592 let autoscroll = self
10593 .selections
10594 .all::<Point>(cx)
10595 .iter()
10596 .any(|selection| selection.range().overlaps(&intersection_range));
10597
10598 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10599 }
10600
10601 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10602 let selections = self.selections.all::<Point>(cx);
10603 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10604 let line_mode = self.selections.line_mode;
10605 let ranges = selections.into_iter().map(|s| {
10606 if line_mode {
10607 let start = Point::new(s.start.row, 0);
10608 let end = Point::new(
10609 s.end.row,
10610 display_map
10611 .buffer_snapshot
10612 .line_len(MultiBufferRow(s.end.row)),
10613 );
10614 (start..end, display_map.fold_placeholder.clone())
10615 } else {
10616 (s.start..s.end, display_map.fold_placeholder.clone())
10617 }
10618 });
10619 self.fold_ranges(ranges, true, cx);
10620 }
10621
10622 pub fn fold_ranges<T: ToOffset + Clone>(
10623 &mut self,
10624 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10625 auto_scroll: bool,
10626 cx: &mut ViewContext<Self>,
10627 ) {
10628 let mut fold_ranges = Vec::new();
10629 let mut buffers_affected = HashMap::default();
10630 let multi_buffer = self.buffer().read(cx);
10631 for (fold_range, fold_text) in ranges {
10632 if let Some((_, buffer, _)) =
10633 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10634 {
10635 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10636 };
10637 fold_ranges.push((fold_range, fold_text));
10638 }
10639
10640 let mut ranges = fold_ranges.into_iter().peekable();
10641 if ranges.peek().is_some() {
10642 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10643
10644 if auto_scroll {
10645 self.request_autoscroll(Autoscroll::fit(), cx);
10646 }
10647
10648 for buffer in buffers_affected.into_values() {
10649 self.sync_expanded_diff_hunks(buffer, cx);
10650 }
10651
10652 cx.notify();
10653
10654 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10655 // Clear diagnostics block when folding a range that contains it.
10656 let snapshot = self.snapshot(cx);
10657 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10658 drop(snapshot);
10659 self.active_diagnostics = Some(active_diagnostics);
10660 self.dismiss_diagnostics(cx);
10661 } else {
10662 self.active_diagnostics = Some(active_diagnostics);
10663 }
10664 }
10665
10666 self.scrollbar_marker_state.dirty = true;
10667 }
10668 }
10669
10670 pub fn unfold_ranges<T: ToOffset + Clone>(
10671 &mut self,
10672 ranges: impl IntoIterator<Item = Range<T>>,
10673 inclusive: bool,
10674 auto_scroll: bool,
10675 cx: &mut ViewContext<Self>,
10676 ) {
10677 let mut unfold_ranges = Vec::new();
10678 let mut buffers_affected = HashMap::default();
10679 let multi_buffer = self.buffer().read(cx);
10680 for range in ranges {
10681 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10682 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10683 };
10684 unfold_ranges.push(range);
10685 }
10686
10687 let mut ranges = unfold_ranges.into_iter().peekable();
10688 if ranges.peek().is_some() {
10689 self.display_map
10690 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10691 if auto_scroll {
10692 self.request_autoscroll(Autoscroll::fit(), cx);
10693 }
10694
10695 for buffer in buffers_affected.into_values() {
10696 self.sync_expanded_diff_hunks(buffer, cx);
10697 }
10698
10699 cx.notify();
10700 self.scrollbar_marker_state.dirty = true;
10701 self.active_indent_guides_state.dirty = true;
10702 }
10703 }
10704
10705 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10706 self.display_map.read(cx).fold_placeholder.clone()
10707 }
10708
10709 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10710 if hovered != self.gutter_hovered {
10711 self.gutter_hovered = hovered;
10712 cx.notify();
10713 }
10714 }
10715
10716 pub fn insert_blocks(
10717 &mut self,
10718 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10719 autoscroll: Option<Autoscroll>,
10720 cx: &mut ViewContext<Self>,
10721 ) -> Vec<CustomBlockId> {
10722 let blocks = self
10723 .display_map
10724 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10725 if let Some(autoscroll) = autoscroll {
10726 self.request_autoscroll(autoscroll, cx);
10727 }
10728 cx.notify();
10729 blocks
10730 }
10731
10732 pub fn resize_blocks(
10733 &mut self,
10734 heights: HashMap<CustomBlockId, u32>,
10735 autoscroll: Option<Autoscroll>,
10736 cx: &mut ViewContext<Self>,
10737 ) {
10738 self.display_map
10739 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10740 if let Some(autoscroll) = autoscroll {
10741 self.request_autoscroll(autoscroll, cx);
10742 }
10743 cx.notify();
10744 }
10745
10746 pub fn replace_blocks(
10747 &mut self,
10748 renderers: HashMap<CustomBlockId, RenderBlock>,
10749 autoscroll: Option<Autoscroll>,
10750 cx: &mut ViewContext<Self>,
10751 ) {
10752 self.display_map
10753 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10754 if let Some(autoscroll) = autoscroll {
10755 self.request_autoscroll(autoscroll, cx);
10756 }
10757 cx.notify();
10758 }
10759
10760 pub fn remove_blocks(
10761 &mut self,
10762 block_ids: HashSet<CustomBlockId>,
10763 autoscroll: Option<Autoscroll>,
10764 cx: &mut ViewContext<Self>,
10765 ) {
10766 self.display_map.update(cx, |display_map, cx| {
10767 display_map.remove_blocks(block_ids, cx)
10768 });
10769 if let Some(autoscroll) = autoscroll {
10770 self.request_autoscroll(autoscroll, cx);
10771 }
10772 cx.notify();
10773 }
10774
10775 pub fn row_for_block(
10776 &self,
10777 block_id: CustomBlockId,
10778 cx: &mut ViewContext<Self>,
10779 ) -> Option<DisplayRow> {
10780 self.display_map
10781 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10782 }
10783
10784 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10785 self.focused_block = Some(focused_block);
10786 }
10787
10788 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10789 self.focused_block.take()
10790 }
10791
10792 pub fn insert_creases(
10793 &mut self,
10794 creases: impl IntoIterator<Item = Crease>,
10795 cx: &mut ViewContext<Self>,
10796 ) -> Vec<CreaseId> {
10797 self.display_map
10798 .update(cx, |map, cx| map.insert_creases(creases, cx))
10799 }
10800
10801 pub fn remove_creases(
10802 &mut self,
10803 ids: impl IntoIterator<Item = CreaseId>,
10804 cx: &mut ViewContext<Self>,
10805 ) {
10806 self.display_map
10807 .update(cx, |map, cx| map.remove_creases(ids, cx));
10808 }
10809
10810 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10811 self.display_map
10812 .update(cx, |map, cx| map.snapshot(cx))
10813 .longest_row()
10814 }
10815
10816 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10817 self.display_map
10818 .update(cx, |map, cx| map.snapshot(cx))
10819 .max_point()
10820 }
10821
10822 pub fn text(&self, cx: &AppContext) -> String {
10823 self.buffer.read(cx).read(cx).text()
10824 }
10825
10826 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10827 let text = self.text(cx);
10828 let text = text.trim();
10829
10830 if text.is_empty() {
10831 return None;
10832 }
10833
10834 Some(text.to_string())
10835 }
10836
10837 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10838 self.transact(cx, |this, cx| {
10839 this.buffer
10840 .read(cx)
10841 .as_singleton()
10842 .expect("you can only call set_text on editors for singleton buffers")
10843 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10844 });
10845 }
10846
10847 pub fn display_text(&self, cx: &mut AppContext) -> String {
10848 self.display_map
10849 .update(cx, |map, cx| map.snapshot(cx))
10850 .text()
10851 }
10852
10853 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10854 let mut wrap_guides = smallvec::smallvec![];
10855
10856 if self.show_wrap_guides == Some(false) {
10857 return wrap_guides;
10858 }
10859
10860 let settings = self.buffer.read(cx).settings_at(0, cx);
10861 if settings.show_wrap_guides {
10862 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10863 wrap_guides.push((soft_wrap as usize, true));
10864 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
10865 wrap_guides.push((soft_wrap as usize, true));
10866 }
10867 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10868 }
10869
10870 wrap_guides
10871 }
10872
10873 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10874 let settings = self.buffer.read(cx).settings_at(0, cx);
10875 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
10876 match mode {
10877 language_settings::SoftWrap::None => SoftWrap::None,
10878 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10879 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10880 language_settings::SoftWrap::PreferredLineLength => {
10881 SoftWrap::Column(settings.preferred_line_length)
10882 }
10883 language_settings::SoftWrap::Bounded => {
10884 SoftWrap::Bounded(settings.preferred_line_length)
10885 }
10886 }
10887 }
10888
10889 pub fn set_soft_wrap_mode(
10890 &mut self,
10891 mode: language_settings::SoftWrap,
10892 cx: &mut ViewContext<Self>,
10893 ) {
10894 self.soft_wrap_mode_override = Some(mode);
10895 cx.notify();
10896 }
10897
10898 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10899 let rem_size = cx.rem_size();
10900 self.display_map.update(cx, |map, cx| {
10901 map.set_font(
10902 style.text.font(),
10903 style.text.font_size.to_pixels(rem_size),
10904 cx,
10905 )
10906 });
10907 self.style = Some(style);
10908 }
10909
10910 pub fn style(&self) -> Option<&EditorStyle> {
10911 self.style.as_ref()
10912 }
10913
10914 // Called by the element. This method is not designed to be called outside of the editor
10915 // element's layout code because it does not notify when rewrapping is computed synchronously.
10916 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10917 self.display_map
10918 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10919 }
10920
10921 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10922 if self.soft_wrap_mode_override.is_some() {
10923 self.soft_wrap_mode_override.take();
10924 } else {
10925 let soft_wrap = match self.soft_wrap_mode(cx) {
10926 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10927 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
10928 language_settings::SoftWrap::PreferLine
10929 }
10930 };
10931 self.soft_wrap_mode_override = Some(soft_wrap);
10932 }
10933 cx.notify();
10934 }
10935
10936 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10937 let Some(workspace) = self.workspace() else {
10938 return;
10939 };
10940 let fs = workspace.read(cx).app_state().fs.clone();
10941 let current_show = TabBarSettings::get_global(cx).show;
10942 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10943 setting.show = Some(!current_show);
10944 });
10945 }
10946
10947 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10948 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10949 self.buffer
10950 .read(cx)
10951 .settings_at(0, cx)
10952 .indent_guides
10953 .enabled
10954 });
10955 self.show_indent_guides = Some(!currently_enabled);
10956 cx.notify();
10957 }
10958
10959 fn should_show_indent_guides(&self) -> Option<bool> {
10960 self.show_indent_guides
10961 }
10962
10963 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10964 let mut editor_settings = EditorSettings::get_global(cx).clone();
10965 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10966 EditorSettings::override_global(editor_settings, cx);
10967 }
10968
10969 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
10970 self.use_relative_line_numbers
10971 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
10972 }
10973
10974 pub fn toggle_relative_line_numbers(
10975 &mut self,
10976 _: &ToggleRelativeLineNumbers,
10977 cx: &mut ViewContext<Self>,
10978 ) {
10979 let is_relative = self.should_use_relative_line_numbers(cx);
10980 self.set_relative_line_number(Some(!is_relative), cx)
10981 }
10982
10983 pub fn set_relative_line_number(
10984 &mut self,
10985 is_relative: Option<bool>,
10986 cx: &mut ViewContext<Self>,
10987 ) {
10988 self.use_relative_line_numbers = is_relative;
10989 cx.notify();
10990 }
10991
10992 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10993 self.show_gutter = show_gutter;
10994 cx.notify();
10995 }
10996
10997 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10998 self.show_line_numbers = Some(show_line_numbers);
10999 cx.notify();
11000 }
11001
11002 pub fn set_show_git_diff_gutter(
11003 &mut self,
11004 show_git_diff_gutter: bool,
11005 cx: &mut ViewContext<Self>,
11006 ) {
11007 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11008 cx.notify();
11009 }
11010
11011 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11012 self.show_code_actions = Some(show_code_actions);
11013 cx.notify();
11014 }
11015
11016 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11017 self.show_runnables = Some(show_runnables);
11018 cx.notify();
11019 }
11020
11021 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11022 if self.display_map.read(cx).masked != masked {
11023 self.display_map.update(cx, |map, _| map.masked = masked);
11024 }
11025 cx.notify()
11026 }
11027
11028 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11029 self.show_wrap_guides = Some(show_wrap_guides);
11030 cx.notify();
11031 }
11032
11033 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11034 self.show_indent_guides = Some(show_indent_guides);
11035 cx.notify();
11036 }
11037
11038 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11039 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11040 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11041 if let Some(dir) = file.abs_path(cx).parent() {
11042 return Some(dir.to_owned());
11043 }
11044 }
11045
11046 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11047 return Some(project_path.path.to_path_buf());
11048 }
11049 }
11050
11051 None
11052 }
11053
11054 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11055 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11056 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11057 cx.reveal_path(&file.abs_path(cx));
11058 }
11059 }
11060 }
11061
11062 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11063 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11064 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11065 if let Some(path) = file.abs_path(cx).to_str() {
11066 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11067 }
11068 }
11069 }
11070 }
11071
11072 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11073 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11074 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11075 if let Some(path) = file.path().to_str() {
11076 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11077 }
11078 }
11079 }
11080 }
11081
11082 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11083 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11084
11085 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11086 self.start_git_blame(true, cx);
11087 }
11088
11089 cx.notify();
11090 }
11091
11092 pub fn toggle_git_blame_inline(
11093 &mut self,
11094 _: &ToggleGitBlameInline,
11095 cx: &mut ViewContext<Self>,
11096 ) {
11097 self.toggle_git_blame_inline_internal(true, cx);
11098 cx.notify();
11099 }
11100
11101 pub fn git_blame_inline_enabled(&self) -> bool {
11102 self.git_blame_inline_enabled
11103 }
11104
11105 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11106 self.show_selection_menu = self
11107 .show_selection_menu
11108 .map(|show_selections_menu| !show_selections_menu)
11109 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11110
11111 cx.notify();
11112 }
11113
11114 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11115 self.show_selection_menu
11116 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11117 }
11118
11119 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11120 if let Some(project) = self.project.as_ref() {
11121 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11122 return;
11123 };
11124
11125 if buffer.read(cx).file().is_none() {
11126 return;
11127 }
11128
11129 let focused = self.focus_handle(cx).contains_focused(cx);
11130
11131 let project = project.clone();
11132 let blame =
11133 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11134 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11135 self.blame = Some(blame);
11136 }
11137 }
11138
11139 fn toggle_git_blame_inline_internal(
11140 &mut self,
11141 user_triggered: bool,
11142 cx: &mut ViewContext<Self>,
11143 ) {
11144 if self.git_blame_inline_enabled {
11145 self.git_blame_inline_enabled = false;
11146 self.show_git_blame_inline = false;
11147 self.show_git_blame_inline_delay_task.take();
11148 } else {
11149 self.git_blame_inline_enabled = true;
11150 self.start_git_blame_inline(user_triggered, cx);
11151 }
11152
11153 cx.notify();
11154 }
11155
11156 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11157 self.start_git_blame(user_triggered, cx);
11158
11159 if ProjectSettings::get_global(cx)
11160 .git
11161 .inline_blame_delay()
11162 .is_some()
11163 {
11164 self.start_inline_blame_timer(cx);
11165 } else {
11166 self.show_git_blame_inline = true
11167 }
11168 }
11169
11170 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11171 self.blame.as_ref()
11172 }
11173
11174 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11175 self.show_git_blame_gutter && self.has_blame_entries(cx)
11176 }
11177
11178 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11179 self.show_git_blame_inline
11180 && self.focus_handle.is_focused(cx)
11181 && !self.newest_selection_head_on_empty_line(cx)
11182 && self.has_blame_entries(cx)
11183 }
11184
11185 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11186 self.blame()
11187 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11188 }
11189
11190 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11191 let cursor_anchor = self.selections.newest_anchor().head();
11192
11193 let snapshot = self.buffer.read(cx).snapshot(cx);
11194 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11195
11196 snapshot.line_len(buffer_row) == 0
11197 }
11198
11199 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
11200 let (path, selection, repo) = maybe!({
11201 let project_handle = self.project.as_ref()?.clone();
11202 let project = project_handle.read(cx);
11203
11204 let selection = self.selections.newest::<Point>(cx);
11205 let selection_range = selection.range();
11206
11207 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11208 (buffer, selection_range.start.row..selection_range.end.row)
11209 } else {
11210 let buffer_ranges = self
11211 .buffer()
11212 .read(cx)
11213 .range_to_buffer_ranges(selection_range, cx);
11214
11215 let (buffer, range, _) = if selection.reversed {
11216 buffer_ranges.first()
11217 } else {
11218 buffer_ranges.last()
11219 }?;
11220
11221 let snapshot = buffer.read(cx).snapshot();
11222 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11223 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11224 (buffer.clone(), selection)
11225 };
11226
11227 let path = buffer
11228 .read(cx)
11229 .file()?
11230 .as_local()?
11231 .path()
11232 .to_str()?
11233 .to_string();
11234 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
11235 Some((path, selection, repo))
11236 })
11237 .ok_or_else(|| anyhow!("unable to open git repository"))?;
11238
11239 const REMOTE_NAME: &str = "origin";
11240 let origin_url = repo
11241 .remote_url(REMOTE_NAME)
11242 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
11243 let sha = repo
11244 .head_sha()
11245 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
11246
11247 let (provider, remote) =
11248 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
11249 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
11250
11251 Ok(provider.build_permalink(
11252 remote,
11253 BuildPermalinkParams {
11254 sha: &sha,
11255 path: &path,
11256 selection: Some(selection),
11257 },
11258 ))
11259 }
11260
11261 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11262 let permalink = self.get_permalink_to_line(cx);
11263
11264 match permalink {
11265 Ok(permalink) => {
11266 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11267 }
11268 Err(err) => {
11269 let message = format!("Failed to copy permalink: {err}");
11270
11271 Err::<(), anyhow::Error>(err).log_err();
11272
11273 if let Some(workspace) = self.workspace() {
11274 workspace.update(cx, |workspace, cx| {
11275 struct CopyPermalinkToLine;
11276
11277 workspace.show_toast(
11278 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
11279 cx,
11280 )
11281 })
11282 }
11283 }
11284 }
11285 }
11286
11287 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11288 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11289 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11290 if let Some(path) = file.path().to_str() {
11291 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11292 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11293 }
11294 }
11295 }
11296 }
11297
11298 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11299 let permalink = self.get_permalink_to_line(cx);
11300
11301 match permalink {
11302 Ok(permalink) => {
11303 cx.open_url(permalink.as_ref());
11304 }
11305 Err(err) => {
11306 let message = format!("Failed to open permalink: {err}");
11307
11308 Err::<(), anyhow::Error>(err).log_err();
11309
11310 if let Some(workspace) = self.workspace() {
11311 workspace.update(cx, |workspace, cx| {
11312 struct OpenPermalinkToLine;
11313
11314 workspace.show_toast(
11315 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11316 cx,
11317 )
11318 })
11319 }
11320 }
11321 }
11322 }
11323
11324 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
11325 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
11326 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
11327 pub fn highlight_rows<T: 'static>(
11328 &mut self,
11329 rows: RangeInclusive<Anchor>,
11330 color: Option<Hsla>,
11331 should_autoscroll: bool,
11332 cx: &mut ViewContext<Self>,
11333 ) {
11334 let snapshot = self.buffer().read(cx).snapshot(cx);
11335 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11336 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
11337 highlight
11338 .range
11339 .start()
11340 .cmp(rows.start(), &snapshot)
11341 .then(highlight.range.end().cmp(rows.end(), &snapshot))
11342 });
11343 match (color, existing_highlight_index) {
11344 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
11345 ix,
11346 RowHighlight {
11347 index: post_inc(&mut self.highlight_order),
11348 range: rows,
11349 should_autoscroll,
11350 color,
11351 },
11352 ),
11353 (None, Ok(i)) => {
11354 row_highlights.remove(i);
11355 }
11356 }
11357 }
11358
11359 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11360 pub fn clear_row_highlights<T: 'static>(&mut self) {
11361 self.highlighted_rows.remove(&TypeId::of::<T>());
11362 }
11363
11364 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11365 pub fn highlighted_rows<T: 'static>(
11366 &self,
11367 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
11368 Some(
11369 self.highlighted_rows
11370 .get(&TypeId::of::<T>())?
11371 .iter()
11372 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
11373 )
11374 }
11375
11376 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11377 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11378 /// Allows to ignore certain kinds of highlights.
11379 pub fn highlighted_display_rows(
11380 &mut self,
11381 cx: &mut WindowContext,
11382 ) -> BTreeMap<DisplayRow, Hsla> {
11383 let snapshot = self.snapshot(cx);
11384 let mut used_highlight_orders = HashMap::default();
11385 self.highlighted_rows
11386 .iter()
11387 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11388 .fold(
11389 BTreeMap::<DisplayRow, Hsla>::new(),
11390 |mut unique_rows, highlight| {
11391 let start_row = highlight.range.start().to_display_point(&snapshot).row();
11392 let end_row = highlight.range.end().to_display_point(&snapshot).row();
11393 for row in start_row.0..=end_row.0 {
11394 let used_index =
11395 used_highlight_orders.entry(row).or_insert(highlight.index);
11396 if highlight.index >= *used_index {
11397 *used_index = highlight.index;
11398 match highlight.color {
11399 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
11400 None => unique_rows.remove(&DisplayRow(row)),
11401 };
11402 }
11403 }
11404 unique_rows
11405 },
11406 )
11407 }
11408
11409 pub fn highlighted_display_row_for_autoscroll(
11410 &self,
11411 snapshot: &DisplaySnapshot,
11412 ) -> Option<DisplayRow> {
11413 self.highlighted_rows
11414 .values()
11415 .flat_map(|highlighted_rows| highlighted_rows.iter())
11416 .filter_map(|highlight| {
11417 if highlight.color.is_none() || !highlight.should_autoscroll {
11418 return None;
11419 }
11420 Some(highlight.range.start().to_display_point(snapshot).row())
11421 })
11422 .min()
11423 }
11424
11425 pub fn set_search_within_ranges(
11426 &mut self,
11427 ranges: &[Range<Anchor>],
11428 cx: &mut ViewContext<Self>,
11429 ) {
11430 self.highlight_background::<SearchWithinRange>(
11431 ranges,
11432 |colors| colors.editor_document_highlight_read_background,
11433 cx,
11434 )
11435 }
11436
11437 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11438 self.breadcrumb_header = Some(new_header);
11439 }
11440
11441 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11442 self.clear_background_highlights::<SearchWithinRange>(cx);
11443 }
11444
11445 pub fn highlight_background<T: 'static>(
11446 &mut self,
11447 ranges: &[Range<Anchor>],
11448 color_fetcher: fn(&ThemeColors) -> Hsla,
11449 cx: &mut ViewContext<Self>,
11450 ) {
11451 self.background_highlights
11452 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11453 self.scrollbar_marker_state.dirty = true;
11454 cx.notify();
11455 }
11456
11457 pub fn clear_background_highlights<T: 'static>(
11458 &mut self,
11459 cx: &mut ViewContext<Self>,
11460 ) -> Option<BackgroundHighlight> {
11461 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11462 if !text_highlights.1.is_empty() {
11463 self.scrollbar_marker_state.dirty = true;
11464 cx.notify();
11465 }
11466 Some(text_highlights)
11467 }
11468
11469 pub fn highlight_gutter<T: 'static>(
11470 &mut self,
11471 ranges: &[Range<Anchor>],
11472 color_fetcher: fn(&AppContext) -> Hsla,
11473 cx: &mut ViewContext<Self>,
11474 ) {
11475 self.gutter_highlights
11476 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11477 cx.notify();
11478 }
11479
11480 pub fn clear_gutter_highlights<T: 'static>(
11481 &mut self,
11482 cx: &mut ViewContext<Self>,
11483 ) -> Option<GutterHighlight> {
11484 cx.notify();
11485 self.gutter_highlights.remove(&TypeId::of::<T>())
11486 }
11487
11488 #[cfg(feature = "test-support")]
11489 pub fn all_text_background_highlights(
11490 &mut self,
11491 cx: &mut ViewContext<Self>,
11492 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11493 let snapshot = self.snapshot(cx);
11494 let buffer = &snapshot.buffer_snapshot;
11495 let start = buffer.anchor_before(0);
11496 let end = buffer.anchor_after(buffer.len());
11497 let theme = cx.theme().colors();
11498 self.background_highlights_in_range(start..end, &snapshot, theme)
11499 }
11500
11501 #[cfg(feature = "test-support")]
11502 pub fn search_background_highlights(
11503 &mut self,
11504 cx: &mut ViewContext<Self>,
11505 ) -> Vec<Range<Point>> {
11506 let snapshot = self.buffer().read(cx).snapshot(cx);
11507
11508 let highlights = self
11509 .background_highlights
11510 .get(&TypeId::of::<items::BufferSearchHighlights>());
11511
11512 if let Some((_color, ranges)) = highlights {
11513 ranges
11514 .iter()
11515 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11516 .collect_vec()
11517 } else {
11518 vec![]
11519 }
11520 }
11521
11522 fn document_highlights_for_position<'a>(
11523 &'a self,
11524 position: Anchor,
11525 buffer: &'a MultiBufferSnapshot,
11526 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11527 let read_highlights = self
11528 .background_highlights
11529 .get(&TypeId::of::<DocumentHighlightRead>())
11530 .map(|h| &h.1);
11531 let write_highlights = self
11532 .background_highlights
11533 .get(&TypeId::of::<DocumentHighlightWrite>())
11534 .map(|h| &h.1);
11535 let left_position = position.bias_left(buffer);
11536 let right_position = position.bias_right(buffer);
11537 read_highlights
11538 .into_iter()
11539 .chain(write_highlights)
11540 .flat_map(move |ranges| {
11541 let start_ix = match ranges.binary_search_by(|probe| {
11542 let cmp = probe.end.cmp(&left_position, buffer);
11543 if cmp.is_ge() {
11544 Ordering::Greater
11545 } else {
11546 Ordering::Less
11547 }
11548 }) {
11549 Ok(i) | Err(i) => i,
11550 };
11551
11552 ranges[start_ix..]
11553 .iter()
11554 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11555 })
11556 }
11557
11558 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11559 self.background_highlights
11560 .get(&TypeId::of::<T>())
11561 .map_or(false, |(_, highlights)| !highlights.is_empty())
11562 }
11563
11564 pub fn background_highlights_in_range(
11565 &self,
11566 search_range: Range<Anchor>,
11567 display_snapshot: &DisplaySnapshot,
11568 theme: &ThemeColors,
11569 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11570 let mut results = Vec::new();
11571 for (color_fetcher, ranges) in self.background_highlights.values() {
11572 let color = color_fetcher(theme);
11573 let start_ix = match ranges.binary_search_by(|probe| {
11574 let cmp = probe
11575 .end
11576 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11577 if cmp.is_gt() {
11578 Ordering::Greater
11579 } else {
11580 Ordering::Less
11581 }
11582 }) {
11583 Ok(i) | Err(i) => i,
11584 };
11585 for range in &ranges[start_ix..] {
11586 if range
11587 .start
11588 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11589 .is_ge()
11590 {
11591 break;
11592 }
11593
11594 let start = range.start.to_display_point(display_snapshot);
11595 let end = range.end.to_display_point(display_snapshot);
11596 results.push((start..end, color))
11597 }
11598 }
11599 results
11600 }
11601
11602 pub fn background_highlight_row_ranges<T: 'static>(
11603 &self,
11604 search_range: Range<Anchor>,
11605 display_snapshot: &DisplaySnapshot,
11606 count: usize,
11607 ) -> Vec<RangeInclusive<DisplayPoint>> {
11608 let mut results = Vec::new();
11609 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11610 return vec![];
11611 };
11612
11613 let start_ix = match ranges.binary_search_by(|probe| {
11614 let cmp = probe
11615 .end
11616 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11617 if cmp.is_gt() {
11618 Ordering::Greater
11619 } else {
11620 Ordering::Less
11621 }
11622 }) {
11623 Ok(i) | Err(i) => i,
11624 };
11625 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11626 if let (Some(start_display), Some(end_display)) = (start, end) {
11627 results.push(
11628 start_display.to_display_point(display_snapshot)
11629 ..=end_display.to_display_point(display_snapshot),
11630 );
11631 }
11632 };
11633 let mut start_row: Option<Point> = None;
11634 let mut end_row: Option<Point> = None;
11635 if ranges.len() > count {
11636 return Vec::new();
11637 }
11638 for range in &ranges[start_ix..] {
11639 if range
11640 .start
11641 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11642 .is_ge()
11643 {
11644 break;
11645 }
11646 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11647 if let Some(current_row) = &end_row {
11648 if end.row == current_row.row {
11649 continue;
11650 }
11651 }
11652 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11653 if start_row.is_none() {
11654 assert_eq!(end_row, None);
11655 start_row = Some(start);
11656 end_row = Some(end);
11657 continue;
11658 }
11659 if let Some(current_end) = end_row.as_mut() {
11660 if start.row > current_end.row + 1 {
11661 push_region(start_row, end_row);
11662 start_row = Some(start);
11663 end_row = Some(end);
11664 } else {
11665 // Merge two hunks.
11666 *current_end = end;
11667 }
11668 } else {
11669 unreachable!();
11670 }
11671 }
11672 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11673 push_region(start_row, end_row);
11674 results
11675 }
11676
11677 pub fn gutter_highlights_in_range(
11678 &self,
11679 search_range: Range<Anchor>,
11680 display_snapshot: &DisplaySnapshot,
11681 cx: &AppContext,
11682 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11683 let mut results = Vec::new();
11684 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11685 let color = color_fetcher(cx);
11686 let start_ix = match ranges.binary_search_by(|probe| {
11687 let cmp = probe
11688 .end
11689 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11690 if cmp.is_gt() {
11691 Ordering::Greater
11692 } else {
11693 Ordering::Less
11694 }
11695 }) {
11696 Ok(i) | Err(i) => i,
11697 };
11698 for range in &ranges[start_ix..] {
11699 if range
11700 .start
11701 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11702 .is_ge()
11703 {
11704 break;
11705 }
11706
11707 let start = range.start.to_display_point(display_snapshot);
11708 let end = range.end.to_display_point(display_snapshot);
11709 results.push((start..end, color))
11710 }
11711 }
11712 results
11713 }
11714
11715 /// Get the text ranges corresponding to the redaction query
11716 pub fn redacted_ranges(
11717 &self,
11718 search_range: Range<Anchor>,
11719 display_snapshot: &DisplaySnapshot,
11720 cx: &WindowContext,
11721 ) -> Vec<Range<DisplayPoint>> {
11722 display_snapshot
11723 .buffer_snapshot
11724 .redacted_ranges(search_range, |file| {
11725 if let Some(file) = file {
11726 file.is_private()
11727 && EditorSettings::get(
11728 Some(SettingsLocation {
11729 worktree_id: file.worktree_id(cx),
11730 path: file.path().as_ref(),
11731 }),
11732 cx,
11733 )
11734 .redact_private_values
11735 } else {
11736 false
11737 }
11738 })
11739 .map(|range| {
11740 range.start.to_display_point(display_snapshot)
11741 ..range.end.to_display_point(display_snapshot)
11742 })
11743 .collect()
11744 }
11745
11746 pub fn highlight_text<T: 'static>(
11747 &mut self,
11748 ranges: Vec<Range<Anchor>>,
11749 style: HighlightStyle,
11750 cx: &mut ViewContext<Self>,
11751 ) {
11752 self.display_map.update(cx, |map, _| {
11753 map.highlight_text(TypeId::of::<T>(), ranges, style)
11754 });
11755 cx.notify();
11756 }
11757
11758 pub(crate) fn highlight_inlays<T: 'static>(
11759 &mut self,
11760 highlights: Vec<InlayHighlight>,
11761 style: HighlightStyle,
11762 cx: &mut ViewContext<Self>,
11763 ) {
11764 self.display_map.update(cx, |map, _| {
11765 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11766 });
11767 cx.notify();
11768 }
11769
11770 pub fn text_highlights<'a, T: 'static>(
11771 &'a self,
11772 cx: &'a AppContext,
11773 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11774 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11775 }
11776
11777 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11778 let cleared = self
11779 .display_map
11780 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11781 if cleared {
11782 cx.notify();
11783 }
11784 }
11785
11786 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11787 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11788 && self.focus_handle.is_focused(cx)
11789 }
11790
11791 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11792 self.show_cursor_when_unfocused = is_enabled;
11793 cx.notify();
11794 }
11795
11796 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11797 cx.notify();
11798 }
11799
11800 fn on_buffer_event(
11801 &mut self,
11802 multibuffer: Model<MultiBuffer>,
11803 event: &multi_buffer::Event,
11804 cx: &mut ViewContext<Self>,
11805 ) {
11806 match event {
11807 multi_buffer::Event::Edited {
11808 singleton_buffer_edited,
11809 } => {
11810 self.scrollbar_marker_state.dirty = true;
11811 self.active_indent_guides_state.dirty = true;
11812 self.refresh_active_diagnostics(cx);
11813 self.refresh_code_actions(cx);
11814 if self.has_active_inline_completion(cx) {
11815 self.update_visible_inline_completion(cx);
11816 }
11817 cx.emit(EditorEvent::BufferEdited);
11818 cx.emit(SearchEvent::MatchesInvalidated);
11819 if *singleton_buffer_edited {
11820 if let Some(project) = &self.project {
11821 let project = project.read(cx);
11822 #[allow(clippy::mutable_key_type)]
11823 let languages_affected = multibuffer
11824 .read(cx)
11825 .all_buffers()
11826 .into_iter()
11827 .filter_map(|buffer| {
11828 let buffer = buffer.read(cx);
11829 let language = buffer.language()?;
11830 if project.is_local()
11831 && project.language_servers_for_buffer(buffer, cx).count() == 0
11832 {
11833 None
11834 } else {
11835 Some(language)
11836 }
11837 })
11838 .cloned()
11839 .collect::<HashSet<_>>();
11840 if !languages_affected.is_empty() {
11841 self.refresh_inlay_hints(
11842 InlayHintRefreshReason::BufferEdited(languages_affected),
11843 cx,
11844 );
11845 }
11846 }
11847 }
11848
11849 let Some(project) = &self.project else { return };
11850 let telemetry = project.read(cx).client().telemetry().clone();
11851 refresh_linked_ranges(self, cx);
11852 telemetry.log_edit_event("editor");
11853 }
11854 multi_buffer::Event::ExcerptsAdded {
11855 buffer,
11856 predecessor,
11857 excerpts,
11858 } => {
11859 self.tasks_update_task = Some(self.refresh_runnables(cx));
11860 cx.emit(EditorEvent::ExcerptsAdded {
11861 buffer: buffer.clone(),
11862 predecessor: *predecessor,
11863 excerpts: excerpts.clone(),
11864 });
11865 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11866 }
11867 multi_buffer::Event::ExcerptsRemoved { ids } => {
11868 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11869 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11870 }
11871 multi_buffer::Event::ExcerptsEdited { ids } => {
11872 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11873 }
11874 multi_buffer::Event::ExcerptsExpanded { ids } => {
11875 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11876 }
11877 multi_buffer::Event::Reparsed(buffer_id) => {
11878 self.tasks_update_task = Some(self.refresh_runnables(cx));
11879
11880 cx.emit(EditorEvent::Reparsed(*buffer_id));
11881 }
11882 multi_buffer::Event::LanguageChanged(buffer_id) => {
11883 linked_editing_ranges::refresh_linked_ranges(self, cx);
11884 cx.emit(EditorEvent::Reparsed(*buffer_id));
11885 cx.notify();
11886 }
11887 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11888 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11889 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11890 cx.emit(EditorEvent::TitleChanged)
11891 }
11892 multi_buffer::Event::DiffBaseChanged => {
11893 self.scrollbar_marker_state.dirty = true;
11894 cx.emit(EditorEvent::DiffBaseChanged);
11895 cx.notify();
11896 }
11897 multi_buffer::Event::DiffUpdated { buffer } => {
11898 self.sync_expanded_diff_hunks(buffer.clone(), cx);
11899 cx.notify();
11900 }
11901 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11902 multi_buffer::Event::DiagnosticsUpdated => {
11903 self.refresh_active_diagnostics(cx);
11904 self.scrollbar_marker_state.dirty = true;
11905 cx.notify();
11906 }
11907 _ => {}
11908 };
11909 }
11910
11911 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11912 cx.notify();
11913 }
11914
11915 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11916 self.tasks_update_task = Some(self.refresh_runnables(cx));
11917 self.refresh_inline_completion(true, false, cx);
11918 self.refresh_inlay_hints(
11919 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11920 self.selections.newest_anchor().head(),
11921 &self.buffer.read(cx).snapshot(cx),
11922 cx,
11923 )),
11924 cx,
11925 );
11926 let editor_settings = EditorSettings::get_global(cx);
11927 if let Some(cursor_shape) = editor_settings.cursor_shape {
11928 self.cursor_shape = cursor_shape;
11929 }
11930 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11931 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11932
11933 let project_settings = ProjectSettings::get_global(cx);
11934 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11935
11936 if self.mode == EditorMode::Full {
11937 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11938 if self.git_blame_inline_enabled != inline_blame_enabled {
11939 self.toggle_git_blame_inline_internal(false, cx);
11940 }
11941 }
11942
11943 cx.notify();
11944 }
11945
11946 pub fn set_searchable(&mut self, searchable: bool) {
11947 self.searchable = searchable;
11948 }
11949
11950 pub fn searchable(&self) -> bool {
11951 self.searchable
11952 }
11953
11954 fn open_proposed_changes_editor(
11955 &mut self,
11956 _: &OpenProposedChangesEditor,
11957 cx: &mut ViewContext<Self>,
11958 ) {
11959 let Some(workspace) = self.workspace() else {
11960 cx.propagate();
11961 return;
11962 };
11963
11964 let buffer = self.buffer.read(cx);
11965 let mut new_selections_by_buffer = HashMap::default();
11966 for selection in self.selections.all::<usize>(cx) {
11967 for (buffer, mut range, _) in
11968 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11969 {
11970 if selection.reversed {
11971 mem::swap(&mut range.start, &mut range.end);
11972 }
11973 let mut range = range.to_point(buffer.read(cx));
11974 range.start.column = 0;
11975 range.end.column = buffer.read(cx).line_len(range.end.row);
11976 new_selections_by_buffer
11977 .entry(buffer)
11978 .or_insert(Vec::new())
11979 .push(range)
11980 }
11981 }
11982
11983 let proposed_changes_buffers = new_selections_by_buffer
11984 .into_iter()
11985 .map(|(buffer, ranges)| ProposedChangesBuffer { buffer, ranges })
11986 .collect::<Vec<_>>();
11987 let proposed_changes_editor = cx.new_view(|cx| {
11988 ProposedChangesEditor::new(proposed_changes_buffers, self.project.clone(), cx)
11989 });
11990
11991 cx.window_context().defer(move |cx| {
11992 workspace.update(cx, |workspace, cx| {
11993 workspace.active_pane().update(cx, |pane, cx| {
11994 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
11995 });
11996 });
11997 });
11998 }
11999
12000 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12001 self.open_excerpts_common(true, cx)
12002 }
12003
12004 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12005 self.open_excerpts_common(false, cx)
12006 }
12007
12008 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12009 let buffer = self.buffer.read(cx);
12010 if buffer.is_singleton() {
12011 cx.propagate();
12012 return;
12013 }
12014
12015 let Some(workspace) = self.workspace() else {
12016 cx.propagate();
12017 return;
12018 };
12019
12020 let mut new_selections_by_buffer = HashMap::default();
12021 for selection in self.selections.all::<usize>(cx) {
12022 for (buffer, mut range, _) in
12023 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12024 {
12025 if selection.reversed {
12026 mem::swap(&mut range.start, &mut range.end);
12027 }
12028 new_selections_by_buffer
12029 .entry(buffer)
12030 .or_insert(Vec::new())
12031 .push(range)
12032 }
12033 }
12034
12035 // We defer the pane interaction because we ourselves are a workspace item
12036 // and activating a new item causes the pane to call a method on us reentrantly,
12037 // which panics if we're on the stack.
12038 cx.window_context().defer(move |cx| {
12039 workspace.update(cx, |workspace, cx| {
12040 let pane = if split {
12041 workspace.adjacent_pane(cx)
12042 } else {
12043 workspace.active_pane().clone()
12044 };
12045
12046 for (buffer, ranges) in new_selections_by_buffer {
12047 let editor =
12048 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12049 editor.update(cx, |editor, cx| {
12050 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12051 s.select_ranges(ranges);
12052 });
12053 });
12054 }
12055 })
12056 });
12057 }
12058
12059 fn jump(
12060 &mut self,
12061 path: ProjectPath,
12062 position: Point,
12063 anchor: language::Anchor,
12064 offset_from_top: u32,
12065 cx: &mut ViewContext<Self>,
12066 ) {
12067 let workspace = self.workspace();
12068 cx.spawn(|_, mut cx| async move {
12069 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12070 let editor = workspace.update(&mut cx, |workspace, cx| {
12071 // Reset the preview item id before opening the new item
12072 workspace.active_pane().update(cx, |pane, cx| {
12073 pane.set_preview_item_id(None, cx);
12074 });
12075 workspace.open_path_preview(path, None, true, true, cx)
12076 })?;
12077 let editor = editor
12078 .await?
12079 .downcast::<Editor>()
12080 .ok_or_else(|| anyhow!("opened item was not an editor"))?
12081 .downgrade();
12082 editor.update(&mut cx, |editor, cx| {
12083 let buffer = editor
12084 .buffer()
12085 .read(cx)
12086 .as_singleton()
12087 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12088 let buffer = buffer.read(cx);
12089 let cursor = if buffer.can_resolve(&anchor) {
12090 language::ToPoint::to_point(&anchor, buffer)
12091 } else {
12092 buffer.clip_point(position, Bias::Left)
12093 };
12094
12095 let nav_history = editor.nav_history.take();
12096 editor.change_selections(
12097 Some(Autoscroll::top_relative(offset_from_top as usize)),
12098 cx,
12099 |s| {
12100 s.select_ranges([cursor..cursor]);
12101 },
12102 );
12103 editor.nav_history = nav_history;
12104
12105 anyhow::Ok(())
12106 })??;
12107
12108 anyhow::Ok(())
12109 })
12110 .detach_and_log_err(cx);
12111 }
12112
12113 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12114 let snapshot = self.buffer.read(cx).read(cx);
12115 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12116 Some(
12117 ranges
12118 .iter()
12119 .map(move |range| {
12120 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12121 })
12122 .collect(),
12123 )
12124 }
12125
12126 fn selection_replacement_ranges(
12127 &self,
12128 range: Range<OffsetUtf16>,
12129 cx: &AppContext,
12130 ) -> Vec<Range<OffsetUtf16>> {
12131 let selections = self.selections.all::<OffsetUtf16>(cx);
12132 let newest_selection = selections
12133 .iter()
12134 .max_by_key(|selection| selection.id)
12135 .unwrap();
12136 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12137 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12138 let snapshot = self.buffer.read(cx).read(cx);
12139 selections
12140 .into_iter()
12141 .map(|mut selection| {
12142 selection.start.0 =
12143 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12144 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12145 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12146 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12147 })
12148 .collect()
12149 }
12150
12151 fn report_editor_event(
12152 &self,
12153 operation: &'static str,
12154 file_extension: Option<String>,
12155 cx: &AppContext,
12156 ) {
12157 if cfg!(any(test, feature = "test-support")) {
12158 return;
12159 }
12160
12161 let Some(project) = &self.project else { return };
12162
12163 // If None, we are in a file without an extension
12164 let file = self
12165 .buffer
12166 .read(cx)
12167 .as_singleton()
12168 .and_then(|b| b.read(cx).file());
12169 let file_extension = file_extension.or(file
12170 .as_ref()
12171 .and_then(|file| Path::new(file.file_name(cx)).extension())
12172 .and_then(|e| e.to_str())
12173 .map(|a| a.to_string()));
12174
12175 let vim_mode = cx
12176 .global::<SettingsStore>()
12177 .raw_user_settings()
12178 .get("vim_mode")
12179 == Some(&serde_json::Value::Bool(true));
12180
12181 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12182 == language::language_settings::InlineCompletionProvider::Copilot;
12183 let copilot_enabled_for_language = self
12184 .buffer
12185 .read(cx)
12186 .settings_at(0, cx)
12187 .show_inline_completions;
12188
12189 let telemetry = project.read(cx).client().telemetry().clone();
12190 telemetry.report_editor_event(
12191 file_extension,
12192 vim_mode,
12193 operation,
12194 copilot_enabled,
12195 copilot_enabled_for_language,
12196 )
12197 }
12198
12199 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12200 /// with each line being an array of {text, highlight} objects.
12201 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12202 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12203 return;
12204 };
12205
12206 #[derive(Serialize)]
12207 struct Chunk<'a> {
12208 text: String,
12209 highlight: Option<&'a str>,
12210 }
12211
12212 let snapshot = buffer.read(cx).snapshot();
12213 let range = self
12214 .selected_text_range(false, cx)
12215 .and_then(|selection| {
12216 if selection.range.is_empty() {
12217 None
12218 } else {
12219 Some(selection.range)
12220 }
12221 })
12222 .unwrap_or_else(|| 0..snapshot.len());
12223
12224 let chunks = snapshot.chunks(range, true);
12225 let mut lines = Vec::new();
12226 let mut line: VecDeque<Chunk> = VecDeque::new();
12227
12228 let Some(style) = self.style.as_ref() else {
12229 return;
12230 };
12231
12232 for chunk in chunks {
12233 let highlight = chunk
12234 .syntax_highlight_id
12235 .and_then(|id| id.name(&style.syntax));
12236 let mut chunk_lines = chunk.text.split('\n').peekable();
12237 while let Some(text) = chunk_lines.next() {
12238 let mut merged_with_last_token = false;
12239 if let Some(last_token) = line.back_mut() {
12240 if last_token.highlight == highlight {
12241 last_token.text.push_str(text);
12242 merged_with_last_token = true;
12243 }
12244 }
12245
12246 if !merged_with_last_token {
12247 line.push_back(Chunk {
12248 text: text.into(),
12249 highlight,
12250 });
12251 }
12252
12253 if chunk_lines.peek().is_some() {
12254 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12255 line.pop_front();
12256 }
12257 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12258 line.pop_back();
12259 }
12260
12261 lines.push(mem::take(&mut line));
12262 }
12263 }
12264 }
12265
12266 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12267 return;
12268 };
12269 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12270 }
12271
12272 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12273 &self.inlay_hint_cache
12274 }
12275
12276 pub fn replay_insert_event(
12277 &mut self,
12278 text: &str,
12279 relative_utf16_range: Option<Range<isize>>,
12280 cx: &mut ViewContext<Self>,
12281 ) {
12282 if !self.input_enabled {
12283 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12284 return;
12285 }
12286 if let Some(relative_utf16_range) = relative_utf16_range {
12287 let selections = self.selections.all::<OffsetUtf16>(cx);
12288 self.change_selections(None, cx, |s| {
12289 let new_ranges = selections.into_iter().map(|range| {
12290 let start = OffsetUtf16(
12291 range
12292 .head()
12293 .0
12294 .saturating_add_signed(relative_utf16_range.start),
12295 );
12296 let end = OffsetUtf16(
12297 range
12298 .head()
12299 .0
12300 .saturating_add_signed(relative_utf16_range.end),
12301 );
12302 start..end
12303 });
12304 s.select_ranges(new_ranges);
12305 });
12306 }
12307
12308 self.handle_input(text, cx);
12309 }
12310
12311 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12312 let Some(project) = self.project.as_ref() else {
12313 return false;
12314 };
12315 let project = project.read(cx);
12316
12317 let mut supports = false;
12318 self.buffer().read(cx).for_each_buffer(|buffer| {
12319 if !supports {
12320 supports = project
12321 .language_servers_for_buffer(buffer.read(cx), cx)
12322 .any(
12323 |(_, server)| match server.capabilities().inlay_hint_provider {
12324 Some(lsp::OneOf::Left(enabled)) => enabled,
12325 Some(lsp::OneOf::Right(_)) => true,
12326 None => false,
12327 },
12328 )
12329 }
12330 });
12331 supports
12332 }
12333
12334 pub fn focus(&self, cx: &mut WindowContext) {
12335 cx.focus(&self.focus_handle)
12336 }
12337
12338 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12339 self.focus_handle.is_focused(cx)
12340 }
12341
12342 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12343 cx.emit(EditorEvent::Focused);
12344
12345 if let Some(descendant) = self
12346 .last_focused_descendant
12347 .take()
12348 .and_then(|descendant| descendant.upgrade())
12349 {
12350 cx.focus(&descendant);
12351 } else {
12352 if let Some(blame) = self.blame.as_ref() {
12353 blame.update(cx, GitBlame::focus)
12354 }
12355
12356 self.blink_manager.update(cx, BlinkManager::enable);
12357 self.show_cursor_names(cx);
12358 self.buffer.update(cx, |buffer, cx| {
12359 buffer.finalize_last_transaction(cx);
12360 if self.leader_peer_id.is_none() {
12361 buffer.set_active_selections(
12362 &self.selections.disjoint_anchors(),
12363 self.selections.line_mode,
12364 self.cursor_shape,
12365 cx,
12366 );
12367 }
12368 });
12369 }
12370 }
12371
12372 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12373 cx.emit(EditorEvent::FocusedIn)
12374 }
12375
12376 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12377 if event.blurred != self.focus_handle {
12378 self.last_focused_descendant = Some(event.blurred);
12379 }
12380 }
12381
12382 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12383 self.blink_manager.update(cx, BlinkManager::disable);
12384 self.buffer
12385 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12386
12387 if let Some(blame) = self.blame.as_ref() {
12388 blame.update(cx, GitBlame::blur)
12389 }
12390 if !self.hover_state.focused(cx) {
12391 hide_hover(self, cx);
12392 }
12393
12394 self.hide_context_menu(cx);
12395 cx.emit(EditorEvent::Blurred);
12396 cx.notify();
12397 }
12398
12399 pub fn register_action<A: Action>(
12400 &mut self,
12401 listener: impl Fn(&A, &mut WindowContext) + 'static,
12402 ) -> Subscription {
12403 let id = self.next_editor_action_id.post_inc();
12404 let listener = Arc::new(listener);
12405 self.editor_actions.borrow_mut().insert(
12406 id,
12407 Box::new(move |cx| {
12408 let cx = cx.window_context();
12409 let listener = listener.clone();
12410 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12411 let action = action.downcast_ref().unwrap();
12412 if phase == DispatchPhase::Bubble {
12413 listener(action, cx)
12414 }
12415 })
12416 }),
12417 );
12418
12419 let editor_actions = self.editor_actions.clone();
12420 Subscription::new(move || {
12421 editor_actions.borrow_mut().remove(&id);
12422 })
12423 }
12424
12425 pub fn file_header_size(&self) -> u32 {
12426 self.file_header_size
12427 }
12428
12429 pub fn revert(
12430 &mut self,
12431 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12432 cx: &mut ViewContext<Self>,
12433 ) {
12434 self.buffer().update(cx, |multi_buffer, cx| {
12435 for (buffer_id, changes) in revert_changes {
12436 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12437 buffer.update(cx, |buffer, cx| {
12438 buffer.edit(
12439 changes.into_iter().map(|(range, text)| {
12440 (range, text.to_string().map(Arc::<str>::from))
12441 }),
12442 None,
12443 cx,
12444 );
12445 });
12446 }
12447 }
12448 });
12449 self.change_selections(None, cx, |selections| selections.refresh());
12450 }
12451
12452 pub fn to_pixel_point(
12453 &mut self,
12454 source: multi_buffer::Anchor,
12455 editor_snapshot: &EditorSnapshot,
12456 cx: &mut ViewContext<Self>,
12457 ) -> Option<gpui::Point<Pixels>> {
12458 let source_point = source.to_display_point(editor_snapshot);
12459 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12460 }
12461
12462 pub fn display_to_pixel_point(
12463 &mut self,
12464 source: DisplayPoint,
12465 editor_snapshot: &EditorSnapshot,
12466 cx: &mut ViewContext<Self>,
12467 ) -> Option<gpui::Point<Pixels>> {
12468 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12469 let text_layout_details = self.text_layout_details(cx);
12470 let scroll_top = text_layout_details
12471 .scroll_anchor
12472 .scroll_position(editor_snapshot)
12473 .y;
12474
12475 if source.row().as_f32() < scroll_top.floor() {
12476 return None;
12477 }
12478 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12479 let source_y = line_height * (source.row().as_f32() - scroll_top);
12480 Some(gpui::Point::new(source_x, source_y))
12481 }
12482
12483 pub fn has_active_completions_menu(&self) -> bool {
12484 self.context_menu.read().as_ref().map_or(false, |menu| {
12485 menu.visible() && matches!(menu, ContextMenu::Completions(_))
12486 })
12487 }
12488
12489 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12490 self.addons
12491 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12492 }
12493
12494 pub fn unregister_addon<T: Addon>(&mut self) {
12495 self.addons.remove(&std::any::TypeId::of::<T>());
12496 }
12497
12498 pub fn addon<T: Addon>(&self) -> Option<&T> {
12499 let type_id = std::any::TypeId::of::<T>();
12500 self.addons
12501 .get(&type_id)
12502 .and_then(|item| item.to_any().downcast_ref::<T>())
12503 }
12504}
12505
12506fn hunks_for_selections(
12507 multi_buffer_snapshot: &MultiBufferSnapshot,
12508 selections: &[Selection<Anchor>],
12509) -> Vec<MultiBufferDiffHunk> {
12510 let buffer_rows_for_selections = selections.iter().map(|selection| {
12511 let head = selection.head();
12512 let tail = selection.tail();
12513 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12514 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12515 if start > end {
12516 end..start
12517 } else {
12518 start..end
12519 }
12520 });
12521
12522 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12523}
12524
12525pub fn hunks_for_rows(
12526 rows: impl Iterator<Item = Range<MultiBufferRow>>,
12527 multi_buffer_snapshot: &MultiBufferSnapshot,
12528) -> Vec<MultiBufferDiffHunk> {
12529 let mut hunks = Vec::new();
12530 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12531 HashMap::default();
12532 for selected_multi_buffer_rows in rows {
12533 let query_rows =
12534 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12535 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12536 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12537 // when the caret is just above or just below the deleted hunk.
12538 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12539 let related_to_selection = if allow_adjacent {
12540 hunk.row_range.overlaps(&query_rows)
12541 || hunk.row_range.start == query_rows.end
12542 || hunk.row_range.end == query_rows.start
12543 } else {
12544 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12545 // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12546 hunk.row_range.overlaps(&selected_multi_buffer_rows)
12547 || selected_multi_buffer_rows.end == hunk.row_range.start
12548 };
12549 if related_to_selection {
12550 if !processed_buffer_rows
12551 .entry(hunk.buffer_id)
12552 .or_default()
12553 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12554 {
12555 continue;
12556 }
12557 hunks.push(hunk);
12558 }
12559 }
12560 }
12561
12562 hunks
12563}
12564
12565pub trait CollaborationHub {
12566 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12567 fn user_participant_indices<'a>(
12568 &self,
12569 cx: &'a AppContext,
12570 ) -> &'a HashMap<u64, ParticipantIndex>;
12571 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12572}
12573
12574impl CollaborationHub for Model<Project> {
12575 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12576 self.read(cx).collaborators()
12577 }
12578
12579 fn user_participant_indices<'a>(
12580 &self,
12581 cx: &'a AppContext,
12582 ) -> &'a HashMap<u64, ParticipantIndex> {
12583 self.read(cx).user_store().read(cx).participant_indices()
12584 }
12585
12586 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12587 let this = self.read(cx);
12588 let user_ids = this.collaborators().values().map(|c| c.user_id);
12589 this.user_store().read_with(cx, |user_store, cx| {
12590 user_store.participant_names(user_ids, cx)
12591 })
12592 }
12593}
12594
12595pub trait CompletionProvider {
12596 fn completions(
12597 &self,
12598 buffer: &Model<Buffer>,
12599 buffer_position: text::Anchor,
12600 trigger: CompletionContext,
12601 cx: &mut ViewContext<Editor>,
12602 ) -> Task<Result<Vec<Completion>>>;
12603
12604 fn resolve_completions(
12605 &self,
12606 buffer: Model<Buffer>,
12607 completion_indices: Vec<usize>,
12608 completions: Arc<RwLock<Box<[Completion]>>>,
12609 cx: &mut ViewContext<Editor>,
12610 ) -> Task<Result<bool>>;
12611
12612 fn apply_additional_edits_for_completion(
12613 &self,
12614 buffer: Model<Buffer>,
12615 completion: Completion,
12616 push_to_history: bool,
12617 cx: &mut ViewContext<Editor>,
12618 ) -> Task<Result<Option<language::Transaction>>>;
12619
12620 fn is_completion_trigger(
12621 &self,
12622 buffer: &Model<Buffer>,
12623 position: language::Anchor,
12624 text: &str,
12625 trigger_in_words: bool,
12626 cx: &mut ViewContext<Editor>,
12627 ) -> bool;
12628
12629 fn sort_completions(&self) -> bool {
12630 true
12631 }
12632}
12633
12634pub trait CodeActionProvider {
12635 fn code_actions(
12636 &self,
12637 buffer: &Model<Buffer>,
12638 range: Range<text::Anchor>,
12639 cx: &mut WindowContext,
12640 ) -> Task<Result<Vec<CodeAction>>>;
12641
12642 fn apply_code_action(
12643 &self,
12644 buffer_handle: Model<Buffer>,
12645 action: CodeAction,
12646 excerpt_id: ExcerptId,
12647 push_to_history: bool,
12648 cx: &mut WindowContext,
12649 ) -> Task<Result<ProjectTransaction>>;
12650}
12651
12652impl CodeActionProvider for Model<Project> {
12653 fn code_actions(
12654 &self,
12655 buffer: &Model<Buffer>,
12656 range: Range<text::Anchor>,
12657 cx: &mut WindowContext,
12658 ) -> Task<Result<Vec<CodeAction>>> {
12659 self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
12660 }
12661
12662 fn apply_code_action(
12663 &self,
12664 buffer_handle: Model<Buffer>,
12665 action: CodeAction,
12666 _excerpt_id: ExcerptId,
12667 push_to_history: bool,
12668 cx: &mut WindowContext,
12669 ) -> Task<Result<ProjectTransaction>> {
12670 self.update(cx, |project, cx| {
12671 project.apply_code_action(buffer_handle, action, push_to_history, cx)
12672 })
12673 }
12674}
12675
12676fn snippet_completions(
12677 project: &Project,
12678 buffer: &Model<Buffer>,
12679 buffer_position: text::Anchor,
12680 cx: &mut AppContext,
12681) -> Vec<Completion> {
12682 let language = buffer.read(cx).language_at(buffer_position);
12683 let language_name = language.as_ref().map(|language| language.lsp_id());
12684 let snippet_store = project.snippets().read(cx);
12685 let snippets = snippet_store.snippets_for(language_name, cx);
12686
12687 if snippets.is_empty() {
12688 return vec![];
12689 }
12690 let snapshot = buffer.read(cx).text_snapshot();
12691 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12692
12693 let mut lines = chunks.lines();
12694 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12695 return vec![];
12696 };
12697
12698 let scope = language.map(|language| language.default_scope());
12699 let classifier = CharClassifier::new(scope).for_completion(true);
12700 let mut last_word = line_at
12701 .chars()
12702 .rev()
12703 .take_while(|c| classifier.is_word(*c))
12704 .collect::<String>();
12705 last_word = last_word.chars().rev().collect();
12706 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12707 let to_lsp = |point: &text::Anchor| {
12708 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12709 point_to_lsp(end)
12710 };
12711 let lsp_end = to_lsp(&buffer_position);
12712 snippets
12713 .into_iter()
12714 .filter_map(|snippet| {
12715 let matching_prefix = snippet
12716 .prefix
12717 .iter()
12718 .find(|prefix| prefix.starts_with(&last_word))?;
12719 let start = as_offset - last_word.len();
12720 let start = snapshot.anchor_before(start);
12721 let range = start..buffer_position;
12722 let lsp_start = to_lsp(&start);
12723 let lsp_range = lsp::Range {
12724 start: lsp_start,
12725 end: lsp_end,
12726 };
12727 Some(Completion {
12728 old_range: range,
12729 new_text: snippet.body.clone(),
12730 label: CodeLabel {
12731 text: matching_prefix.clone(),
12732 runs: vec![],
12733 filter_range: 0..matching_prefix.len(),
12734 },
12735 server_id: LanguageServerId(usize::MAX),
12736 documentation: snippet.description.clone().map(Documentation::SingleLine),
12737 lsp_completion: lsp::CompletionItem {
12738 label: snippet.prefix.first().unwrap().clone(),
12739 kind: Some(CompletionItemKind::SNIPPET),
12740 label_details: snippet.description.as_ref().map(|description| {
12741 lsp::CompletionItemLabelDetails {
12742 detail: Some(description.clone()),
12743 description: None,
12744 }
12745 }),
12746 insert_text_format: Some(InsertTextFormat::SNIPPET),
12747 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12748 lsp::InsertReplaceEdit {
12749 new_text: snippet.body.clone(),
12750 insert: lsp_range,
12751 replace: lsp_range,
12752 },
12753 )),
12754 filter_text: Some(snippet.body.clone()),
12755 sort_text: Some(char::MAX.to_string()),
12756 ..Default::default()
12757 },
12758 confirm: None,
12759 })
12760 })
12761 .collect()
12762}
12763
12764impl CompletionProvider for Model<Project> {
12765 fn completions(
12766 &self,
12767 buffer: &Model<Buffer>,
12768 buffer_position: text::Anchor,
12769 options: CompletionContext,
12770 cx: &mut ViewContext<Editor>,
12771 ) -> Task<Result<Vec<Completion>>> {
12772 self.update(cx, |project, cx| {
12773 let snippets = snippet_completions(project, buffer, buffer_position, cx);
12774 let project_completions = project.completions(buffer, buffer_position, options, cx);
12775 cx.background_executor().spawn(async move {
12776 let mut completions = project_completions.await?;
12777 //let snippets = snippets.into_iter().;
12778 completions.extend(snippets);
12779 Ok(completions)
12780 })
12781 })
12782 }
12783
12784 fn resolve_completions(
12785 &self,
12786 buffer: Model<Buffer>,
12787 completion_indices: Vec<usize>,
12788 completions: Arc<RwLock<Box<[Completion]>>>,
12789 cx: &mut ViewContext<Editor>,
12790 ) -> Task<Result<bool>> {
12791 self.update(cx, |project, cx| {
12792 project.resolve_completions(buffer, completion_indices, completions, cx)
12793 })
12794 }
12795
12796 fn apply_additional_edits_for_completion(
12797 &self,
12798 buffer: Model<Buffer>,
12799 completion: Completion,
12800 push_to_history: bool,
12801 cx: &mut ViewContext<Editor>,
12802 ) -> Task<Result<Option<language::Transaction>>> {
12803 self.update(cx, |project, cx| {
12804 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12805 })
12806 }
12807
12808 fn is_completion_trigger(
12809 &self,
12810 buffer: &Model<Buffer>,
12811 position: language::Anchor,
12812 text: &str,
12813 trigger_in_words: bool,
12814 cx: &mut ViewContext<Editor>,
12815 ) -> bool {
12816 if !EditorSettings::get_global(cx).show_completions_on_input {
12817 return false;
12818 }
12819
12820 let mut chars = text.chars();
12821 let char = if let Some(char) = chars.next() {
12822 char
12823 } else {
12824 return false;
12825 };
12826 if chars.next().is_some() {
12827 return false;
12828 }
12829
12830 let buffer = buffer.read(cx);
12831 let classifier = buffer
12832 .snapshot()
12833 .char_classifier_at(position)
12834 .for_completion(true);
12835 if trigger_in_words && classifier.is_word(char) {
12836 return true;
12837 }
12838
12839 buffer
12840 .completion_triggers()
12841 .iter()
12842 .any(|string| string == text)
12843 }
12844}
12845
12846fn inlay_hint_settings(
12847 location: Anchor,
12848 snapshot: &MultiBufferSnapshot,
12849 cx: &mut ViewContext<'_, Editor>,
12850) -> InlayHintSettings {
12851 let file = snapshot.file_at(location);
12852 let language = snapshot.language_at(location);
12853 let settings = all_language_settings(file, cx);
12854 settings
12855 .language(language.map(|l| l.name()).as_ref())
12856 .inlay_hints
12857}
12858
12859fn consume_contiguous_rows(
12860 contiguous_row_selections: &mut Vec<Selection<Point>>,
12861 selection: &Selection<Point>,
12862 display_map: &DisplaySnapshot,
12863 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12864) -> (MultiBufferRow, MultiBufferRow) {
12865 contiguous_row_selections.push(selection.clone());
12866 let start_row = MultiBufferRow(selection.start.row);
12867 let mut end_row = ending_row(selection, display_map);
12868
12869 while let Some(next_selection) = selections.peek() {
12870 if next_selection.start.row <= end_row.0 {
12871 end_row = ending_row(next_selection, display_map);
12872 contiguous_row_selections.push(selections.next().unwrap().clone());
12873 } else {
12874 break;
12875 }
12876 }
12877 (start_row, end_row)
12878}
12879
12880fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12881 if next_selection.end.column > 0 || next_selection.is_empty() {
12882 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12883 } else {
12884 MultiBufferRow(next_selection.end.row)
12885 }
12886}
12887
12888impl EditorSnapshot {
12889 pub fn remote_selections_in_range<'a>(
12890 &'a self,
12891 range: &'a Range<Anchor>,
12892 collaboration_hub: &dyn CollaborationHub,
12893 cx: &'a AppContext,
12894 ) -> impl 'a + Iterator<Item = RemoteSelection> {
12895 let participant_names = collaboration_hub.user_names(cx);
12896 let participant_indices = collaboration_hub.user_participant_indices(cx);
12897 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12898 let collaborators_by_replica_id = collaborators_by_peer_id
12899 .iter()
12900 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12901 .collect::<HashMap<_, _>>();
12902 self.buffer_snapshot
12903 .selections_in_range(range, false)
12904 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12905 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12906 let participant_index = participant_indices.get(&collaborator.user_id).copied();
12907 let user_name = participant_names.get(&collaborator.user_id).cloned();
12908 Some(RemoteSelection {
12909 replica_id,
12910 selection,
12911 cursor_shape,
12912 line_mode,
12913 participant_index,
12914 peer_id: collaborator.peer_id,
12915 user_name,
12916 })
12917 })
12918 }
12919
12920 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12921 self.display_snapshot.buffer_snapshot.language_at(position)
12922 }
12923
12924 pub fn is_focused(&self) -> bool {
12925 self.is_focused
12926 }
12927
12928 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12929 self.placeholder_text.as_ref()
12930 }
12931
12932 pub fn scroll_position(&self) -> gpui::Point<f32> {
12933 self.scroll_anchor.scroll_position(&self.display_snapshot)
12934 }
12935
12936 fn gutter_dimensions(
12937 &self,
12938 font_id: FontId,
12939 font_size: Pixels,
12940 em_width: Pixels,
12941 max_line_number_width: Pixels,
12942 cx: &AppContext,
12943 ) -> GutterDimensions {
12944 if !self.show_gutter {
12945 return GutterDimensions::default();
12946 }
12947 let descent = cx.text_system().descent(font_id, font_size);
12948
12949 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12950 matches!(
12951 ProjectSettings::get_global(cx).git.git_gutter,
12952 Some(GitGutterSetting::TrackedFiles)
12953 )
12954 });
12955 let gutter_settings = EditorSettings::get_global(cx).gutter;
12956 let show_line_numbers = self
12957 .show_line_numbers
12958 .unwrap_or(gutter_settings.line_numbers);
12959 let line_gutter_width = if show_line_numbers {
12960 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12961 let min_width_for_number_on_gutter = em_width * 4.0;
12962 max_line_number_width.max(min_width_for_number_on_gutter)
12963 } else {
12964 0.0.into()
12965 };
12966
12967 let show_code_actions = self
12968 .show_code_actions
12969 .unwrap_or(gutter_settings.code_actions);
12970
12971 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12972
12973 let git_blame_entries_width = self
12974 .render_git_blame_gutter
12975 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12976
12977 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12978 left_padding += if show_code_actions || show_runnables {
12979 em_width * 3.0
12980 } else if show_git_gutter && show_line_numbers {
12981 em_width * 2.0
12982 } else if show_git_gutter || show_line_numbers {
12983 em_width
12984 } else {
12985 px(0.)
12986 };
12987
12988 let right_padding = if gutter_settings.folds && show_line_numbers {
12989 em_width * 4.0
12990 } else if gutter_settings.folds {
12991 em_width * 3.0
12992 } else if show_line_numbers {
12993 em_width
12994 } else {
12995 px(0.)
12996 };
12997
12998 GutterDimensions {
12999 left_padding,
13000 right_padding,
13001 width: line_gutter_width + left_padding + right_padding,
13002 margin: -descent,
13003 git_blame_entries_width,
13004 }
13005 }
13006
13007 pub fn render_fold_toggle(
13008 &self,
13009 buffer_row: MultiBufferRow,
13010 row_contains_cursor: bool,
13011 editor: View<Editor>,
13012 cx: &mut WindowContext,
13013 ) -> Option<AnyElement> {
13014 let folded = self.is_line_folded(buffer_row);
13015
13016 if let Some(crease) = self
13017 .crease_snapshot
13018 .query_row(buffer_row, &self.buffer_snapshot)
13019 {
13020 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13021 if folded {
13022 editor.update(cx, |editor, cx| {
13023 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13024 });
13025 } else {
13026 editor.update(cx, |editor, cx| {
13027 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13028 });
13029 }
13030 });
13031
13032 Some((crease.render_toggle)(
13033 buffer_row,
13034 folded,
13035 toggle_callback,
13036 cx,
13037 ))
13038 } else if folded
13039 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
13040 {
13041 Some(
13042 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
13043 .selected(folded)
13044 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13045 if folded {
13046 this.unfold_at(&UnfoldAt { buffer_row }, cx);
13047 } else {
13048 this.fold_at(&FoldAt { buffer_row }, cx);
13049 }
13050 }))
13051 .into_any_element(),
13052 )
13053 } else {
13054 None
13055 }
13056 }
13057
13058 pub fn render_crease_trailer(
13059 &self,
13060 buffer_row: MultiBufferRow,
13061 cx: &mut WindowContext,
13062 ) -> Option<AnyElement> {
13063 let folded = self.is_line_folded(buffer_row);
13064 let crease = self
13065 .crease_snapshot
13066 .query_row(buffer_row, &self.buffer_snapshot)?;
13067 Some((crease.render_trailer)(buffer_row, folded, cx))
13068 }
13069}
13070
13071impl Deref for EditorSnapshot {
13072 type Target = DisplaySnapshot;
13073
13074 fn deref(&self) -> &Self::Target {
13075 &self.display_snapshot
13076 }
13077}
13078
13079#[derive(Clone, Debug, PartialEq, Eq)]
13080pub enum EditorEvent {
13081 InputIgnored {
13082 text: Arc<str>,
13083 },
13084 InputHandled {
13085 utf16_range_to_replace: Option<Range<isize>>,
13086 text: Arc<str>,
13087 },
13088 ExcerptsAdded {
13089 buffer: Model<Buffer>,
13090 predecessor: ExcerptId,
13091 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13092 },
13093 ExcerptsRemoved {
13094 ids: Vec<ExcerptId>,
13095 },
13096 ExcerptsEdited {
13097 ids: Vec<ExcerptId>,
13098 },
13099 ExcerptsExpanded {
13100 ids: Vec<ExcerptId>,
13101 },
13102 BufferEdited,
13103 Edited {
13104 transaction_id: clock::Lamport,
13105 },
13106 Reparsed(BufferId),
13107 Focused,
13108 FocusedIn,
13109 Blurred,
13110 DirtyChanged,
13111 Saved,
13112 TitleChanged,
13113 DiffBaseChanged,
13114 SelectionsChanged {
13115 local: bool,
13116 },
13117 ScrollPositionChanged {
13118 local: bool,
13119 autoscroll: bool,
13120 },
13121 Closed,
13122 TransactionUndone {
13123 transaction_id: clock::Lamport,
13124 },
13125 TransactionBegun {
13126 transaction_id: clock::Lamport,
13127 },
13128}
13129
13130impl EventEmitter<EditorEvent> for Editor {}
13131
13132impl FocusableView for Editor {
13133 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13134 self.focus_handle.clone()
13135 }
13136}
13137
13138impl Render for Editor {
13139 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13140 let settings = ThemeSettings::get_global(cx);
13141
13142 let text_style = match self.mode {
13143 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13144 color: cx.theme().colors().editor_foreground,
13145 font_family: settings.ui_font.family.clone(),
13146 font_features: settings.ui_font.features.clone(),
13147 font_fallbacks: settings.ui_font.fallbacks.clone(),
13148 font_size: rems(0.875).into(),
13149 font_weight: settings.ui_font.weight,
13150 line_height: relative(settings.buffer_line_height.value()),
13151 ..Default::default()
13152 },
13153 EditorMode::Full => TextStyle {
13154 color: cx.theme().colors().editor_foreground,
13155 font_family: settings.buffer_font.family.clone(),
13156 font_features: settings.buffer_font.features.clone(),
13157 font_fallbacks: settings.buffer_font.fallbacks.clone(),
13158 font_size: settings.buffer_font_size(cx).into(),
13159 font_weight: settings.buffer_font.weight,
13160 line_height: relative(settings.buffer_line_height.value()),
13161 ..Default::default()
13162 },
13163 };
13164
13165 let background = match self.mode {
13166 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13167 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13168 EditorMode::Full => cx.theme().colors().editor_background,
13169 };
13170
13171 EditorElement::new(
13172 cx.view(),
13173 EditorStyle {
13174 background,
13175 local_player: cx.theme().players().local(),
13176 text: text_style,
13177 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13178 syntax: cx.theme().syntax().clone(),
13179 status: cx.theme().status().clone(),
13180 inlay_hints_style: make_inlay_hints_style(cx),
13181 suggestions_style: HighlightStyle {
13182 color: Some(cx.theme().status().predictive),
13183 ..HighlightStyle::default()
13184 },
13185 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13186 },
13187 )
13188 }
13189}
13190
13191impl ViewInputHandler for Editor {
13192 fn text_for_range(
13193 &mut self,
13194 range_utf16: Range<usize>,
13195 cx: &mut ViewContext<Self>,
13196 ) -> Option<String> {
13197 Some(
13198 self.buffer
13199 .read(cx)
13200 .read(cx)
13201 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13202 .collect(),
13203 )
13204 }
13205
13206 fn selected_text_range(
13207 &mut self,
13208 ignore_disabled_input: bool,
13209 cx: &mut ViewContext<Self>,
13210 ) -> Option<UTF16Selection> {
13211 // Prevent the IME menu from appearing when holding down an alphabetic key
13212 // while input is disabled.
13213 if !ignore_disabled_input && !self.input_enabled {
13214 return None;
13215 }
13216
13217 let selection = self.selections.newest::<OffsetUtf16>(cx);
13218 let range = selection.range();
13219
13220 Some(UTF16Selection {
13221 range: range.start.0..range.end.0,
13222 reversed: selection.reversed,
13223 })
13224 }
13225
13226 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13227 let snapshot = self.buffer.read(cx).read(cx);
13228 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13229 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13230 }
13231
13232 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13233 self.clear_highlights::<InputComposition>(cx);
13234 self.ime_transaction.take();
13235 }
13236
13237 fn replace_text_in_range(
13238 &mut self,
13239 range_utf16: Option<Range<usize>>,
13240 text: &str,
13241 cx: &mut ViewContext<Self>,
13242 ) {
13243 if !self.input_enabled {
13244 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13245 return;
13246 }
13247
13248 self.transact(cx, |this, cx| {
13249 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13250 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13251 Some(this.selection_replacement_ranges(range_utf16, cx))
13252 } else {
13253 this.marked_text_ranges(cx)
13254 };
13255
13256 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13257 let newest_selection_id = this.selections.newest_anchor().id;
13258 this.selections
13259 .all::<OffsetUtf16>(cx)
13260 .iter()
13261 .zip(ranges_to_replace.iter())
13262 .find_map(|(selection, range)| {
13263 if selection.id == newest_selection_id {
13264 Some(
13265 (range.start.0 as isize - selection.head().0 as isize)
13266 ..(range.end.0 as isize - selection.head().0 as isize),
13267 )
13268 } else {
13269 None
13270 }
13271 })
13272 });
13273
13274 cx.emit(EditorEvent::InputHandled {
13275 utf16_range_to_replace: range_to_replace,
13276 text: text.into(),
13277 });
13278
13279 if let Some(new_selected_ranges) = new_selected_ranges {
13280 this.change_selections(None, cx, |selections| {
13281 selections.select_ranges(new_selected_ranges)
13282 });
13283 this.backspace(&Default::default(), cx);
13284 }
13285
13286 this.handle_input(text, cx);
13287 });
13288
13289 if let Some(transaction) = self.ime_transaction {
13290 self.buffer.update(cx, |buffer, cx| {
13291 buffer.group_until_transaction(transaction, cx);
13292 });
13293 }
13294
13295 self.unmark_text(cx);
13296 }
13297
13298 fn replace_and_mark_text_in_range(
13299 &mut self,
13300 range_utf16: Option<Range<usize>>,
13301 text: &str,
13302 new_selected_range_utf16: Option<Range<usize>>,
13303 cx: &mut ViewContext<Self>,
13304 ) {
13305 if !self.input_enabled {
13306 return;
13307 }
13308
13309 let transaction = self.transact(cx, |this, cx| {
13310 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13311 let snapshot = this.buffer.read(cx).read(cx);
13312 if let Some(relative_range_utf16) = range_utf16.as_ref() {
13313 for marked_range in &mut marked_ranges {
13314 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13315 marked_range.start.0 += relative_range_utf16.start;
13316 marked_range.start =
13317 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13318 marked_range.end =
13319 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13320 }
13321 }
13322 Some(marked_ranges)
13323 } else if let Some(range_utf16) = range_utf16 {
13324 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13325 Some(this.selection_replacement_ranges(range_utf16, cx))
13326 } else {
13327 None
13328 };
13329
13330 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13331 let newest_selection_id = this.selections.newest_anchor().id;
13332 this.selections
13333 .all::<OffsetUtf16>(cx)
13334 .iter()
13335 .zip(ranges_to_replace.iter())
13336 .find_map(|(selection, range)| {
13337 if selection.id == newest_selection_id {
13338 Some(
13339 (range.start.0 as isize - selection.head().0 as isize)
13340 ..(range.end.0 as isize - selection.head().0 as isize),
13341 )
13342 } else {
13343 None
13344 }
13345 })
13346 });
13347
13348 cx.emit(EditorEvent::InputHandled {
13349 utf16_range_to_replace: range_to_replace,
13350 text: text.into(),
13351 });
13352
13353 if let Some(ranges) = ranges_to_replace {
13354 this.change_selections(None, cx, |s| s.select_ranges(ranges));
13355 }
13356
13357 let marked_ranges = {
13358 let snapshot = this.buffer.read(cx).read(cx);
13359 this.selections
13360 .disjoint_anchors()
13361 .iter()
13362 .map(|selection| {
13363 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13364 })
13365 .collect::<Vec<_>>()
13366 };
13367
13368 if text.is_empty() {
13369 this.unmark_text(cx);
13370 } else {
13371 this.highlight_text::<InputComposition>(
13372 marked_ranges.clone(),
13373 HighlightStyle {
13374 underline: Some(UnderlineStyle {
13375 thickness: px(1.),
13376 color: None,
13377 wavy: false,
13378 }),
13379 ..Default::default()
13380 },
13381 cx,
13382 );
13383 }
13384
13385 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13386 let use_autoclose = this.use_autoclose;
13387 let use_auto_surround = this.use_auto_surround;
13388 this.set_use_autoclose(false);
13389 this.set_use_auto_surround(false);
13390 this.handle_input(text, cx);
13391 this.set_use_autoclose(use_autoclose);
13392 this.set_use_auto_surround(use_auto_surround);
13393
13394 if let Some(new_selected_range) = new_selected_range_utf16 {
13395 let snapshot = this.buffer.read(cx).read(cx);
13396 let new_selected_ranges = marked_ranges
13397 .into_iter()
13398 .map(|marked_range| {
13399 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13400 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13401 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13402 snapshot.clip_offset_utf16(new_start, Bias::Left)
13403 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13404 })
13405 .collect::<Vec<_>>();
13406
13407 drop(snapshot);
13408 this.change_selections(None, cx, |selections| {
13409 selections.select_ranges(new_selected_ranges)
13410 });
13411 }
13412 });
13413
13414 self.ime_transaction = self.ime_transaction.or(transaction);
13415 if let Some(transaction) = self.ime_transaction {
13416 self.buffer.update(cx, |buffer, cx| {
13417 buffer.group_until_transaction(transaction, cx);
13418 });
13419 }
13420
13421 if self.text_highlights::<InputComposition>(cx).is_none() {
13422 self.ime_transaction.take();
13423 }
13424 }
13425
13426 fn bounds_for_range(
13427 &mut self,
13428 range_utf16: Range<usize>,
13429 element_bounds: gpui::Bounds<Pixels>,
13430 cx: &mut ViewContext<Self>,
13431 ) -> Option<gpui::Bounds<Pixels>> {
13432 let text_layout_details = self.text_layout_details(cx);
13433 let style = &text_layout_details.editor_style;
13434 let font_id = cx.text_system().resolve_font(&style.text.font());
13435 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13436 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13437
13438 let em_width = cx
13439 .text_system()
13440 .typographic_bounds(font_id, font_size, 'm')
13441 .unwrap()
13442 .size
13443 .width;
13444
13445 let snapshot = self.snapshot(cx);
13446 let scroll_position = snapshot.scroll_position();
13447 let scroll_left = scroll_position.x * em_width;
13448
13449 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13450 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13451 + self.gutter_dimensions.width;
13452 let y = line_height * (start.row().as_f32() - scroll_position.y);
13453
13454 Some(Bounds {
13455 origin: element_bounds.origin + point(x, y),
13456 size: size(em_width, line_height),
13457 })
13458 }
13459}
13460
13461trait SelectionExt {
13462 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13463 fn spanned_rows(
13464 &self,
13465 include_end_if_at_line_start: bool,
13466 map: &DisplaySnapshot,
13467 ) -> Range<MultiBufferRow>;
13468}
13469
13470impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
13471 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
13472 let start = self
13473 .start
13474 .to_point(&map.buffer_snapshot)
13475 .to_display_point(map);
13476 let end = self
13477 .end
13478 .to_point(&map.buffer_snapshot)
13479 .to_display_point(map);
13480 if self.reversed {
13481 end..start
13482 } else {
13483 start..end
13484 }
13485 }
13486
13487 fn spanned_rows(
13488 &self,
13489 include_end_if_at_line_start: bool,
13490 map: &DisplaySnapshot,
13491 ) -> Range<MultiBufferRow> {
13492 let start = self.start.to_point(&map.buffer_snapshot);
13493 let mut end = self.end.to_point(&map.buffer_snapshot);
13494 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
13495 end.row -= 1;
13496 }
13497
13498 let buffer_start = map.prev_line_boundary(start).0;
13499 let buffer_end = map.next_line_boundary(end).0;
13500 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
13501 }
13502}
13503
13504impl<T: InvalidationRegion> InvalidationStack<T> {
13505 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
13506 where
13507 S: Clone + ToOffset,
13508 {
13509 while let Some(region) = self.last() {
13510 let all_selections_inside_invalidation_ranges =
13511 if selections.len() == region.ranges().len() {
13512 selections
13513 .iter()
13514 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
13515 .all(|(selection, invalidation_range)| {
13516 let head = selection.head().to_offset(buffer);
13517 invalidation_range.start <= head && invalidation_range.end >= head
13518 })
13519 } else {
13520 false
13521 };
13522
13523 if all_selections_inside_invalidation_ranges {
13524 break;
13525 } else {
13526 self.pop();
13527 }
13528 }
13529 }
13530}
13531
13532impl<T> Default for InvalidationStack<T> {
13533 fn default() -> Self {
13534 Self(Default::default())
13535 }
13536}
13537
13538impl<T> Deref for InvalidationStack<T> {
13539 type Target = Vec<T>;
13540
13541 fn deref(&self) -> &Self::Target {
13542 &self.0
13543 }
13544}
13545
13546impl<T> DerefMut for InvalidationStack<T> {
13547 fn deref_mut(&mut self) -> &mut Self::Target {
13548 &mut self.0
13549 }
13550}
13551
13552impl InvalidationRegion for SnippetState {
13553 fn ranges(&self) -> &[Range<Anchor>] {
13554 &self.ranges[self.active_index]
13555 }
13556}
13557
13558pub fn diagnostic_block_renderer(
13559 diagnostic: Diagnostic,
13560 max_message_rows: Option<u8>,
13561 allow_closing: bool,
13562 _is_valid: bool,
13563) -> RenderBlock {
13564 let (text_without_backticks, code_ranges) =
13565 highlight_diagnostic_message(&diagnostic, max_message_rows);
13566
13567 Box::new(move |cx: &mut BlockContext| {
13568 let group_id: SharedString = cx.block_id.to_string().into();
13569
13570 let mut text_style = cx.text_style().clone();
13571 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13572 let theme_settings = ThemeSettings::get_global(cx);
13573 text_style.font_family = theme_settings.buffer_font.family.clone();
13574 text_style.font_style = theme_settings.buffer_font.style;
13575 text_style.font_features = theme_settings.buffer_font.features.clone();
13576 text_style.font_weight = theme_settings.buffer_font.weight;
13577
13578 let multi_line_diagnostic = diagnostic.message.contains('\n');
13579
13580 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13581 if multi_line_diagnostic {
13582 v_flex()
13583 } else {
13584 h_flex()
13585 }
13586 .when(allow_closing, |div| {
13587 div.children(diagnostic.is_primary.then(|| {
13588 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13589 .icon_color(Color::Muted)
13590 .size(ButtonSize::Compact)
13591 .style(ButtonStyle::Transparent)
13592 .visible_on_hover(group_id.clone())
13593 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13594 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13595 }))
13596 })
13597 .child(
13598 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13599 .icon_color(Color::Muted)
13600 .size(ButtonSize::Compact)
13601 .style(ButtonStyle::Transparent)
13602 .visible_on_hover(group_id.clone())
13603 .on_click({
13604 let message = diagnostic.message.clone();
13605 move |_click, cx| {
13606 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13607 }
13608 })
13609 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13610 )
13611 };
13612
13613 let icon_size = buttons(&diagnostic, cx.block_id)
13614 .into_any_element()
13615 .layout_as_root(AvailableSpace::min_size(), cx);
13616
13617 h_flex()
13618 .id(cx.block_id)
13619 .group(group_id.clone())
13620 .relative()
13621 .size_full()
13622 .pl(cx.gutter_dimensions.width)
13623 .w(cx.max_width + cx.gutter_dimensions.width)
13624 .child(
13625 div()
13626 .flex()
13627 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13628 .flex_shrink(),
13629 )
13630 .child(buttons(&diagnostic, cx.block_id))
13631 .child(div().flex().flex_shrink_0().child(
13632 StyledText::new(text_without_backticks.clone()).with_highlights(
13633 &text_style,
13634 code_ranges.iter().map(|range| {
13635 (
13636 range.clone(),
13637 HighlightStyle {
13638 font_weight: Some(FontWeight::BOLD),
13639 ..Default::default()
13640 },
13641 )
13642 }),
13643 ),
13644 ))
13645 .into_any_element()
13646 })
13647}
13648
13649pub fn highlight_diagnostic_message(
13650 diagnostic: &Diagnostic,
13651 mut max_message_rows: Option<u8>,
13652) -> (SharedString, Vec<Range<usize>>) {
13653 let mut text_without_backticks = String::new();
13654 let mut code_ranges = Vec::new();
13655
13656 if let Some(source) = &diagnostic.source {
13657 text_without_backticks.push_str(source);
13658 code_ranges.push(0..source.len());
13659 text_without_backticks.push_str(": ");
13660 }
13661
13662 let mut prev_offset = 0;
13663 let mut in_code_block = false;
13664 let has_row_limit = max_message_rows.is_some();
13665 let mut newline_indices = diagnostic
13666 .message
13667 .match_indices('\n')
13668 .filter(|_| has_row_limit)
13669 .map(|(ix, _)| ix)
13670 .fuse()
13671 .peekable();
13672
13673 for (quote_ix, _) in diagnostic
13674 .message
13675 .match_indices('`')
13676 .chain([(diagnostic.message.len(), "")])
13677 {
13678 let mut first_newline_ix = None;
13679 let mut last_newline_ix = None;
13680 while let Some(newline_ix) = newline_indices.peek() {
13681 if *newline_ix < quote_ix {
13682 if first_newline_ix.is_none() {
13683 first_newline_ix = Some(*newline_ix);
13684 }
13685 last_newline_ix = Some(*newline_ix);
13686
13687 if let Some(rows_left) = &mut max_message_rows {
13688 if *rows_left == 0 {
13689 break;
13690 } else {
13691 *rows_left -= 1;
13692 }
13693 }
13694 let _ = newline_indices.next();
13695 } else {
13696 break;
13697 }
13698 }
13699 let prev_len = text_without_backticks.len();
13700 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
13701 text_without_backticks.push_str(new_text);
13702 if in_code_block {
13703 code_ranges.push(prev_len..text_without_backticks.len());
13704 }
13705 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13706 in_code_block = !in_code_block;
13707 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13708 text_without_backticks.push_str("...");
13709 break;
13710 }
13711 }
13712
13713 (text_without_backticks.into(), code_ranges)
13714}
13715
13716fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13717 match severity {
13718 DiagnosticSeverity::ERROR => colors.error,
13719 DiagnosticSeverity::WARNING => colors.warning,
13720 DiagnosticSeverity::INFORMATION => colors.info,
13721 DiagnosticSeverity::HINT => colors.info,
13722 _ => colors.ignored,
13723 }
13724}
13725
13726pub fn styled_runs_for_code_label<'a>(
13727 label: &'a CodeLabel,
13728 syntax_theme: &'a theme::SyntaxTheme,
13729) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13730 let fade_out = HighlightStyle {
13731 fade_out: Some(0.35),
13732 ..Default::default()
13733 };
13734
13735 let mut prev_end = label.filter_range.end;
13736 label
13737 .runs
13738 .iter()
13739 .enumerate()
13740 .flat_map(move |(ix, (range, highlight_id))| {
13741 let style = if let Some(style) = highlight_id.style(syntax_theme) {
13742 style
13743 } else {
13744 return Default::default();
13745 };
13746 let mut muted_style = style;
13747 muted_style.highlight(fade_out);
13748
13749 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13750 if range.start >= label.filter_range.end {
13751 if range.start > prev_end {
13752 runs.push((prev_end..range.start, fade_out));
13753 }
13754 runs.push((range.clone(), muted_style));
13755 } else if range.end <= label.filter_range.end {
13756 runs.push((range.clone(), style));
13757 } else {
13758 runs.push((range.start..label.filter_range.end, style));
13759 runs.push((label.filter_range.end..range.end, muted_style));
13760 }
13761 prev_end = cmp::max(prev_end, range.end);
13762
13763 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13764 runs.push((prev_end..label.text.len(), fade_out));
13765 }
13766
13767 runs
13768 })
13769}
13770
13771pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13772 let mut prev_index = 0;
13773 let mut prev_codepoint: Option<char> = None;
13774 text.char_indices()
13775 .chain([(text.len(), '\0')])
13776 .filter_map(move |(index, codepoint)| {
13777 let prev_codepoint = prev_codepoint.replace(codepoint)?;
13778 let is_boundary = index == text.len()
13779 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13780 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13781 if is_boundary {
13782 let chunk = &text[prev_index..index];
13783 prev_index = index;
13784 Some(chunk)
13785 } else {
13786 None
13787 }
13788 })
13789}
13790
13791pub trait RangeToAnchorExt: Sized {
13792 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13793
13794 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13795 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13796 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
13797 }
13798}
13799
13800impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13801 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13802 let start_offset = self.start.to_offset(snapshot);
13803 let end_offset = self.end.to_offset(snapshot);
13804 if start_offset == end_offset {
13805 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13806 } else {
13807 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13808 }
13809 }
13810}
13811
13812pub trait RowExt {
13813 fn as_f32(&self) -> f32;
13814
13815 fn next_row(&self) -> Self;
13816
13817 fn previous_row(&self) -> Self;
13818
13819 fn minus(&self, other: Self) -> u32;
13820}
13821
13822impl RowExt for DisplayRow {
13823 fn as_f32(&self) -> f32 {
13824 self.0 as f32
13825 }
13826
13827 fn next_row(&self) -> Self {
13828 Self(self.0 + 1)
13829 }
13830
13831 fn previous_row(&self) -> Self {
13832 Self(self.0.saturating_sub(1))
13833 }
13834
13835 fn minus(&self, other: Self) -> u32 {
13836 self.0 - other.0
13837 }
13838}
13839
13840impl RowExt for MultiBufferRow {
13841 fn as_f32(&self) -> f32 {
13842 self.0 as f32
13843 }
13844
13845 fn next_row(&self) -> Self {
13846 Self(self.0 + 1)
13847 }
13848
13849 fn previous_row(&self) -> Self {
13850 Self(self.0.saturating_sub(1))
13851 }
13852
13853 fn minus(&self, other: Self) -> u32 {
13854 self.0 - other.0
13855 }
13856}
13857
13858trait RowRangeExt {
13859 type Row;
13860
13861 fn len(&self) -> usize;
13862
13863 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13864}
13865
13866impl RowRangeExt for Range<MultiBufferRow> {
13867 type Row = MultiBufferRow;
13868
13869 fn len(&self) -> usize {
13870 (self.end.0 - self.start.0) as usize
13871 }
13872
13873 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13874 (self.start.0..self.end.0).map(MultiBufferRow)
13875 }
13876}
13877
13878impl RowRangeExt for Range<DisplayRow> {
13879 type Row = DisplayRow;
13880
13881 fn len(&self) -> usize {
13882 (self.end.0 - self.start.0) as usize
13883 }
13884
13885 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13886 (self.start.0..self.end.0).map(DisplayRow)
13887 }
13888}
13889
13890fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
13891 if hunk.diff_base_byte_range.is_empty() {
13892 DiffHunkStatus::Added
13893 } else if hunk.row_range.is_empty() {
13894 DiffHunkStatus::Removed
13895 } else {
13896 DiffHunkStatus::Modified
13897 }
13898}
13899
13900/// If select range has more than one line, we
13901/// just point the cursor to range.start.
13902fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
13903 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
13904 range
13905 } else {
13906 range.start..range.start
13907 }
13908}