1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blame_entry_tooltip;
17mod blink_manager;
18mod clangd_ext;
19mod debounced_delay;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod hunk_diff;
29mod indent_guides;
30mod inlay_hint_cache;
31mod inline_completion_provider;
32pub mod items;
33mod linked_editing_ranges;
34mod lsp_ext;
35mod mouse_context_menu;
36pub mod movement;
37mod persistence;
38mod rust_analyzer_ext;
39pub mod scroll;
40mod selections_collection;
41pub mod tasks;
42
43#[cfg(test)]
44mod editor_tests;
45mod signature_help;
46#[cfg(any(test, feature = "test-support"))]
47pub mod test;
48
49use ::git::diff::{DiffHunk, DiffHunkStatus};
50use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
51pub(crate) use actions::*;
52use aho_corasick::AhoCorasick;
53use anyhow::{anyhow, Context as _, Result};
54use blink_manager::BlinkManager;
55use client::{Collaborator, ParticipantIndex};
56use clock::ReplicaId;
57use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
58use convert_case::{Case, Casing};
59use debounced_delay::DebouncedDelay;
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{
63 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings,
64};
65pub use editor_settings_controls::*;
66use element::LineWithInvisibles;
67pub use element::{
68 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
69};
70use futures::FutureExt;
71use fuzzy::{StringMatch, StringMatchCandidate};
72use git::blame::GitBlame;
73use git::diff_hunk_to_display;
74use gpui::{
75 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
76 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
77 ClipboardItem, Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle,
78 FocusOutEvent, FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText,
79 KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
80 SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
81 UTF16Selection, UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler,
82 VisualContext, WeakFocusHandle, WeakView, WindowContext,
83};
84use highlight_matching_bracket::refresh_matching_bracket_highlights;
85use hover_popover::{hide_hover, HoverState};
86use hunk_diff::ExpandedHunks;
87pub(crate) use hunk_diff::HoveredHunk;
88use indent_guides::ActiveIndentGuidesState;
89use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
90pub use inline_completion_provider::*;
91pub use items::MAX_TAB_TITLE_LEN;
92use itertools::Itertools;
93use language::{
94 language_settings::{self, all_language_settings, InlayHintSettings},
95 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
96 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
97 Point, Selection, SelectionGoal, TransactionId,
98};
99use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
100use linked_editing_ranges::refresh_linked_ranges;
101use task::{ResolvedTask, TaskTemplate, TaskVariables};
102
103use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
104pub use lsp::CompletionContext;
105use lsp::{
106 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
107 LanguageServerId,
108};
109use mouse_context_menu::MouseContextMenu;
110use movement::TextLayoutDetails;
111pub use multi_buffer::{
112 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
113 ToPoint,
114};
115use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
116use ordered_float::OrderedFloat;
117use parking_lot::{Mutex, RwLock};
118use project::project_settings::{GitGutterSetting, ProjectSettings};
119use project::{
120 CodeAction, Completion, CompletionIntent, FormatTrigger, Item, Location, Project, ProjectPath,
121 ProjectTransaction, TaskSourceKind,
122};
123use rand::prelude::*;
124use rpc::{proto::*, ErrorExt};
125use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
126use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
127use serde::{Deserialize, Serialize};
128use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
129use smallvec::SmallVec;
130use snippet::Snippet;
131use std::{
132 any::TypeId,
133 borrow::Cow,
134 cell::RefCell,
135 cmp::{self, Ordering, Reverse},
136 mem,
137 num::NonZeroU32,
138 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
139 path::{Path, PathBuf},
140 rc::Rc,
141 sync::Arc,
142 time::{Duration, Instant},
143};
144pub use sum_tree::Bias;
145use sum_tree::TreeMap;
146use text::{BufferId, OffsetUtf16, Rope};
147use theme::{
148 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
149 ThemeColors, ThemeSettings,
150};
151use ui::{
152 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
153 ListItem, Popover, Tooltip,
154};
155use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
156use workspace::item::{ItemHandle, PreviewTabsSettings};
157use workspace::notifications::{DetachAndPromptErr, NotificationId};
158use workspace::{
159 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
160};
161use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
162
163use crate::hover_links::find_url;
164use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
165
166pub const FILE_HEADER_HEIGHT: u32 = 1;
167pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
168pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
169pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
170const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
171const MAX_LINE_LEN: usize = 1024;
172const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
173const MAX_SELECTION_HISTORY_LEN: usize = 1024;
174pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
175#[doc(hidden)]
176pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
177#[doc(hidden)]
178pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
179
180pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
181pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
182
183pub fn render_parsed_markdown(
184 element_id: impl Into<ElementId>,
185 parsed: &language::ParsedMarkdown,
186 editor_style: &EditorStyle,
187 workspace: Option<WeakView<Workspace>>,
188 cx: &mut WindowContext,
189) -> InteractiveText {
190 let code_span_background_color = cx
191 .theme()
192 .colors()
193 .editor_document_highlight_read_background;
194
195 let highlights = gpui::combine_highlights(
196 parsed.highlights.iter().filter_map(|(range, highlight)| {
197 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
198 Some((range.clone(), highlight))
199 }),
200 parsed
201 .regions
202 .iter()
203 .zip(&parsed.region_ranges)
204 .filter_map(|(region, range)| {
205 if region.code {
206 Some((
207 range.clone(),
208 HighlightStyle {
209 background_color: Some(code_span_background_color),
210 ..Default::default()
211 },
212 ))
213 } else {
214 None
215 }
216 }),
217 );
218
219 let mut links = Vec::new();
220 let mut link_ranges = Vec::new();
221 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
222 if let Some(link) = region.link.clone() {
223 links.push(link);
224 link_ranges.push(range.clone());
225 }
226 }
227
228 InteractiveText::new(
229 element_id,
230 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
231 )
232 .on_click(link_ranges, move |clicked_range_ix, cx| {
233 match &links[clicked_range_ix] {
234 markdown::Link::Web { url } => cx.open_url(url),
235 markdown::Link::Path { path } => {
236 if let Some(workspace) = &workspace {
237 _ = workspace.update(cx, |workspace, cx| {
238 workspace.open_abs_path(path.clone(), false, cx).detach();
239 });
240 }
241 }
242 }
243 })
244}
245
246#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
247pub(crate) enum InlayId {
248 Suggestion(usize),
249 Hint(usize),
250}
251
252impl InlayId {
253 fn id(&self) -> usize {
254 match self {
255 Self::Suggestion(id) => *id,
256 Self::Hint(id) => *id,
257 }
258 }
259}
260
261enum DiffRowHighlight {}
262enum DocumentHighlightRead {}
263enum DocumentHighlightWrite {}
264enum InputComposition {}
265
266#[derive(Copy, Clone, PartialEq, Eq)]
267pub enum Direction {
268 Prev,
269 Next,
270}
271
272#[derive(Debug, Copy, Clone, PartialEq, Eq)]
273pub enum Navigated {
274 Yes,
275 No,
276}
277
278impl Navigated {
279 pub fn from_bool(yes: bool) -> Navigated {
280 if yes {
281 Navigated::Yes
282 } else {
283 Navigated::No
284 }
285 }
286}
287
288pub fn init_settings(cx: &mut AppContext) {
289 EditorSettings::register(cx);
290}
291
292pub fn init(cx: &mut AppContext) {
293 init_settings(cx);
294
295 workspace::register_project_item::<Editor>(cx);
296 workspace::FollowableViewRegistry::register::<Editor>(cx);
297 workspace::register_serializable_item::<Editor>(cx);
298
299 cx.observe_new_views(
300 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
301 workspace.register_action(Editor::new_file);
302 workspace.register_action(Editor::new_file_vertical);
303 workspace.register_action(Editor::new_file_horizontal);
304 },
305 )
306 .detach();
307
308 cx.on_action(move |_: &workspace::NewFile, cx| {
309 let app_state = workspace::AppState::global(cx);
310 if let Some(app_state) = app_state.upgrade() {
311 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
312 Editor::new_file(workspace, &Default::default(), cx)
313 })
314 .detach();
315 }
316 });
317 cx.on_action(move |_: &workspace::NewWindow, cx| {
318 let app_state = workspace::AppState::global(cx);
319 if let Some(app_state) = app_state.upgrade() {
320 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
321 Editor::new_file(workspace, &Default::default(), cx)
322 })
323 .detach();
324 }
325 });
326}
327
328pub struct SearchWithinRange;
329
330trait InvalidationRegion {
331 fn ranges(&self) -> &[Range<Anchor>];
332}
333
334#[derive(Clone, Debug, PartialEq)]
335pub enum SelectPhase {
336 Begin {
337 position: DisplayPoint,
338 add: bool,
339 click_count: usize,
340 },
341 BeginColumnar {
342 position: DisplayPoint,
343 reset: bool,
344 goal_column: u32,
345 },
346 Extend {
347 position: DisplayPoint,
348 click_count: usize,
349 },
350 Update {
351 position: DisplayPoint,
352 goal_column: u32,
353 scroll_delta: gpui::Point<f32>,
354 },
355 End,
356}
357
358#[derive(Clone, Debug)]
359pub enum SelectMode {
360 Character,
361 Word(Range<Anchor>),
362 Line(Range<Anchor>),
363 All,
364}
365
366#[derive(Copy, Clone, PartialEq, Eq, Debug)]
367pub enum EditorMode {
368 SingleLine { auto_width: bool },
369 AutoHeight { max_lines: usize },
370 Full,
371}
372
373#[derive(Clone, Debug)]
374pub enum SoftWrap {
375 None,
376 PreferLine,
377 EditorWidth,
378 Column(u32),
379 Bounded(u32),
380}
381
382#[derive(Clone)]
383pub struct EditorStyle {
384 pub background: Hsla,
385 pub local_player: PlayerColor,
386 pub text: TextStyle,
387 pub scrollbar_width: Pixels,
388 pub syntax: Arc<SyntaxTheme>,
389 pub status: StatusColors,
390 pub inlay_hints_style: HighlightStyle,
391 pub suggestions_style: HighlightStyle,
392 pub unnecessary_code_fade: f32,
393}
394
395impl Default for EditorStyle {
396 fn default() -> Self {
397 Self {
398 background: Hsla::default(),
399 local_player: PlayerColor::default(),
400 text: TextStyle::default(),
401 scrollbar_width: Pixels::default(),
402 syntax: Default::default(),
403 // HACK: Status colors don't have a real default.
404 // We should look into removing the status colors from the editor
405 // style and retrieve them directly from the theme.
406 status: StatusColors::dark(),
407 inlay_hints_style: HighlightStyle::default(),
408 suggestions_style: HighlightStyle::default(),
409 unnecessary_code_fade: Default::default(),
410 }
411 }
412}
413
414type CompletionId = usize;
415
416#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
417struct EditorActionId(usize);
418
419impl EditorActionId {
420 pub fn post_inc(&mut self) -> Self {
421 let answer = self.0;
422
423 *self = Self(answer + 1);
424
425 Self(answer)
426 }
427}
428
429// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
430// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
431
432type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
433type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
434
435#[derive(Default)]
436struct ScrollbarMarkerState {
437 scrollbar_size: Size<Pixels>,
438 dirty: bool,
439 markers: Arc<[PaintQuad]>,
440 pending_refresh: Option<Task<Result<()>>>,
441}
442
443impl ScrollbarMarkerState {
444 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
445 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
446 }
447}
448
449#[derive(Clone, Debug)]
450struct RunnableTasks {
451 templates: Vec<(TaskSourceKind, TaskTemplate)>,
452 offset: MultiBufferOffset,
453 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
454 column: u32,
455 // Values of all named captures, including those starting with '_'
456 extra_variables: HashMap<String, String>,
457 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
458 context_range: Range<BufferOffset>,
459}
460
461#[derive(Clone)]
462struct ResolvedTasks {
463 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
464 position: Anchor,
465}
466#[derive(Copy, Clone, Debug)]
467struct MultiBufferOffset(usize);
468#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
469struct BufferOffset(usize);
470
471// Addons allow storing per-editor state in other crates (e.g. Vim)
472pub trait Addon: 'static {
473 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
474
475 fn to_any(&self) -> &dyn std::any::Any;
476}
477
478/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
479///
480/// See the [module level documentation](self) for more information.
481pub struct Editor {
482 focus_handle: FocusHandle,
483 last_focused_descendant: Option<WeakFocusHandle>,
484 /// The text buffer being edited
485 buffer: Model<MultiBuffer>,
486 /// Map of how text in the buffer should be displayed.
487 /// Handles soft wraps, folds, fake inlay text insertions, etc.
488 pub display_map: Model<DisplayMap>,
489 pub selections: SelectionsCollection,
490 pub scroll_manager: ScrollManager,
491 /// When inline assist editors are linked, they all render cursors because
492 /// typing enters text into each of them, even the ones that aren't focused.
493 pub(crate) show_cursor_when_unfocused: bool,
494 columnar_selection_tail: Option<Anchor>,
495 add_selections_state: Option<AddSelectionsState>,
496 select_next_state: Option<SelectNextState>,
497 select_prev_state: Option<SelectNextState>,
498 selection_history: SelectionHistory,
499 autoclose_regions: Vec<AutocloseRegion>,
500 snippet_stack: InvalidationStack<SnippetState>,
501 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
502 ime_transaction: Option<TransactionId>,
503 active_diagnostics: Option<ActiveDiagnosticGroup>,
504 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
505 project: Option<Model<Project>>,
506 completion_provider: Option<Box<dyn CompletionProvider>>,
507 collaboration_hub: Option<Box<dyn CollaborationHub>>,
508 blink_manager: Model<BlinkManager>,
509 show_cursor_names: bool,
510 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
511 pub show_local_selections: bool,
512 mode: EditorMode,
513 show_breadcrumbs: bool,
514 show_gutter: bool,
515 show_line_numbers: Option<bool>,
516 use_relative_line_numbers: Option<bool>,
517 show_git_diff_gutter: Option<bool>,
518 show_code_actions: Option<bool>,
519 show_runnables: Option<bool>,
520 show_wrap_guides: Option<bool>,
521 show_indent_guides: Option<bool>,
522 placeholder_text: Option<Arc<str>>,
523 highlight_order: usize,
524 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
525 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
526 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
527 scrollbar_marker_state: ScrollbarMarkerState,
528 active_indent_guides_state: ActiveIndentGuidesState,
529 nav_history: Option<ItemNavHistory>,
530 context_menu: RwLock<Option<ContextMenu>>,
531 mouse_context_menu: Option<MouseContextMenu>,
532 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
533 signature_help_state: SignatureHelpState,
534 auto_signature_help: Option<bool>,
535 find_all_references_task_sources: Vec<Anchor>,
536 next_completion_id: CompletionId,
537 completion_documentation_pre_resolve_debounce: DebouncedDelay,
538 available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
539 code_actions_task: Option<Task<()>>,
540 document_highlights_task: Option<Task<()>>,
541 linked_editing_range_task: Option<Task<Option<()>>>,
542 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
543 pending_rename: Option<RenameState>,
544 searchable: bool,
545 cursor_shape: CursorShape,
546 current_line_highlight: Option<CurrentLineHighlight>,
547 collapse_matches: bool,
548 autoindent_mode: Option<AutoindentMode>,
549 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
550 input_enabled: bool,
551 use_modal_editing: bool,
552 read_only: bool,
553 leader_peer_id: Option<PeerId>,
554 remote_id: Option<ViewId>,
555 hover_state: HoverState,
556 gutter_hovered: bool,
557 hovered_link_state: Option<HoveredLinkState>,
558 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
559 active_inline_completion: Option<(Inlay, Option<Range<Anchor>>)>,
560 // enable_inline_completions is a switch that Vim can use to disable
561 // inline completions based on its mode.
562 enable_inline_completions: bool,
563 show_inline_completions_override: Option<bool>,
564 inlay_hint_cache: InlayHintCache,
565 expanded_hunks: ExpandedHunks,
566 next_inlay_id: usize,
567 _subscriptions: Vec<Subscription>,
568 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
569 gutter_dimensions: GutterDimensions,
570 style: Option<EditorStyle>,
571 next_editor_action_id: EditorActionId,
572 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
573 use_autoclose: bool,
574 use_auto_surround: bool,
575 auto_replace_emoji_shortcode: bool,
576 show_git_blame_gutter: bool,
577 show_git_blame_inline: bool,
578 show_git_blame_inline_delay_task: Option<Task<()>>,
579 git_blame_inline_enabled: bool,
580 serialize_dirty_buffers: bool,
581 show_selection_menu: Option<bool>,
582 blame: Option<Model<GitBlame>>,
583 blame_subscription: Option<Subscription>,
584 custom_context_menu: Option<
585 Box<
586 dyn 'static
587 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
588 >,
589 >,
590 last_bounds: Option<Bounds<Pixels>>,
591 expect_bounds_change: Option<Bounds<Pixels>>,
592 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
593 tasks_update_task: Option<Task<()>>,
594 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
595 file_header_size: u32,
596 breadcrumb_header: Option<String>,
597 focused_block: Option<FocusedBlock>,
598 next_scroll_position: NextScrollCursorCenterTopBottom,
599 addons: HashMap<TypeId, Box<dyn Addon>>,
600 _scroll_cursor_center_top_bottom_task: Task<()>,
601}
602
603#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
604enum NextScrollCursorCenterTopBottom {
605 #[default]
606 Center,
607 Top,
608 Bottom,
609}
610
611impl NextScrollCursorCenterTopBottom {
612 fn next(&self) -> Self {
613 match self {
614 Self::Center => Self::Top,
615 Self::Top => Self::Bottom,
616 Self::Bottom => Self::Center,
617 }
618 }
619}
620
621#[derive(Clone)]
622pub struct EditorSnapshot {
623 pub mode: EditorMode,
624 show_gutter: bool,
625 show_line_numbers: Option<bool>,
626 show_git_diff_gutter: Option<bool>,
627 show_code_actions: Option<bool>,
628 show_runnables: Option<bool>,
629 render_git_blame_gutter: bool,
630 pub display_snapshot: DisplaySnapshot,
631 pub placeholder_text: Option<Arc<str>>,
632 is_focused: bool,
633 scroll_anchor: ScrollAnchor,
634 ongoing_scroll: OngoingScroll,
635 current_line_highlight: CurrentLineHighlight,
636 gutter_hovered: bool,
637}
638
639const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
640
641#[derive(Default, Debug, Clone, Copy)]
642pub struct GutterDimensions {
643 pub left_padding: Pixels,
644 pub right_padding: Pixels,
645 pub width: Pixels,
646 pub margin: Pixels,
647 pub git_blame_entries_width: Option<Pixels>,
648}
649
650impl GutterDimensions {
651 /// The full width of the space taken up by the gutter.
652 pub fn full_width(&self) -> Pixels {
653 self.margin + self.width
654 }
655
656 /// The width of the space reserved for the fold indicators,
657 /// use alongside 'justify_end' and `gutter_width` to
658 /// right align content with the line numbers
659 pub fn fold_area_width(&self) -> Pixels {
660 self.margin + self.right_padding
661 }
662}
663
664#[derive(Debug)]
665pub struct RemoteSelection {
666 pub replica_id: ReplicaId,
667 pub selection: Selection<Anchor>,
668 pub cursor_shape: CursorShape,
669 pub peer_id: PeerId,
670 pub line_mode: bool,
671 pub participant_index: Option<ParticipantIndex>,
672 pub user_name: Option<SharedString>,
673}
674
675#[derive(Clone, Debug)]
676struct SelectionHistoryEntry {
677 selections: Arc<[Selection<Anchor>]>,
678 select_next_state: Option<SelectNextState>,
679 select_prev_state: Option<SelectNextState>,
680 add_selections_state: Option<AddSelectionsState>,
681}
682
683enum SelectionHistoryMode {
684 Normal,
685 Undoing,
686 Redoing,
687}
688
689#[derive(Clone, PartialEq, Eq, Hash)]
690struct HoveredCursor {
691 replica_id: u16,
692 selection_id: usize,
693}
694
695impl Default for SelectionHistoryMode {
696 fn default() -> Self {
697 Self::Normal
698 }
699}
700
701#[derive(Default)]
702struct SelectionHistory {
703 #[allow(clippy::type_complexity)]
704 selections_by_transaction:
705 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
706 mode: SelectionHistoryMode,
707 undo_stack: VecDeque<SelectionHistoryEntry>,
708 redo_stack: VecDeque<SelectionHistoryEntry>,
709}
710
711impl SelectionHistory {
712 fn insert_transaction(
713 &mut self,
714 transaction_id: TransactionId,
715 selections: Arc<[Selection<Anchor>]>,
716 ) {
717 self.selections_by_transaction
718 .insert(transaction_id, (selections, None));
719 }
720
721 #[allow(clippy::type_complexity)]
722 fn transaction(
723 &self,
724 transaction_id: TransactionId,
725 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
726 self.selections_by_transaction.get(&transaction_id)
727 }
728
729 #[allow(clippy::type_complexity)]
730 fn transaction_mut(
731 &mut self,
732 transaction_id: TransactionId,
733 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
734 self.selections_by_transaction.get_mut(&transaction_id)
735 }
736
737 fn push(&mut self, entry: SelectionHistoryEntry) {
738 if !entry.selections.is_empty() {
739 match self.mode {
740 SelectionHistoryMode::Normal => {
741 self.push_undo(entry);
742 self.redo_stack.clear();
743 }
744 SelectionHistoryMode::Undoing => self.push_redo(entry),
745 SelectionHistoryMode::Redoing => self.push_undo(entry),
746 }
747 }
748 }
749
750 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
751 if self
752 .undo_stack
753 .back()
754 .map_or(true, |e| e.selections != entry.selections)
755 {
756 self.undo_stack.push_back(entry);
757 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
758 self.undo_stack.pop_front();
759 }
760 }
761 }
762
763 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
764 if self
765 .redo_stack
766 .back()
767 .map_or(true, |e| e.selections != entry.selections)
768 {
769 self.redo_stack.push_back(entry);
770 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
771 self.redo_stack.pop_front();
772 }
773 }
774 }
775}
776
777struct RowHighlight {
778 index: usize,
779 range: RangeInclusive<Anchor>,
780 color: Option<Hsla>,
781 should_autoscroll: bool,
782}
783
784#[derive(Clone, Debug)]
785struct AddSelectionsState {
786 above: bool,
787 stack: Vec<usize>,
788}
789
790#[derive(Clone)]
791struct SelectNextState {
792 query: AhoCorasick,
793 wordwise: bool,
794 done: bool,
795}
796
797impl std::fmt::Debug for SelectNextState {
798 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
799 f.debug_struct(std::any::type_name::<Self>())
800 .field("wordwise", &self.wordwise)
801 .field("done", &self.done)
802 .finish()
803 }
804}
805
806#[derive(Debug)]
807struct AutocloseRegion {
808 selection_id: usize,
809 range: Range<Anchor>,
810 pair: BracketPair,
811}
812
813#[derive(Debug)]
814struct SnippetState {
815 ranges: Vec<Vec<Range<Anchor>>>,
816 active_index: usize,
817}
818
819#[doc(hidden)]
820pub struct RenameState {
821 pub range: Range<Anchor>,
822 pub old_name: Arc<str>,
823 pub editor: View<Editor>,
824 block_id: CustomBlockId,
825}
826
827struct InvalidationStack<T>(Vec<T>);
828
829struct RegisteredInlineCompletionProvider {
830 provider: Arc<dyn InlineCompletionProviderHandle>,
831 _subscription: Subscription,
832}
833
834enum ContextMenu {
835 Completions(CompletionsMenu),
836 CodeActions(CodeActionsMenu),
837}
838
839impl ContextMenu {
840 fn select_first(
841 &mut self,
842 project: Option<&Model<Project>>,
843 cx: &mut ViewContext<Editor>,
844 ) -> bool {
845 if self.visible() {
846 match self {
847 ContextMenu::Completions(menu) => menu.select_first(project, cx),
848 ContextMenu::CodeActions(menu) => menu.select_first(cx),
849 }
850 true
851 } else {
852 false
853 }
854 }
855
856 fn select_prev(
857 &mut self,
858 project: Option<&Model<Project>>,
859 cx: &mut ViewContext<Editor>,
860 ) -> bool {
861 if self.visible() {
862 match self {
863 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
864 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
865 }
866 true
867 } else {
868 false
869 }
870 }
871
872 fn select_next(
873 &mut self,
874 project: Option<&Model<Project>>,
875 cx: &mut ViewContext<Editor>,
876 ) -> bool {
877 if self.visible() {
878 match self {
879 ContextMenu::Completions(menu) => menu.select_next(project, cx),
880 ContextMenu::CodeActions(menu) => menu.select_next(cx),
881 }
882 true
883 } else {
884 false
885 }
886 }
887
888 fn select_last(
889 &mut self,
890 project: Option<&Model<Project>>,
891 cx: &mut ViewContext<Editor>,
892 ) -> bool {
893 if self.visible() {
894 match self {
895 ContextMenu::Completions(menu) => menu.select_last(project, cx),
896 ContextMenu::CodeActions(menu) => menu.select_last(cx),
897 }
898 true
899 } else {
900 false
901 }
902 }
903
904 fn visible(&self) -> bool {
905 match self {
906 ContextMenu::Completions(menu) => menu.visible(),
907 ContextMenu::CodeActions(menu) => menu.visible(),
908 }
909 }
910
911 fn render(
912 &self,
913 cursor_position: DisplayPoint,
914 style: &EditorStyle,
915 max_height: Pixels,
916 workspace: Option<WeakView<Workspace>>,
917 cx: &mut ViewContext<Editor>,
918 ) -> (ContextMenuOrigin, AnyElement) {
919 match self {
920 ContextMenu::Completions(menu) => (
921 ContextMenuOrigin::EditorPoint(cursor_position),
922 menu.render(style, max_height, workspace, cx),
923 ),
924 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
925 }
926 }
927}
928
929enum ContextMenuOrigin {
930 EditorPoint(DisplayPoint),
931 GutterIndicator(DisplayRow),
932}
933
934#[derive(Clone)]
935struct CompletionsMenu {
936 id: CompletionId,
937 sort_completions: bool,
938 initial_position: Anchor,
939 buffer: Model<Buffer>,
940 completions: Arc<RwLock<Box<[Completion]>>>,
941 match_candidates: Arc<[StringMatchCandidate]>,
942 matches: Arc<[StringMatch]>,
943 selected_item: usize,
944 scroll_handle: UniformListScrollHandle,
945 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
946}
947
948impl CompletionsMenu {
949 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
950 self.selected_item = 0;
951 self.scroll_handle.scroll_to_item(self.selected_item);
952 self.attempt_resolve_selected_completion_documentation(project, cx);
953 cx.notify();
954 }
955
956 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
957 if self.selected_item > 0 {
958 self.selected_item -= 1;
959 } else {
960 self.selected_item = self.matches.len() - 1;
961 }
962 self.scroll_handle.scroll_to_item(self.selected_item);
963 self.attempt_resolve_selected_completion_documentation(project, cx);
964 cx.notify();
965 }
966
967 fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
968 if self.selected_item + 1 < self.matches.len() {
969 self.selected_item += 1;
970 } else {
971 self.selected_item = 0;
972 }
973 self.scroll_handle.scroll_to_item(self.selected_item);
974 self.attempt_resolve_selected_completion_documentation(project, cx);
975 cx.notify();
976 }
977
978 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
979 self.selected_item = self.matches.len() - 1;
980 self.scroll_handle.scroll_to_item(self.selected_item);
981 self.attempt_resolve_selected_completion_documentation(project, cx);
982 cx.notify();
983 }
984
985 fn pre_resolve_completion_documentation(
986 buffer: Model<Buffer>,
987 completions: Arc<RwLock<Box<[Completion]>>>,
988 matches: Arc<[StringMatch]>,
989 editor: &Editor,
990 cx: &mut ViewContext<Editor>,
991 ) -> Task<()> {
992 let settings = EditorSettings::get_global(cx);
993 if !settings.show_completion_documentation {
994 return Task::ready(());
995 }
996
997 let Some(provider) = editor.completion_provider.as_ref() else {
998 return Task::ready(());
999 };
1000
1001 let resolve_task = provider.resolve_completions(
1002 buffer,
1003 matches.iter().map(|m| m.candidate_id).collect(),
1004 completions.clone(),
1005 cx,
1006 );
1007
1008 cx.spawn(move |this, mut cx| async move {
1009 if let Some(true) = resolve_task.await.log_err() {
1010 this.update(&mut cx, |_, cx| cx.notify()).ok();
1011 }
1012 })
1013 }
1014
1015 fn attempt_resolve_selected_completion_documentation(
1016 &mut self,
1017 project: Option<&Model<Project>>,
1018 cx: &mut ViewContext<Editor>,
1019 ) {
1020 let settings = EditorSettings::get_global(cx);
1021 if !settings.show_completion_documentation {
1022 return;
1023 }
1024
1025 let completion_index = self.matches[self.selected_item].candidate_id;
1026 let Some(project) = project else {
1027 return;
1028 };
1029
1030 let resolve_task = project.update(cx, |project, cx| {
1031 project.resolve_completions(
1032 self.buffer.clone(),
1033 vec![completion_index],
1034 self.completions.clone(),
1035 cx,
1036 )
1037 });
1038
1039 let delay_ms =
1040 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1041 let delay = Duration::from_millis(delay_ms);
1042
1043 self.selected_completion_documentation_resolve_debounce
1044 .lock()
1045 .fire_new(delay, cx, |_, cx| {
1046 cx.spawn(move |this, mut cx| async move {
1047 if let Some(true) = resolve_task.await.log_err() {
1048 this.update(&mut cx, |_, cx| cx.notify()).ok();
1049 }
1050 })
1051 });
1052 }
1053
1054 fn visible(&self) -> bool {
1055 !self.matches.is_empty()
1056 }
1057
1058 fn render(
1059 &self,
1060 style: &EditorStyle,
1061 max_height: Pixels,
1062 workspace: Option<WeakView<Workspace>>,
1063 cx: &mut ViewContext<Editor>,
1064 ) -> AnyElement {
1065 let settings = EditorSettings::get_global(cx);
1066 let show_completion_documentation = settings.show_completion_documentation;
1067
1068 let widest_completion_ix = self
1069 .matches
1070 .iter()
1071 .enumerate()
1072 .max_by_key(|(_, mat)| {
1073 let completions = self.completions.read();
1074 let completion = &completions[mat.candidate_id];
1075 let documentation = &completion.documentation;
1076
1077 let mut len = completion.label.text.chars().count();
1078 if let Some(Documentation::SingleLine(text)) = documentation {
1079 if show_completion_documentation {
1080 len += text.chars().count();
1081 }
1082 }
1083
1084 len
1085 })
1086 .map(|(ix, _)| ix);
1087
1088 let completions = self.completions.clone();
1089 let matches = self.matches.clone();
1090 let selected_item = self.selected_item;
1091 let style = style.clone();
1092
1093 let multiline_docs = if show_completion_documentation {
1094 let mat = &self.matches[selected_item];
1095 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1096 Some(Documentation::MultiLinePlainText(text)) => {
1097 Some(div().child(SharedString::from(text.clone())))
1098 }
1099 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1100 Some(div().child(render_parsed_markdown(
1101 "completions_markdown",
1102 parsed,
1103 &style,
1104 workspace,
1105 cx,
1106 )))
1107 }
1108 _ => None,
1109 };
1110 multiline_docs.map(|div| {
1111 div.id("multiline_docs")
1112 .max_h(max_height)
1113 .flex_1()
1114 .px_1p5()
1115 .py_1()
1116 .min_w(px(260.))
1117 .max_w(px(640.))
1118 .w(px(500.))
1119 .overflow_y_scroll()
1120 .occlude()
1121 })
1122 } else {
1123 None
1124 };
1125
1126 let list = uniform_list(
1127 cx.view().clone(),
1128 "completions",
1129 matches.len(),
1130 move |_editor, range, cx| {
1131 let start_ix = range.start;
1132 let completions_guard = completions.read();
1133
1134 matches[range]
1135 .iter()
1136 .enumerate()
1137 .map(|(ix, mat)| {
1138 let item_ix = start_ix + ix;
1139 let candidate_id = mat.candidate_id;
1140 let completion = &completions_guard[candidate_id];
1141
1142 let documentation = if show_completion_documentation {
1143 &completion.documentation
1144 } else {
1145 &None
1146 };
1147
1148 let highlights = gpui::combine_highlights(
1149 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1150 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1151 |(range, mut highlight)| {
1152 // Ignore font weight for syntax highlighting, as we'll use it
1153 // for fuzzy matches.
1154 highlight.font_weight = None;
1155
1156 if completion.lsp_completion.deprecated.unwrap_or(false) {
1157 highlight.strikethrough = Some(StrikethroughStyle {
1158 thickness: 1.0.into(),
1159 ..Default::default()
1160 });
1161 highlight.color = Some(cx.theme().colors().text_muted);
1162 }
1163
1164 (range, highlight)
1165 },
1166 ),
1167 );
1168 let completion_label = StyledText::new(completion.label.text.clone())
1169 .with_highlights(&style.text, highlights);
1170 let documentation_label =
1171 if let Some(Documentation::SingleLine(text)) = documentation {
1172 if text.trim().is_empty() {
1173 None
1174 } else {
1175 Some(
1176 Label::new(text.clone())
1177 .ml_4()
1178 .size(LabelSize::Small)
1179 .color(Color::Muted),
1180 )
1181 }
1182 } else {
1183 None
1184 };
1185
1186 div().min_w(px(220.)).max_w(px(540.)).child(
1187 ListItem::new(mat.candidate_id)
1188 .inset(true)
1189 .selected(item_ix == selected_item)
1190 .on_click(cx.listener(move |editor, _event, cx| {
1191 cx.stop_propagation();
1192 if let Some(task) = editor.confirm_completion(
1193 &ConfirmCompletion {
1194 item_ix: Some(item_ix),
1195 },
1196 cx,
1197 ) {
1198 task.detach_and_log_err(cx)
1199 }
1200 }))
1201 .child(h_flex().overflow_hidden().child(completion_label))
1202 .end_slot::<Label>(documentation_label),
1203 )
1204 })
1205 .collect()
1206 },
1207 )
1208 .occlude()
1209 .max_h(max_height)
1210 .track_scroll(self.scroll_handle.clone())
1211 .with_width_from_item(widest_completion_ix)
1212 .with_sizing_behavior(ListSizingBehavior::Infer);
1213
1214 Popover::new()
1215 .child(list)
1216 .when_some(multiline_docs, |popover, multiline_docs| {
1217 popover.aside(multiline_docs)
1218 })
1219 .into_any_element()
1220 }
1221
1222 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1223 let mut matches = if let Some(query) = query {
1224 fuzzy::match_strings(
1225 &self.match_candidates,
1226 query,
1227 query.chars().any(|c| c.is_uppercase()),
1228 100,
1229 &Default::default(),
1230 executor,
1231 )
1232 .await
1233 } else {
1234 self.match_candidates
1235 .iter()
1236 .enumerate()
1237 .map(|(candidate_id, candidate)| StringMatch {
1238 candidate_id,
1239 score: Default::default(),
1240 positions: Default::default(),
1241 string: candidate.string.clone(),
1242 })
1243 .collect()
1244 };
1245
1246 // Remove all candidates where the query's start does not match the start of any word in the candidate
1247 if let Some(query) = query {
1248 if let Some(query_start) = query.chars().next() {
1249 matches.retain(|string_match| {
1250 split_words(&string_match.string).any(|word| {
1251 // Check that the first codepoint of the word as lowercase matches the first
1252 // codepoint of the query as lowercase
1253 word.chars()
1254 .flat_map(|codepoint| codepoint.to_lowercase())
1255 .zip(query_start.to_lowercase())
1256 .all(|(word_cp, query_cp)| word_cp == query_cp)
1257 })
1258 });
1259 }
1260 }
1261
1262 let completions = self.completions.read();
1263 if self.sort_completions {
1264 matches.sort_unstable_by_key(|mat| {
1265 // We do want to strike a balance here between what the language server tells us
1266 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1267 // `Creat` and there is a local variable called `CreateComponent`).
1268 // So what we do is: we bucket all matches into two buckets
1269 // - Strong matches
1270 // - Weak matches
1271 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1272 // and the Weak matches are the rest.
1273 //
1274 // For the strong matches, we sort by the language-servers score first and for the weak
1275 // matches, we prefer our fuzzy finder first.
1276 //
1277 // The thinking behind that: it's useless to take the sort_text the language-server gives
1278 // us into account when it's obviously a bad match.
1279
1280 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1281 enum MatchScore<'a> {
1282 Strong {
1283 sort_text: Option<&'a str>,
1284 score: Reverse<OrderedFloat<f64>>,
1285 sort_key: (usize, &'a str),
1286 },
1287 Weak {
1288 score: Reverse<OrderedFloat<f64>>,
1289 sort_text: Option<&'a str>,
1290 sort_key: (usize, &'a str),
1291 },
1292 }
1293
1294 let completion = &completions[mat.candidate_id];
1295 let sort_key = completion.sort_key();
1296 let sort_text = completion.lsp_completion.sort_text.as_deref();
1297 let score = Reverse(OrderedFloat(mat.score));
1298
1299 if mat.score >= 0.2 {
1300 MatchScore::Strong {
1301 sort_text,
1302 score,
1303 sort_key,
1304 }
1305 } else {
1306 MatchScore::Weak {
1307 score,
1308 sort_text,
1309 sort_key,
1310 }
1311 }
1312 });
1313 }
1314
1315 for mat in &mut matches {
1316 let completion = &completions[mat.candidate_id];
1317 mat.string.clone_from(&completion.label.text);
1318 for position in &mut mat.positions {
1319 *position += completion.label.filter_range.start;
1320 }
1321 }
1322 drop(completions);
1323
1324 self.matches = matches.into();
1325 self.selected_item = 0;
1326 }
1327}
1328
1329#[derive(Clone)]
1330struct CodeActionContents {
1331 tasks: Option<Arc<ResolvedTasks>>,
1332 actions: Option<Arc<[CodeAction]>>,
1333}
1334
1335impl CodeActionContents {
1336 fn len(&self) -> usize {
1337 match (&self.tasks, &self.actions) {
1338 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1339 (Some(tasks), None) => tasks.templates.len(),
1340 (None, Some(actions)) => actions.len(),
1341 (None, None) => 0,
1342 }
1343 }
1344
1345 fn is_empty(&self) -> bool {
1346 match (&self.tasks, &self.actions) {
1347 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1348 (Some(tasks), None) => tasks.templates.is_empty(),
1349 (None, Some(actions)) => actions.is_empty(),
1350 (None, None) => true,
1351 }
1352 }
1353
1354 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1355 self.tasks
1356 .iter()
1357 .flat_map(|tasks| {
1358 tasks
1359 .templates
1360 .iter()
1361 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1362 })
1363 .chain(self.actions.iter().flat_map(|actions| {
1364 actions
1365 .iter()
1366 .map(|action| CodeActionsItem::CodeAction(action.clone()))
1367 }))
1368 }
1369 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1370 match (&self.tasks, &self.actions) {
1371 (Some(tasks), Some(actions)) => {
1372 if index < tasks.templates.len() {
1373 tasks
1374 .templates
1375 .get(index)
1376 .cloned()
1377 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1378 } else {
1379 actions
1380 .get(index - tasks.templates.len())
1381 .cloned()
1382 .map(CodeActionsItem::CodeAction)
1383 }
1384 }
1385 (Some(tasks), None) => tasks
1386 .templates
1387 .get(index)
1388 .cloned()
1389 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1390 (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
1391 (None, None) => None,
1392 }
1393 }
1394}
1395
1396#[allow(clippy::large_enum_variant)]
1397#[derive(Clone)]
1398enum CodeActionsItem {
1399 Task(TaskSourceKind, ResolvedTask),
1400 CodeAction(CodeAction),
1401}
1402
1403impl CodeActionsItem {
1404 fn as_task(&self) -> Option<&ResolvedTask> {
1405 let Self::Task(_, task) = self else {
1406 return None;
1407 };
1408 Some(task)
1409 }
1410 fn as_code_action(&self) -> Option<&CodeAction> {
1411 let Self::CodeAction(action) = self else {
1412 return None;
1413 };
1414 Some(action)
1415 }
1416 fn label(&self) -> String {
1417 match self {
1418 Self::CodeAction(action) => action.lsp_action.title.clone(),
1419 Self::Task(_, task) => task.resolved_label.clone(),
1420 }
1421 }
1422}
1423
1424struct CodeActionsMenu {
1425 actions: CodeActionContents,
1426 buffer: Model<Buffer>,
1427 selected_item: usize,
1428 scroll_handle: UniformListScrollHandle,
1429 deployed_from_indicator: Option<DisplayRow>,
1430}
1431
1432impl CodeActionsMenu {
1433 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1434 self.selected_item = 0;
1435 self.scroll_handle.scroll_to_item(self.selected_item);
1436 cx.notify()
1437 }
1438
1439 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1440 if self.selected_item > 0 {
1441 self.selected_item -= 1;
1442 } else {
1443 self.selected_item = self.actions.len() - 1;
1444 }
1445 self.scroll_handle.scroll_to_item(self.selected_item);
1446 cx.notify();
1447 }
1448
1449 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1450 if self.selected_item + 1 < self.actions.len() {
1451 self.selected_item += 1;
1452 } else {
1453 self.selected_item = 0;
1454 }
1455 self.scroll_handle.scroll_to_item(self.selected_item);
1456 cx.notify();
1457 }
1458
1459 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1460 self.selected_item = self.actions.len() - 1;
1461 self.scroll_handle.scroll_to_item(self.selected_item);
1462 cx.notify()
1463 }
1464
1465 fn visible(&self) -> bool {
1466 !self.actions.is_empty()
1467 }
1468
1469 fn render(
1470 &self,
1471 cursor_position: DisplayPoint,
1472 _style: &EditorStyle,
1473 max_height: Pixels,
1474 cx: &mut ViewContext<Editor>,
1475 ) -> (ContextMenuOrigin, AnyElement) {
1476 let actions = self.actions.clone();
1477 let selected_item = self.selected_item;
1478 let element = uniform_list(
1479 cx.view().clone(),
1480 "code_actions_menu",
1481 self.actions.len(),
1482 move |_this, range, cx| {
1483 actions
1484 .iter()
1485 .skip(range.start)
1486 .take(range.end - range.start)
1487 .enumerate()
1488 .map(|(ix, action)| {
1489 let item_ix = range.start + ix;
1490 let selected = selected_item == item_ix;
1491 let colors = cx.theme().colors();
1492 div()
1493 .px_1()
1494 .rounded_md()
1495 .text_color(colors.text)
1496 .when(selected, |style| {
1497 style
1498 .bg(colors.element_active)
1499 .text_color(colors.text_accent)
1500 })
1501 .hover(|style| {
1502 style
1503 .bg(colors.element_hover)
1504 .text_color(colors.text_accent)
1505 })
1506 .whitespace_nowrap()
1507 .when_some(action.as_code_action(), |this, action| {
1508 this.on_mouse_down(
1509 MouseButton::Left,
1510 cx.listener(move |editor, _, cx| {
1511 cx.stop_propagation();
1512 if let Some(task) = editor.confirm_code_action(
1513 &ConfirmCodeAction {
1514 item_ix: Some(item_ix),
1515 },
1516 cx,
1517 ) {
1518 task.detach_and_log_err(cx)
1519 }
1520 }),
1521 )
1522 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1523 .child(SharedString::from(action.lsp_action.title.clone()))
1524 })
1525 .when_some(action.as_task(), |this, task| {
1526 this.on_mouse_down(
1527 MouseButton::Left,
1528 cx.listener(move |editor, _, cx| {
1529 cx.stop_propagation();
1530 if let Some(task) = editor.confirm_code_action(
1531 &ConfirmCodeAction {
1532 item_ix: Some(item_ix),
1533 },
1534 cx,
1535 ) {
1536 task.detach_and_log_err(cx)
1537 }
1538 }),
1539 )
1540 .child(SharedString::from(task.resolved_label.clone()))
1541 })
1542 })
1543 .collect()
1544 },
1545 )
1546 .elevation_1(cx)
1547 .p_1()
1548 .max_h(max_height)
1549 .occlude()
1550 .track_scroll(self.scroll_handle.clone())
1551 .with_width_from_item(
1552 self.actions
1553 .iter()
1554 .enumerate()
1555 .max_by_key(|(_, action)| match action {
1556 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1557 CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
1558 })
1559 .map(|(ix, _)| ix),
1560 )
1561 .with_sizing_behavior(ListSizingBehavior::Infer)
1562 .into_any_element();
1563
1564 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1565 ContextMenuOrigin::GutterIndicator(row)
1566 } else {
1567 ContextMenuOrigin::EditorPoint(cursor_position)
1568 };
1569
1570 (cursor_position, element)
1571 }
1572}
1573
1574#[derive(Debug)]
1575struct ActiveDiagnosticGroup {
1576 primary_range: Range<Anchor>,
1577 primary_message: String,
1578 group_id: usize,
1579 blocks: HashMap<CustomBlockId, Diagnostic>,
1580 is_valid: bool,
1581}
1582
1583#[derive(Serialize, Deserialize, Clone, Debug)]
1584pub struct ClipboardSelection {
1585 pub len: usize,
1586 pub is_entire_line: bool,
1587 pub first_line_indent: u32,
1588}
1589
1590#[derive(Debug)]
1591pub(crate) struct NavigationData {
1592 cursor_anchor: Anchor,
1593 cursor_position: Point,
1594 scroll_anchor: ScrollAnchor,
1595 scroll_top_row: u32,
1596}
1597
1598#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1599enum GotoDefinitionKind {
1600 Symbol,
1601 Declaration,
1602 Type,
1603 Implementation,
1604}
1605
1606#[derive(Debug, Clone)]
1607enum InlayHintRefreshReason {
1608 Toggle(bool),
1609 SettingsChange(InlayHintSettings),
1610 NewLinesShown,
1611 BufferEdited(HashSet<Arc<Language>>),
1612 RefreshRequested,
1613 ExcerptsRemoved(Vec<ExcerptId>),
1614}
1615
1616impl InlayHintRefreshReason {
1617 fn description(&self) -> &'static str {
1618 match self {
1619 Self::Toggle(_) => "toggle",
1620 Self::SettingsChange(_) => "settings change",
1621 Self::NewLinesShown => "new lines shown",
1622 Self::BufferEdited(_) => "buffer edited",
1623 Self::RefreshRequested => "refresh requested",
1624 Self::ExcerptsRemoved(_) => "excerpts removed",
1625 }
1626 }
1627}
1628
1629pub(crate) struct FocusedBlock {
1630 id: BlockId,
1631 focus_handle: WeakFocusHandle,
1632}
1633
1634impl Editor {
1635 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1636 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1637 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1638 Self::new(
1639 EditorMode::SingleLine { auto_width: false },
1640 buffer,
1641 None,
1642 false,
1643 cx,
1644 )
1645 }
1646
1647 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1648 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1649 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1650 Self::new(EditorMode::Full, buffer, None, false, cx)
1651 }
1652
1653 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1654 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1655 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1656 Self::new(
1657 EditorMode::SingleLine { auto_width: true },
1658 buffer,
1659 None,
1660 false,
1661 cx,
1662 )
1663 }
1664
1665 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1666 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1667 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1668 Self::new(
1669 EditorMode::AutoHeight { max_lines },
1670 buffer,
1671 None,
1672 false,
1673 cx,
1674 )
1675 }
1676
1677 pub fn for_buffer(
1678 buffer: Model<Buffer>,
1679 project: Option<Model<Project>>,
1680 cx: &mut ViewContext<Self>,
1681 ) -> Self {
1682 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1683 Self::new(EditorMode::Full, buffer, project, false, cx)
1684 }
1685
1686 pub fn for_multibuffer(
1687 buffer: Model<MultiBuffer>,
1688 project: Option<Model<Project>>,
1689 show_excerpt_controls: bool,
1690 cx: &mut ViewContext<Self>,
1691 ) -> Self {
1692 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1693 }
1694
1695 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1696 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1697 let mut clone = Self::new(
1698 self.mode,
1699 self.buffer.clone(),
1700 self.project.clone(),
1701 show_excerpt_controls,
1702 cx,
1703 );
1704 self.display_map.update(cx, |display_map, cx| {
1705 let snapshot = display_map.snapshot(cx);
1706 clone.display_map.update(cx, |display_map, cx| {
1707 display_map.set_state(&snapshot, cx);
1708 });
1709 });
1710 clone.selections.clone_state(&self.selections);
1711 clone.scroll_manager.clone_state(&self.scroll_manager);
1712 clone.searchable = self.searchable;
1713 clone
1714 }
1715
1716 pub fn new(
1717 mode: EditorMode,
1718 buffer: Model<MultiBuffer>,
1719 project: Option<Model<Project>>,
1720 show_excerpt_controls: bool,
1721 cx: &mut ViewContext<Self>,
1722 ) -> Self {
1723 let style = cx.text_style();
1724 let font_size = style.font_size.to_pixels(cx.rem_size());
1725 let editor = cx.view().downgrade();
1726 let fold_placeholder = FoldPlaceholder {
1727 constrain_width: true,
1728 render: Arc::new(move |fold_id, fold_range, cx| {
1729 let editor = editor.clone();
1730 div()
1731 .id(fold_id)
1732 .bg(cx.theme().colors().ghost_element_background)
1733 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1734 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1735 .rounded_sm()
1736 .size_full()
1737 .cursor_pointer()
1738 .child("⋯")
1739 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1740 .on_click(move |_, cx| {
1741 editor
1742 .update(cx, |editor, cx| {
1743 editor.unfold_ranges(
1744 [fold_range.start..fold_range.end],
1745 true,
1746 false,
1747 cx,
1748 );
1749 cx.stop_propagation();
1750 })
1751 .ok();
1752 })
1753 .into_any()
1754 }),
1755 merge_adjacent: true,
1756 };
1757 let file_header_size = if show_excerpt_controls { 3 } else { 2 };
1758 let display_map = cx.new_model(|cx| {
1759 DisplayMap::new(
1760 buffer.clone(),
1761 style.font(),
1762 font_size,
1763 None,
1764 show_excerpt_controls,
1765 file_header_size,
1766 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1767 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1768 fold_placeholder,
1769 cx,
1770 )
1771 });
1772
1773 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1774
1775 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1776
1777 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1778 .then(|| language_settings::SoftWrap::PreferLine);
1779
1780 let mut project_subscriptions = Vec::new();
1781 if mode == EditorMode::Full {
1782 if let Some(project) = project.as_ref() {
1783 if buffer.read(cx).is_singleton() {
1784 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1785 cx.emit(EditorEvent::TitleChanged);
1786 }));
1787 }
1788 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1789 if let project::Event::RefreshInlayHints = event {
1790 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1791 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1792 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1793 let focus_handle = editor.focus_handle(cx);
1794 if focus_handle.is_focused(cx) {
1795 let snapshot = buffer.read(cx).snapshot();
1796 for (range, snippet) in snippet_edits {
1797 let editor_range =
1798 language::range_from_lsp(*range).to_offset(&snapshot);
1799 editor
1800 .insert_snippet(&[editor_range], snippet.clone(), cx)
1801 .ok();
1802 }
1803 }
1804 }
1805 }
1806 }));
1807 let task_inventory = project.read(cx).task_inventory().clone();
1808 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1809 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1810 }));
1811 }
1812 }
1813
1814 let inlay_hint_settings = inlay_hint_settings(
1815 selections.newest_anchor().head(),
1816 &buffer.read(cx).snapshot(cx),
1817 cx,
1818 );
1819 let focus_handle = cx.focus_handle();
1820 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1821 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1822 .detach();
1823 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1824 .detach();
1825 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1826
1827 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1828 Some(false)
1829 } else {
1830 None
1831 };
1832
1833 let mut this = Self {
1834 focus_handle,
1835 show_cursor_when_unfocused: false,
1836 last_focused_descendant: None,
1837 buffer: buffer.clone(),
1838 display_map: display_map.clone(),
1839 selections,
1840 scroll_manager: ScrollManager::new(cx),
1841 columnar_selection_tail: None,
1842 add_selections_state: None,
1843 select_next_state: None,
1844 select_prev_state: None,
1845 selection_history: Default::default(),
1846 autoclose_regions: Default::default(),
1847 snippet_stack: Default::default(),
1848 select_larger_syntax_node_stack: Vec::new(),
1849 ime_transaction: Default::default(),
1850 active_diagnostics: None,
1851 soft_wrap_mode_override,
1852 completion_provider: project.clone().map(|project| Box::new(project) as _),
1853 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1854 project,
1855 blink_manager: blink_manager.clone(),
1856 show_local_selections: true,
1857 mode,
1858 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1859 show_gutter: mode == EditorMode::Full,
1860 show_line_numbers: None,
1861 use_relative_line_numbers: None,
1862 show_git_diff_gutter: None,
1863 show_code_actions: None,
1864 show_runnables: None,
1865 show_wrap_guides: None,
1866 show_indent_guides,
1867 placeholder_text: None,
1868 highlight_order: 0,
1869 highlighted_rows: HashMap::default(),
1870 background_highlights: Default::default(),
1871 gutter_highlights: TreeMap::default(),
1872 scrollbar_marker_state: ScrollbarMarkerState::default(),
1873 active_indent_guides_state: ActiveIndentGuidesState::default(),
1874 nav_history: None,
1875 context_menu: RwLock::new(None),
1876 mouse_context_menu: None,
1877 completion_tasks: Default::default(),
1878 signature_help_state: SignatureHelpState::default(),
1879 auto_signature_help: None,
1880 find_all_references_task_sources: Vec::new(),
1881 next_completion_id: 0,
1882 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1883 next_inlay_id: 0,
1884 available_code_actions: Default::default(),
1885 code_actions_task: Default::default(),
1886 document_highlights_task: Default::default(),
1887 linked_editing_range_task: Default::default(),
1888 pending_rename: Default::default(),
1889 searchable: true,
1890 cursor_shape: Default::default(),
1891 current_line_highlight: None,
1892 autoindent_mode: Some(AutoindentMode::EachLine),
1893 collapse_matches: false,
1894 workspace: None,
1895 input_enabled: true,
1896 use_modal_editing: mode == EditorMode::Full,
1897 read_only: false,
1898 use_autoclose: true,
1899 use_auto_surround: true,
1900 auto_replace_emoji_shortcode: false,
1901 leader_peer_id: None,
1902 remote_id: None,
1903 hover_state: Default::default(),
1904 hovered_link_state: Default::default(),
1905 inline_completion_provider: None,
1906 active_inline_completion: None,
1907 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1908 expanded_hunks: ExpandedHunks::default(),
1909 gutter_hovered: false,
1910 pixel_position_of_newest_cursor: None,
1911 last_bounds: None,
1912 expect_bounds_change: None,
1913 gutter_dimensions: GutterDimensions::default(),
1914 style: None,
1915 show_cursor_names: false,
1916 hovered_cursors: Default::default(),
1917 next_editor_action_id: EditorActionId::default(),
1918 editor_actions: Rc::default(),
1919 show_inline_completions_override: None,
1920 enable_inline_completions: true,
1921 custom_context_menu: None,
1922 show_git_blame_gutter: false,
1923 show_git_blame_inline: false,
1924 show_selection_menu: None,
1925 show_git_blame_inline_delay_task: None,
1926 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1927 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1928 .session
1929 .restore_unsaved_buffers,
1930 blame: None,
1931 blame_subscription: None,
1932 file_header_size,
1933 tasks: Default::default(),
1934 _subscriptions: vec![
1935 cx.observe(&buffer, Self::on_buffer_changed),
1936 cx.subscribe(&buffer, Self::on_buffer_event),
1937 cx.observe(&display_map, Self::on_display_map_changed),
1938 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1939 cx.observe_global::<SettingsStore>(Self::settings_changed),
1940 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1941 cx.observe_window_activation(|editor, cx| {
1942 let active = cx.is_window_active();
1943 editor.blink_manager.update(cx, |blink_manager, cx| {
1944 if active {
1945 blink_manager.enable(cx);
1946 } else {
1947 blink_manager.disable(cx);
1948 }
1949 });
1950 }),
1951 ],
1952 tasks_update_task: None,
1953 linked_edit_ranges: Default::default(),
1954 previous_search_ranges: None,
1955 breadcrumb_header: None,
1956 focused_block: None,
1957 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1958 addons: HashMap::default(),
1959 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1960 };
1961 this.tasks_update_task = Some(this.refresh_runnables(cx));
1962 this._subscriptions.extend(project_subscriptions);
1963
1964 this.end_selection(cx);
1965 this.scroll_manager.show_scrollbar(cx);
1966
1967 if mode == EditorMode::Full {
1968 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1969 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1970
1971 if this.git_blame_inline_enabled {
1972 this.git_blame_inline_enabled = true;
1973 this.start_git_blame_inline(false, cx);
1974 }
1975 }
1976
1977 this.report_editor_event("open", None, cx);
1978 this
1979 }
1980
1981 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
1982 self.mouse_context_menu
1983 .as_ref()
1984 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1985 }
1986
1987 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
1988 let mut key_context = KeyContext::new_with_defaults();
1989 key_context.add("Editor");
1990 let mode = match self.mode {
1991 EditorMode::SingleLine { .. } => "single_line",
1992 EditorMode::AutoHeight { .. } => "auto_height",
1993 EditorMode::Full => "full",
1994 };
1995
1996 if EditorSettings::jupyter_enabled(cx) {
1997 key_context.add("jupyter");
1998 }
1999
2000 key_context.set("mode", mode);
2001 if self.pending_rename.is_some() {
2002 key_context.add("renaming");
2003 }
2004 if self.context_menu_visible() {
2005 match self.context_menu.read().as_ref() {
2006 Some(ContextMenu::Completions(_)) => {
2007 key_context.add("menu");
2008 key_context.add("showing_completions")
2009 }
2010 Some(ContextMenu::CodeActions(_)) => {
2011 key_context.add("menu");
2012 key_context.add("showing_code_actions")
2013 }
2014 None => {}
2015 }
2016 }
2017
2018 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2019 if !self.focus_handle(cx).contains_focused(cx)
2020 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2021 {
2022 for addon in self.addons.values() {
2023 addon.extend_key_context(&mut key_context, cx)
2024 }
2025 }
2026
2027 if let Some(extension) = self
2028 .buffer
2029 .read(cx)
2030 .as_singleton()
2031 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2032 {
2033 key_context.set("extension", extension.to_string());
2034 }
2035
2036 if self.has_active_inline_completion(cx) {
2037 key_context.add("copilot_suggestion");
2038 key_context.add("inline_completion");
2039 }
2040
2041 key_context
2042 }
2043
2044 pub fn new_file(
2045 workspace: &mut Workspace,
2046 _: &workspace::NewFile,
2047 cx: &mut ViewContext<Workspace>,
2048 ) {
2049 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2050 "Failed to create buffer",
2051 cx,
2052 |e, _| match e.error_code() {
2053 ErrorCode::RemoteUpgradeRequired => Some(format!(
2054 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2055 e.error_tag("required").unwrap_or("the latest version")
2056 )),
2057 _ => None,
2058 },
2059 );
2060 }
2061
2062 pub fn new_in_workspace(
2063 workspace: &mut Workspace,
2064 cx: &mut ViewContext<Workspace>,
2065 ) -> Task<Result<View<Editor>>> {
2066 let project = workspace.project().clone();
2067 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2068
2069 cx.spawn(|workspace, mut cx| async move {
2070 let buffer = create.await?;
2071 workspace.update(&mut cx, |workspace, cx| {
2072 let editor =
2073 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2074 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2075 editor
2076 })
2077 })
2078 }
2079
2080 fn new_file_vertical(
2081 workspace: &mut Workspace,
2082 _: &workspace::NewFileSplitVertical,
2083 cx: &mut ViewContext<Workspace>,
2084 ) {
2085 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2086 }
2087
2088 fn new_file_horizontal(
2089 workspace: &mut Workspace,
2090 _: &workspace::NewFileSplitHorizontal,
2091 cx: &mut ViewContext<Workspace>,
2092 ) {
2093 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2094 }
2095
2096 fn new_file_in_direction(
2097 workspace: &mut Workspace,
2098 direction: SplitDirection,
2099 cx: &mut ViewContext<Workspace>,
2100 ) {
2101 let project = workspace.project().clone();
2102 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2103
2104 cx.spawn(|workspace, mut cx| async move {
2105 let buffer = create.await?;
2106 workspace.update(&mut cx, move |workspace, cx| {
2107 workspace.split_item(
2108 direction,
2109 Box::new(
2110 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2111 ),
2112 cx,
2113 )
2114 })?;
2115 anyhow::Ok(())
2116 })
2117 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2118 ErrorCode::RemoteUpgradeRequired => Some(format!(
2119 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2120 e.error_tag("required").unwrap_or("the latest version")
2121 )),
2122 _ => None,
2123 });
2124 }
2125
2126 pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
2127 self.buffer.read(cx).replica_id()
2128 }
2129
2130 pub fn leader_peer_id(&self) -> Option<PeerId> {
2131 self.leader_peer_id
2132 }
2133
2134 pub fn buffer(&self) -> &Model<MultiBuffer> {
2135 &self.buffer
2136 }
2137
2138 pub fn workspace(&self) -> Option<View<Workspace>> {
2139 self.workspace.as_ref()?.0.upgrade()
2140 }
2141
2142 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2143 self.buffer().read(cx).title(cx)
2144 }
2145
2146 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2147 EditorSnapshot {
2148 mode: self.mode,
2149 show_gutter: self.show_gutter,
2150 show_line_numbers: self.show_line_numbers,
2151 show_git_diff_gutter: self.show_git_diff_gutter,
2152 show_code_actions: self.show_code_actions,
2153 show_runnables: self.show_runnables,
2154 render_git_blame_gutter: self.render_git_blame_gutter(cx),
2155 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2156 scroll_anchor: self.scroll_manager.anchor(),
2157 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2158 placeholder_text: self.placeholder_text.clone(),
2159 is_focused: self.focus_handle.is_focused(cx),
2160 current_line_highlight: self
2161 .current_line_highlight
2162 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2163 gutter_hovered: self.gutter_hovered,
2164 }
2165 }
2166
2167 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2168 self.buffer.read(cx).language_at(point, cx)
2169 }
2170
2171 pub fn file_at<T: ToOffset>(
2172 &self,
2173 point: T,
2174 cx: &AppContext,
2175 ) -> Option<Arc<dyn language::File>> {
2176 self.buffer.read(cx).read(cx).file_at(point).cloned()
2177 }
2178
2179 pub fn active_excerpt(
2180 &self,
2181 cx: &AppContext,
2182 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2183 self.buffer
2184 .read(cx)
2185 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2186 }
2187
2188 pub fn mode(&self) -> EditorMode {
2189 self.mode
2190 }
2191
2192 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2193 self.collaboration_hub.as_deref()
2194 }
2195
2196 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2197 self.collaboration_hub = Some(hub);
2198 }
2199
2200 pub fn set_custom_context_menu(
2201 &mut self,
2202 f: impl 'static
2203 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2204 ) {
2205 self.custom_context_menu = Some(Box::new(f))
2206 }
2207
2208 pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
2209 self.completion_provider = Some(provider);
2210 }
2211
2212 pub fn set_inline_completion_provider<T>(
2213 &mut self,
2214 provider: Option<Model<T>>,
2215 cx: &mut ViewContext<Self>,
2216 ) where
2217 T: InlineCompletionProvider,
2218 {
2219 self.inline_completion_provider =
2220 provider.map(|provider| RegisteredInlineCompletionProvider {
2221 _subscription: cx.observe(&provider, |this, _, cx| {
2222 if this.focus_handle.is_focused(cx) {
2223 this.update_visible_inline_completion(cx);
2224 }
2225 }),
2226 provider: Arc::new(provider),
2227 });
2228 self.refresh_inline_completion(false, false, cx);
2229 }
2230
2231 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2232 self.placeholder_text.as_deref()
2233 }
2234
2235 pub fn set_placeholder_text(
2236 &mut self,
2237 placeholder_text: impl Into<Arc<str>>,
2238 cx: &mut ViewContext<Self>,
2239 ) {
2240 let placeholder_text = Some(placeholder_text.into());
2241 if self.placeholder_text != placeholder_text {
2242 self.placeholder_text = placeholder_text;
2243 cx.notify();
2244 }
2245 }
2246
2247 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2248 self.cursor_shape = cursor_shape;
2249
2250 // Disrupt blink for immediate user feedback that the cursor shape has changed
2251 self.blink_manager.update(cx, BlinkManager::show_cursor);
2252
2253 cx.notify();
2254 }
2255
2256 pub fn set_current_line_highlight(
2257 &mut self,
2258 current_line_highlight: Option<CurrentLineHighlight>,
2259 ) {
2260 self.current_line_highlight = current_line_highlight;
2261 }
2262
2263 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2264 self.collapse_matches = collapse_matches;
2265 }
2266
2267 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2268 if self.collapse_matches {
2269 return range.start..range.start;
2270 }
2271 range.clone()
2272 }
2273
2274 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2275 if self.display_map.read(cx).clip_at_line_ends != clip {
2276 self.display_map
2277 .update(cx, |map, _| map.clip_at_line_ends = clip);
2278 }
2279 }
2280
2281 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2282 self.input_enabled = input_enabled;
2283 }
2284
2285 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
2286 self.enable_inline_completions = enabled;
2287 }
2288
2289 pub fn set_autoindent(&mut self, autoindent: bool) {
2290 if autoindent {
2291 self.autoindent_mode = Some(AutoindentMode::EachLine);
2292 } else {
2293 self.autoindent_mode = None;
2294 }
2295 }
2296
2297 pub fn read_only(&self, cx: &AppContext) -> bool {
2298 self.read_only || self.buffer.read(cx).read_only()
2299 }
2300
2301 pub fn set_read_only(&mut self, read_only: bool) {
2302 self.read_only = read_only;
2303 }
2304
2305 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2306 self.use_autoclose = autoclose;
2307 }
2308
2309 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2310 self.use_auto_surround = auto_surround;
2311 }
2312
2313 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2314 self.auto_replace_emoji_shortcode = auto_replace;
2315 }
2316
2317 pub fn toggle_inline_completions(
2318 &mut self,
2319 _: &ToggleInlineCompletions,
2320 cx: &mut ViewContext<Self>,
2321 ) {
2322 if self.show_inline_completions_override.is_some() {
2323 self.set_show_inline_completions(None, cx);
2324 } else {
2325 let cursor = self.selections.newest_anchor().head();
2326 if let Some((buffer, cursor_buffer_position)) =
2327 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2328 {
2329 let show_inline_completions =
2330 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2331 self.set_show_inline_completions(Some(show_inline_completions), cx);
2332 }
2333 }
2334 }
2335
2336 pub fn set_show_inline_completions(
2337 &mut self,
2338 show_inline_completions: Option<bool>,
2339 cx: &mut ViewContext<Self>,
2340 ) {
2341 self.show_inline_completions_override = show_inline_completions;
2342 self.refresh_inline_completion(false, true, cx);
2343 }
2344
2345 fn should_show_inline_completions(
2346 &self,
2347 buffer: &Model<Buffer>,
2348 buffer_position: language::Anchor,
2349 cx: &AppContext,
2350 ) -> bool {
2351 if let Some(provider) = self.inline_completion_provider() {
2352 if let Some(show_inline_completions) = self.show_inline_completions_override {
2353 show_inline_completions
2354 } else {
2355 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
2356 }
2357 } else {
2358 false
2359 }
2360 }
2361
2362 pub fn set_use_modal_editing(&mut self, to: bool) {
2363 self.use_modal_editing = to;
2364 }
2365
2366 pub fn use_modal_editing(&self) -> bool {
2367 self.use_modal_editing
2368 }
2369
2370 fn selections_did_change(
2371 &mut self,
2372 local: bool,
2373 old_cursor_position: &Anchor,
2374 show_completions: bool,
2375 cx: &mut ViewContext<Self>,
2376 ) {
2377 cx.invalidate_character_coordinates();
2378
2379 // Copy selections to primary selection buffer
2380 #[cfg(target_os = "linux")]
2381 if local {
2382 let selections = self.selections.all::<usize>(cx);
2383 let buffer_handle = self.buffer.read(cx).read(cx);
2384
2385 let mut text = String::new();
2386 for (index, selection) in selections.iter().enumerate() {
2387 let text_for_selection = buffer_handle
2388 .text_for_range(selection.start..selection.end)
2389 .collect::<String>();
2390
2391 text.push_str(&text_for_selection);
2392 if index != selections.len() - 1 {
2393 text.push('\n');
2394 }
2395 }
2396
2397 if !text.is_empty() {
2398 cx.write_to_primary(ClipboardItem::new_string(text));
2399 }
2400 }
2401
2402 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2403 self.buffer.update(cx, |buffer, cx| {
2404 buffer.set_active_selections(
2405 &self.selections.disjoint_anchors(),
2406 self.selections.line_mode,
2407 self.cursor_shape,
2408 cx,
2409 )
2410 });
2411 }
2412 let display_map = self
2413 .display_map
2414 .update(cx, |display_map, cx| display_map.snapshot(cx));
2415 let buffer = &display_map.buffer_snapshot;
2416 self.add_selections_state = None;
2417 self.select_next_state = None;
2418 self.select_prev_state = None;
2419 self.select_larger_syntax_node_stack.clear();
2420 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2421 self.snippet_stack
2422 .invalidate(&self.selections.disjoint_anchors(), buffer);
2423 self.take_rename(false, cx);
2424
2425 let new_cursor_position = self.selections.newest_anchor().head();
2426
2427 self.push_to_nav_history(
2428 *old_cursor_position,
2429 Some(new_cursor_position.to_point(buffer)),
2430 cx,
2431 );
2432
2433 if local {
2434 let new_cursor_position = self.selections.newest_anchor().head();
2435 let mut context_menu = self.context_menu.write();
2436 let completion_menu = match context_menu.as_ref() {
2437 Some(ContextMenu::Completions(menu)) => Some(menu),
2438
2439 _ => {
2440 *context_menu = None;
2441 None
2442 }
2443 };
2444
2445 if let Some(completion_menu) = completion_menu {
2446 let cursor_position = new_cursor_position.to_offset(buffer);
2447 let (word_range, kind) =
2448 buffer.surrounding_word(completion_menu.initial_position, true);
2449 if kind == Some(CharKind::Word)
2450 && word_range.to_inclusive().contains(&cursor_position)
2451 {
2452 let mut completion_menu = completion_menu.clone();
2453 drop(context_menu);
2454
2455 let query = Self::completion_query(buffer, cursor_position);
2456 cx.spawn(move |this, mut cx| async move {
2457 completion_menu
2458 .filter(query.as_deref(), cx.background_executor().clone())
2459 .await;
2460
2461 this.update(&mut cx, |this, cx| {
2462 let mut context_menu = this.context_menu.write();
2463 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2464 return;
2465 };
2466
2467 if menu.id > completion_menu.id {
2468 return;
2469 }
2470
2471 *context_menu = Some(ContextMenu::Completions(completion_menu));
2472 drop(context_menu);
2473 cx.notify();
2474 })
2475 })
2476 .detach();
2477
2478 if show_completions {
2479 self.show_completions(&ShowCompletions { trigger: None }, cx);
2480 }
2481 } else {
2482 drop(context_menu);
2483 self.hide_context_menu(cx);
2484 }
2485 } else {
2486 drop(context_menu);
2487 }
2488
2489 hide_hover(self, cx);
2490
2491 if old_cursor_position.to_display_point(&display_map).row()
2492 != new_cursor_position.to_display_point(&display_map).row()
2493 {
2494 self.available_code_actions.take();
2495 }
2496 self.refresh_code_actions(cx);
2497 self.refresh_document_highlights(cx);
2498 refresh_matching_bracket_highlights(self, cx);
2499 self.discard_inline_completion(false, cx);
2500 linked_editing_ranges::refresh_linked_ranges(self, cx);
2501 if self.git_blame_inline_enabled {
2502 self.start_inline_blame_timer(cx);
2503 }
2504 }
2505
2506 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2507 cx.emit(EditorEvent::SelectionsChanged { local });
2508
2509 if self.selections.disjoint_anchors().len() == 1 {
2510 cx.emit(SearchEvent::ActiveMatchChanged)
2511 }
2512 cx.notify();
2513 }
2514
2515 pub fn change_selections<R>(
2516 &mut self,
2517 autoscroll: Option<Autoscroll>,
2518 cx: &mut ViewContext<Self>,
2519 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2520 ) -> R {
2521 self.change_selections_inner(autoscroll, true, cx, change)
2522 }
2523
2524 pub fn change_selections_inner<R>(
2525 &mut self,
2526 autoscroll: Option<Autoscroll>,
2527 request_completions: bool,
2528 cx: &mut ViewContext<Self>,
2529 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2530 ) -> R {
2531 let old_cursor_position = self.selections.newest_anchor().head();
2532 self.push_to_selection_history();
2533
2534 let (changed, result) = self.selections.change_with(cx, change);
2535
2536 if changed {
2537 if let Some(autoscroll) = autoscroll {
2538 self.request_autoscroll(autoscroll, cx);
2539 }
2540 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2541
2542 if self.should_open_signature_help_automatically(
2543 &old_cursor_position,
2544 self.signature_help_state.backspace_pressed(),
2545 cx,
2546 ) {
2547 self.show_signature_help(&ShowSignatureHelp, cx);
2548 }
2549 self.signature_help_state.set_backspace_pressed(false);
2550 }
2551
2552 result
2553 }
2554
2555 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2556 where
2557 I: IntoIterator<Item = (Range<S>, T)>,
2558 S: ToOffset,
2559 T: Into<Arc<str>>,
2560 {
2561 if self.read_only(cx) {
2562 return;
2563 }
2564
2565 self.buffer
2566 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2567 }
2568
2569 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2570 where
2571 I: IntoIterator<Item = (Range<S>, T)>,
2572 S: ToOffset,
2573 T: Into<Arc<str>>,
2574 {
2575 if self.read_only(cx) {
2576 return;
2577 }
2578
2579 self.buffer.update(cx, |buffer, cx| {
2580 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2581 });
2582 }
2583
2584 pub fn edit_with_block_indent<I, S, T>(
2585 &mut self,
2586 edits: I,
2587 original_indent_columns: Vec<u32>,
2588 cx: &mut ViewContext<Self>,
2589 ) where
2590 I: IntoIterator<Item = (Range<S>, T)>,
2591 S: ToOffset,
2592 T: Into<Arc<str>>,
2593 {
2594 if self.read_only(cx) {
2595 return;
2596 }
2597
2598 self.buffer.update(cx, |buffer, cx| {
2599 buffer.edit(
2600 edits,
2601 Some(AutoindentMode::Block {
2602 original_indent_columns,
2603 }),
2604 cx,
2605 )
2606 });
2607 }
2608
2609 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2610 self.hide_context_menu(cx);
2611
2612 match phase {
2613 SelectPhase::Begin {
2614 position,
2615 add,
2616 click_count,
2617 } => self.begin_selection(position, add, click_count, cx),
2618 SelectPhase::BeginColumnar {
2619 position,
2620 goal_column,
2621 reset,
2622 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2623 SelectPhase::Extend {
2624 position,
2625 click_count,
2626 } => self.extend_selection(position, click_count, cx),
2627 SelectPhase::Update {
2628 position,
2629 goal_column,
2630 scroll_delta,
2631 } => self.update_selection(position, goal_column, scroll_delta, cx),
2632 SelectPhase::End => self.end_selection(cx),
2633 }
2634 }
2635
2636 fn extend_selection(
2637 &mut self,
2638 position: DisplayPoint,
2639 click_count: usize,
2640 cx: &mut ViewContext<Self>,
2641 ) {
2642 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2643 let tail = self.selections.newest::<usize>(cx).tail();
2644 self.begin_selection(position, false, click_count, cx);
2645
2646 let position = position.to_offset(&display_map, Bias::Left);
2647 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2648
2649 let mut pending_selection = self
2650 .selections
2651 .pending_anchor()
2652 .expect("extend_selection not called with pending selection");
2653 if position >= tail {
2654 pending_selection.start = tail_anchor;
2655 } else {
2656 pending_selection.end = tail_anchor;
2657 pending_selection.reversed = true;
2658 }
2659
2660 let mut pending_mode = self.selections.pending_mode().unwrap();
2661 match &mut pending_mode {
2662 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2663 _ => {}
2664 }
2665
2666 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2667 s.set_pending(pending_selection, pending_mode)
2668 });
2669 }
2670
2671 fn begin_selection(
2672 &mut self,
2673 position: DisplayPoint,
2674 add: bool,
2675 click_count: usize,
2676 cx: &mut ViewContext<Self>,
2677 ) {
2678 if !self.focus_handle.is_focused(cx) {
2679 self.last_focused_descendant = None;
2680 cx.focus(&self.focus_handle);
2681 }
2682
2683 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2684 let buffer = &display_map.buffer_snapshot;
2685 let newest_selection = self.selections.newest_anchor().clone();
2686 let position = display_map.clip_point(position, Bias::Left);
2687
2688 let start;
2689 let end;
2690 let mode;
2691 let auto_scroll;
2692 match click_count {
2693 1 => {
2694 start = buffer.anchor_before(position.to_point(&display_map));
2695 end = start;
2696 mode = SelectMode::Character;
2697 auto_scroll = true;
2698 }
2699 2 => {
2700 let range = movement::surrounding_word(&display_map, position);
2701 start = buffer.anchor_before(range.start.to_point(&display_map));
2702 end = buffer.anchor_before(range.end.to_point(&display_map));
2703 mode = SelectMode::Word(start..end);
2704 auto_scroll = true;
2705 }
2706 3 => {
2707 let position = display_map
2708 .clip_point(position, Bias::Left)
2709 .to_point(&display_map);
2710 let line_start = display_map.prev_line_boundary(position).0;
2711 let next_line_start = buffer.clip_point(
2712 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2713 Bias::Left,
2714 );
2715 start = buffer.anchor_before(line_start);
2716 end = buffer.anchor_before(next_line_start);
2717 mode = SelectMode::Line(start..end);
2718 auto_scroll = true;
2719 }
2720 _ => {
2721 start = buffer.anchor_before(0);
2722 end = buffer.anchor_before(buffer.len());
2723 mode = SelectMode::All;
2724 auto_scroll = false;
2725 }
2726 }
2727
2728 let point_to_delete: Option<usize> = {
2729 let selected_points: Vec<Selection<Point>> =
2730 self.selections.disjoint_in_range(start..end, cx);
2731
2732 if !add || click_count > 1 {
2733 None
2734 } else if !selected_points.is_empty() {
2735 Some(selected_points[0].id)
2736 } else {
2737 let clicked_point_already_selected =
2738 self.selections.disjoint.iter().find(|selection| {
2739 selection.start.to_point(buffer) == start.to_point(buffer)
2740 || selection.end.to_point(buffer) == end.to_point(buffer)
2741 });
2742
2743 clicked_point_already_selected.map(|selection| selection.id)
2744 }
2745 };
2746
2747 let selections_count = self.selections.count();
2748
2749 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2750 if let Some(point_to_delete) = point_to_delete {
2751 s.delete(point_to_delete);
2752
2753 if selections_count == 1 {
2754 s.set_pending_anchor_range(start..end, mode);
2755 }
2756 } else {
2757 if !add {
2758 s.clear_disjoint();
2759 } else if click_count > 1 {
2760 s.delete(newest_selection.id)
2761 }
2762
2763 s.set_pending_anchor_range(start..end, mode);
2764 }
2765 });
2766 }
2767
2768 fn begin_columnar_selection(
2769 &mut self,
2770 position: DisplayPoint,
2771 goal_column: u32,
2772 reset: bool,
2773 cx: &mut ViewContext<Self>,
2774 ) {
2775 if !self.focus_handle.is_focused(cx) {
2776 self.last_focused_descendant = None;
2777 cx.focus(&self.focus_handle);
2778 }
2779
2780 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2781
2782 if reset {
2783 let pointer_position = display_map
2784 .buffer_snapshot
2785 .anchor_before(position.to_point(&display_map));
2786
2787 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2788 s.clear_disjoint();
2789 s.set_pending_anchor_range(
2790 pointer_position..pointer_position,
2791 SelectMode::Character,
2792 );
2793 });
2794 }
2795
2796 let tail = self.selections.newest::<Point>(cx).tail();
2797 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2798
2799 if !reset {
2800 self.select_columns(
2801 tail.to_display_point(&display_map),
2802 position,
2803 goal_column,
2804 &display_map,
2805 cx,
2806 );
2807 }
2808 }
2809
2810 fn update_selection(
2811 &mut self,
2812 position: DisplayPoint,
2813 goal_column: u32,
2814 scroll_delta: gpui::Point<f32>,
2815 cx: &mut ViewContext<Self>,
2816 ) {
2817 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2818
2819 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2820 let tail = tail.to_display_point(&display_map);
2821 self.select_columns(tail, position, goal_column, &display_map, cx);
2822 } else if let Some(mut pending) = self.selections.pending_anchor() {
2823 let buffer = self.buffer.read(cx).snapshot(cx);
2824 let head;
2825 let tail;
2826 let mode = self.selections.pending_mode().unwrap();
2827 match &mode {
2828 SelectMode::Character => {
2829 head = position.to_point(&display_map);
2830 tail = pending.tail().to_point(&buffer);
2831 }
2832 SelectMode::Word(original_range) => {
2833 let original_display_range = original_range.start.to_display_point(&display_map)
2834 ..original_range.end.to_display_point(&display_map);
2835 let original_buffer_range = original_display_range.start.to_point(&display_map)
2836 ..original_display_range.end.to_point(&display_map);
2837 if movement::is_inside_word(&display_map, position)
2838 || original_display_range.contains(&position)
2839 {
2840 let word_range = movement::surrounding_word(&display_map, position);
2841 if word_range.start < original_display_range.start {
2842 head = word_range.start.to_point(&display_map);
2843 } else {
2844 head = word_range.end.to_point(&display_map);
2845 }
2846 } else {
2847 head = position.to_point(&display_map);
2848 }
2849
2850 if head <= original_buffer_range.start {
2851 tail = original_buffer_range.end;
2852 } else {
2853 tail = original_buffer_range.start;
2854 }
2855 }
2856 SelectMode::Line(original_range) => {
2857 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2858
2859 let position = display_map
2860 .clip_point(position, Bias::Left)
2861 .to_point(&display_map);
2862 let line_start = display_map.prev_line_boundary(position).0;
2863 let next_line_start = buffer.clip_point(
2864 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2865 Bias::Left,
2866 );
2867
2868 if line_start < original_range.start {
2869 head = line_start
2870 } else {
2871 head = next_line_start
2872 }
2873
2874 if head <= original_range.start {
2875 tail = original_range.end;
2876 } else {
2877 tail = original_range.start;
2878 }
2879 }
2880 SelectMode::All => {
2881 return;
2882 }
2883 };
2884
2885 if head < tail {
2886 pending.start = buffer.anchor_before(head);
2887 pending.end = buffer.anchor_before(tail);
2888 pending.reversed = true;
2889 } else {
2890 pending.start = buffer.anchor_before(tail);
2891 pending.end = buffer.anchor_before(head);
2892 pending.reversed = false;
2893 }
2894
2895 self.change_selections(None, cx, |s| {
2896 s.set_pending(pending, mode);
2897 });
2898 } else {
2899 log::error!("update_selection dispatched with no pending selection");
2900 return;
2901 }
2902
2903 self.apply_scroll_delta(scroll_delta, cx);
2904 cx.notify();
2905 }
2906
2907 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2908 self.columnar_selection_tail.take();
2909 if self.selections.pending_anchor().is_some() {
2910 let selections = self.selections.all::<usize>(cx);
2911 self.change_selections(None, cx, |s| {
2912 s.select(selections);
2913 s.clear_pending();
2914 });
2915 }
2916 }
2917
2918 fn select_columns(
2919 &mut self,
2920 tail: DisplayPoint,
2921 head: DisplayPoint,
2922 goal_column: u32,
2923 display_map: &DisplaySnapshot,
2924 cx: &mut ViewContext<Self>,
2925 ) {
2926 let start_row = cmp::min(tail.row(), head.row());
2927 let end_row = cmp::max(tail.row(), head.row());
2928 let start_column = cmp::min(tail.column(), goal_column);
2929 let end_column = cmp::max(tail.column(), goal_column);
2930 let reversed = start_column < tail.column();
2931
2932 let selection_ranges = (start_row.0..=end_row.0)
2933 .map(DisplayRow)
2934 .filter_map(|row| {
2935 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2936 let start = display_map
2937 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2938 .to_point(display_map);
2939 let end = display_map
2940 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2941 .to_point(display_map);
2942 if reversed {
2943 Some(end..start)
2944 } else {
2945 Some(start..end)
2946 }
2947 } else {
2948 None
2949 }
2950 })
2951 .collect::<Vec<_>>();
2952
2953 self.change_selections(None, cx, |s| {
2954 s.select_ranges(selection_ranges);
2955 });
2956 cx.notify();
2957 }
2958
2959 pub fn has_pending_nonempty_selection(&self) -> bool {
2960 let pending_nonempty_selection = match self.selections.pending_anchor() {
2961 Some(Selection { start, end, .. }) => start != end,
2962 None => false,
2963 };
2964
2965 pending_nonempty_selection
2966 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2967 }
2968
2969 pub fn has_pending_selection(&self) -> bool {
2970 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2971 }
2972
2973 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2974 if self.clear_clicked_diff_hunks(cx) {
2975 cx.notify();
2976 return;
2977 }
2978 if self.dismiss_menus_and_popups(true, cx) {
2979 return;
2980 }
2981
2982 if self.mode == EditorMode::Full
2983 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
2984 {
2985 return;
2986 }
2987
2988 cx.propagate();
2989 }
2990
2991 pub fn dismiss_menus_and_popups(
2992 &mut self,
2993 should_report_inline_completion_event: bool,
2994 cx: &mut ViewContext<Self>,
2995 ) -> bool {
2996 if self.take_rename(false, cx).is_some() {
2997 return true;
2998 }
2999
3000 if hide_hover(self, cx) {
3001 return true;
3002 }
3003
3004 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3005 return true;
3006 }
3007
3008 if self.hide_context_menu(cx).is_some() {
3009 return true;
3010 }
3011
3012 if self.mouse_context_menu.take().is_some() {
3013 return true;
3014 }
3015
3016 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3017 return true;
3018 }
3019
3020 if self.snippet_stack.pop().is_some() {
3021 return true;
3022 }
3023
3024 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3025 self.dismiss_diagnostics(cx);
3026 return true;
3027 }
3028
3029 false
3030 }
3031
3032 fn linked_editing_ranges_for(
3033 &self,
3034 selection: Range<text::Anchor>,
3035 cx: &AppContext,
3036 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3037 if self.linked_edit_ranges.is_empty() {
3038 return None;
3039 }
3040 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3041 selection.end.buffer_id.and_then(|end_buffer_id| {
3042 if selection.start.buffer_id != Some(end_buffer_id) {
3043 return None;
3044 }
3045 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3046 let snapshot = buffer.read(cx).snapshot();
3047 self.linked_edit_ranges
3048 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3049 .map(|ranges| (ranges, snapshot, buffer))
3050 })?;
3051 use text::ToOffset as TO;
3052 // find offset from the start of current range to current cursor position
3053 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3054
3055 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3056 let start_difference = start_offset - start_byte_offset;
3057 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3058 let end_difference = end_offset - start_byte_offset;
3059 // Current range has associated linked ranges.
3060 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3061 for range in linked_ranges.iter() {
3062 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3063 let end_offset = start_offset + end_difference;
3064 let start_offset = start_offset + start_difference;
3065 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3066 continue;
3067 }
3068 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3069 if s.start.buffer_id != selection.start.buffer_id
3070 || s.end.buffer_id != selection.end.buffer_id
3071 {
3072 return false;
3073 }
3074 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3075 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3076 }) {
3077 continue;
3078 }
3079 let start = buffer_snapshot.anchor_after(start_offset);
3080 let end = buffer_snapshot.anchor_after(end_offset);
3081 linked_edits
3082 .entry(buffer.clone())
3083 .or_default()
3084 .push(start..end);
3085 }
3086 Some(linked_edits)
3087 }
3088
3089 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3090 let text: Arc<str> = text.into();
3091
3092 if self.read_only(cx) {
3093 return;
3094 }
3095
3096 let selections = self.selections.all_adjusted(cx);
3097 let mut bracket_inserted = false;
3098 let mut edits = Vec::new();
3099 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3100 let mut new_selections = Vec::with_capacity(selections.len());
3101 let mut new_autoclose_regions = Vec::new();
3102 let snapshot = self.buffer.read(cx).read(cx);
3103
3104 for (selection, autoclose_region) in
3105 self.selections_with_autoclose_regions(selections, &snapshot)
3106 {
3107 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3108 // Determine if the inserted text matches the opening or closing
3109 // bracket of any of this language's bracket pairs.
3110 let mut bracket_pair = None;
3111 let mut is_bracket_pair_start = false;
3112 let mut is_bracket_pair_end = false;
3113 if !text.is_empty() {
3114 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3115 // and they are removing the character that triggered IME popup.
3116 for (pair, enabled) in scope.brackets() {
3117 if !pair.close && !pair.surround {
3118 continue;
3119 }
3120
3121 if enabled && pair.start.ends_with(text.as_ref()) {
3122 bracket_pair = Some(pair.clone());
3123 is_bracket_pair_start = true;
3124 break;
3125 }
3126 if pair.end.as_str() == text.as_ref() {
3127 bracket_pair = Some(pair.clone());
3128 is_bracket_pair_end = true;
3129 break;
3130 }
3131 }
3132 }
3133
3134 if let Some(bracket_pair) = bracket_pair {
3135 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3136 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3137 let auto_surround =
3138 self.use_auto_surround && snapshot_settings.use_auto_surround;
3139 if selection.is_empty() {
3140 if is_bracket_pair_start {
3141 let prefix_len = bracket_pair.start.len() - text.len();
3142
3143 // If the inserted text is a suffix of an opening bracket and the
3144 // selection is preceded by the rest of the opening bracket, then
3145 // insert the closing bracket.
3146 let following_text_allows_autoclose = snapshot
3147 .chars_at(selection.start)
3148 .next()
3149 .map_or(true, |c| scope.should_autoclose_before(c));
3150 let preceding_text_matches_prefix = prefix_len == 0
3151 || (selection.start.column >= (prefix_len as u32)
3152 && snapshot.contains_str_at(
3153 Point::new(
3154 selection.start.row,
3155 selection.start.column - (prefix_len as u32),
3156 ),
3157 &bracket_pair.start[..prefix_len],
3158 ));
3159
3160 if autoclose
3161 && bracket_pair.close
3162 && following_text_allows_autoclose
3163 && preceding_text_matches_prefix
3164 {
3165 let anchor = snapshot.anchor_before(selection.end);
3166 new_selections.push((selection.map(|_| anchor), text.len()));
3167 new_autoclose_regions.push((
3168 anchor,
3169 text.len(),
3170 selection.id,
3171 bracket_pair.clone(),
3172 ));
3173 edits.push((
3174 selection.range(),
3175 format!("{}{}", text, bracket_pair.end).into(),
3176 ));
3177 bracket_inserted = true;
3178 continue;
3179 }
3180 }
3181
3182 if let Some(region) = autoclose_region {
3183 // If the selection is followed by an auto-inserted closing bracket,
3184 // then don't insert that closing bracket again; just move the selection
3185 // past the closing bracket.
3186 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3187 && text.as_ref() == region.pair.end.as_str();
3188 if should_skip {
3189 let anchor = snapshot.anchor_after(selection.end);
3190 new_selections
3191 .push((selection.map(|_| anchor), region.pair.end.len()));
3192 continue;
3193 }
3194 }
3195
3196 let always_treat_brackets_as_autoclosed = snapshot
3197 .settings_at(selection.start, cx)
3198 .always_treat_brackets_as_autoclosed;
3199 if always_treat_brackets_as_autoclosed
3200 && is_bracket_pair_end
3201 && snapshot.contains_str_at(selection.end, text.as_ref())
3202 {
3203 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3204 // and the inserted text is a closing bracket and the selection is followed
3205 // by the closing bracket then move the selection past the closing bracket.
3206 let anchor = snapshot.anchor_after(selection.end);
3207 new_selections.push((selection.map(|_| anchor), text.len()));
3208 continue;
3209 }
3210 }
3211 // If an opening bracket is 1 character long and is typed while
3212 // text is selected, then surround that text with the bracket pair.
3213 else if auto_surround
3214 && bracket_pair.surround
3215 && is_bracket_pair_start
3216 && bracket_pair.start.chars().count() == 1
3217 {
3218 edits.push((selection.start..selection.start, text.clone()));
3219 edits.push((
3220 selection.end..selection.end,
3221 bracket_pair.end.as_str().into(),
3222 ));
3223 bracket_inserted = true;
3224 new_selections.push((
3225 Selection {
3226 id: selection.id,
3227 start: snapshot.anchor_after(selection.start),
3228 end: snapshot.anchor_before(selection.end),
3229 reversed: selection.reversed,
3230 goal: selection.goal,
3231 },
3232 0,
3233 ));
3234 continue;
3235 }
3236 }
3237 }
3238
3239 if self.auto_replace_emoji_shortcode
3240 && selection.is_empty()
3241 && text.as_ref().ends_with(':')
3242 {
3243 if let Some(possible_emoji_short_code) =
3244 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3245 {
3246 if !possible_emoji_short_code.is_empty() {
3247 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3248 let emoji_shortcode_start = Point::new(
3249 selection.start.row,
3250 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3251 );
3252
3253 // Remove shortcode from buffer
3254 edits.push((
3255 emoji_shortcode_start..selection.start,
3256 "".to_string().into(),
3257 ));
3258 new_selections.push((
3259 Selection {
3260 id: selection.id,
3261 start: snapshot.anchor_after(emoji_shortcode_start),
3262 end: snapshot.anchor_before(selection.start),
3263 reversed: selection.reversed,
3264 goal: selection.goal,
3265 },
3266 0,
3267 ));
3268
3269 // Insert emoji
3270 let selection_start_anchor = snapshot.anchor_after(selection.start);
3271 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3272 edits.push((selection.start..selection.end, emoji.to_string().into()));
3273
3274 continue;
3275 }
3276 }
3277 }
3278 }
3279
3280 // If not handling any auto-close operation, then just replace the selected
3281 // text with the given input and move the selection to the end of the
3282 // newly inserted text.
3283 let anchor = snapshot.anchor_after(selection.end);
3284 if !self.linked_edit_ranges.is_empty() {
3285 let start_anchor = snapshot.anchor_before(selection.start);
3286
3287 let is_word_char = text.chars().next().map_or(true, |char| {
3288 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3289 classifier.is_word(char)
3290 });
3291
3292 if is_word_char {
3293 if let Some(ranges) = self
3294 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3295 {
3296 for (buffer, edits) in ranges {
3297 linked_edits
3298 .entry(buffer.clone())
3299 .or_default()
3300 .extend(edits.into_iter().map(|range| (range, text.clone())));
3301 }
3302 }
3303 }
3304 }
3305
3306 new_selections.push((selection.map(|_| anchor), 0));
3307 edits.push((selection.start..selection.end, text.clone()));
3308 }
3309
3310 drop(snapshot);
3311
3312 self.transact(cx, |this, cx| {
3313 this.buffer.update(cx, |buffer, cx| {
3314 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3315 });
3316 for (buffer, edits) in linked_edits {
3317 buffer.update(cx, |buffer, cx| {
3318 let snapshot = buffer.snapshot();
3319 let edits = edits
3320 .into_iter()
3321 .map(|(range, text)| {
3322 use text::ToPoint as TP;
3323 let end_point = TP::to_point(&range.end, &snapshot);
3324 let start_point = TP::to_point(&range.start, &snapshot);
3325 (start_point..end_point, text)
3326 })
3327 .sorted_by_key(|(range, _)| range.start)
3328 .collect::<Vec<_>>();
3329 buffer.edit(edits, None, cx);
3330 })
3331 }
3332 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3333 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3334 let snapshot = this.buffer.read(cx).read(cx);
3335 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3336 .zip(new_selection_deltas)
3337 .map(|(selection, delta)| Selection {
3338 id: selection.id,
3339 start: selection.start + delta,
3340 end: selection.end + delta,
3341 reversed: selection.reversed,
3342 goal: SelectionGoal::None,
3343 })
3344 .collect::<Vec<_>>();
3345
3346 let mut i = 0;
3347 for (position, delta, selection_id, pair) in new_autoclose_regions {
3348 let position = position.to_offset(&snapshot) + delta;
3349 let start = snapshot.anchor_before(position);
3350 let end = snapshot.anchor_after(position);
3351 while let Some(existing_state) = this.autoclose_regions.get(i) {
3352 match existing_state.range.start.cmp(&start, &snapshot) {
3353 Ordering::Less => i += 1,
3354 Ordering::Greater => break,
3355 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3356 Ordering::Less => i += 1,
3357 Ordering::Equal => break,
3358 Ordering::Greater => break,
3359 },
3360 }
3361 }
3362 this.autoclose_regions.insert(
3363 i,
3364 AutocloseRegion {
3365 selection_id,
3366 range: start..end,
3367 pair,
3368 },
3369 );
3370 }
3371
3372 drop(snapshot);
3373 let had_active_inline_completion = this.has_active_inline_completion(cx);
3374 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3375 s.select(new_selections)
3376 });
3377
3378 if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
3379 if let Some(on_type_format_task) =
3380 this.trigger_on_type_formatting(text.to_string(), cx)
3381 {
3382 on_type_format_task.detach_and_log_err(cx);
3383 }
3384 }
3385
3386 let editor_settings = EditorSettings::get_global(cx);
3387 if bracket_inserted
3388 && (editor_settings.auto_signature_help
3389 || editor_settings.show_signature_help_after_edits)
3390 {
3391 this.show_signature_help(&ShowSignatureHelp, cx);
3392 }
3393
3394 let trigger_in_words = !had_active_inline_completion;
3395 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3396 linked_editing_ranges::refresh_linked_ranges(this, cx);
3397 this.refresh_inline_completion(true, false, cx);
3398 });
3399 }
3400
3401 fn find_possible_emoji_shortcode_at_position(
3402 snapshot: &MultiBufferSnapshot,
3403 position: Point,
3404 ) -> Option<String> {
3405 let mut chars = Vec::new();
3406 let mut found_colon = false;
3407 for char in snapshot.reversed_chars_at(position).take(100) {
3408 // Found a possible emoji shortcode in the middle of the buffer
3409 if found_colon {
3410 if char.is_whitespace() {
3411 chars.reverse();
3412 return Some(chars.iter().collect());
3413 }
3414 // If the previous character is not a whitespace, we are in the middle of a word
3415 // and we only want to complete the shortcode if the word is made up of other emojis
3416 let mut containing_word = String::new();
3417 for ch in snapshot
3418 .reversed_chars_at(position)
3419 .skip(chars.len() + 1)
3420 .take(100)
3421 {
3422 if ch.is_whitespace() {
3423 break;
3424 }
3425 containing_word.push(ch);
3426 }
3427 let containing_word = containing_word.chars().rev().collect::<String>();
3428 if util::word_consists_of_emojis(containing_word.as_str()) {
3429 chars.reverse();
3430 return Some(chars.iter().collect());
3431 }
3432 }
3433
3434 if char.is_whitespace() || !char.is_ascii() {
3435 return None;
3436 }
3437 if char == ':' {
3438 found_colon = true;
3439 } else {
3440 chars.push(char);
3441 }
3442 }
3443 // Found a possible emoji shortcode at the beginning of the buffer
3444 chars.reverse();
3445 Some(chars.iter().collect())
3446 }
3447
3448 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3449 self.transact(cx, |this, cx| {
3450 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3451 let selections = this.selections.all::<usize>(cx);
3452 let multi_buffer = this.buffer.read(cx);
3453 let buffer = multi_buffer.snapshot(cx);
3454 selections
3455 .iter()
3456 .map(|selection| {
3457 let start_point = selection.start.to_point(&buffer);
3458 let mut indent =
3459 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3460 indent.len = cmp::min(indent.len, start_point.column);
3461 let start = selection.start;
3462 let end = selection.end;
3463 let selection_is_empty = start == end;
3464 let language_scope = buffer.language_scope_at(start);
3465 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3466 &language_scope
3467 {
3468 let leading_whitespace_len = buffer
3469 .reversed_chars_at(start)
3470 .take_while(|c| c.is_whitespace() && *c != '\n')
3471 .map(|c| c.len_utf8())
3472 .sum::<usize>();
3473
3474 let trailing_whitespace_len = buffer
3475 .chars_at(end)
3476 .take_while(|c| c.is_whitespace() && *c != '\n')
3477 .map(|c| c.len_utf8())
3478 .sum::<usize>();
3479
3480 let insert_extra_newline =
3481 language.brackets().any(|(pair, enabled)| {
3482 let pair_start = pair.start.trim_end();
3483 let pair_end = pair.end.trim_start();
3484
3485 enabled
3486 && pair.newline
3487 && buffer.contains_str_at(
3488 end + trailing_whitespace_len,
3489 pair_end,
3490 )
3491 && buffer.contains_str_at(
3492 (start - leading_whitespace_len)
3493 .saturating_sub(pair_start.len()),
3494 pair_start,
3495 )
3496 });
3497
3498 // Comment extension on newline is allowed only for cursor selections
3499 let comment_delimiter = maybe!({
3500 if !selection_is_empty {
3501 return None;
3502 }
3503
3504 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3505 return None;
3506 }
3507
3508 let delimiters = language.line_comment_prefixes();
3509 let max_len_of_delimiter =
3510 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3511 let (snapshot, range) =
3512 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3513
3514 let mut index_of_first_non_whitespace = 0;
3515 let comment_candidate = snapshot
3516 .chars_for_range(range)
3517 .skip_while(|c| {
3518 let should_skip = c.is_whitespace();
3519 if should_skip {
3520 index_of_first_non_whitespace += 1;
3521 }
3522 should_skip
3523 })
3524 .take(max_len_of_delimiter)
3525 .collect::<String>();
3526 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3527 comment_candidate.starts_with(comment_prefix.as_ref())
3528 })?;
3529 let cursor_is_placed_after_comment_marker =
3530 index_of_first_non_whitespace + comment_prefix.len()
3531 <= start_point.column as usize;
3532 if cursor_is_placed_after_comment_marker {
3533 Some(comment_prefix.clone())
3534 } else {
3535 None
3536 }
3537 });
3538 (comment_delimiter, insert_extra_newline)
3539 } else {
3540 (None, false)
3541 };
3542
3543 let capacity_for_delimiter = comment_delimiter
3544 .as_deref()
3545 .map(str::len)
3546 .unwrap_or_default();
3547 let mut new_text =
3548 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3549 new_text.push('\n');
3550 new_text.extend(indent.chars());
3551 if let Some(delimiter) = &comment_delimiter {
3552 new_text.push_str(delimiter);
3553 }
3554 if insert_extra_newline {
3555 new_text = new_text.repeat(2);
3556 }
3557
3558 let anchor = buffer.anchor_after(end);
3559 let new_selection = selection.map(|_| anchor);
3560 (
3561 (start..end, new_text),
3562 (insert_extra_newline, new_selection),
3563 )
3564 })
3565 .unzip()
3566 };
3567
3568 this.edit_with_autoindent(edits, cx);
3569 let buffer = this.buffer.read(cx).snapshot(cx);
3570 let new_selections = selection_fixup_info
3571 .into_iter()
3572 .map(|(extra_newline_inserted, new_selection)| {
3573 let mut cursor = new_selection.end.to_point(&buffer);
3574 if extra_newline_inserted {
3575 cursor.row -= 1;
3576 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3577 }
3578 new_selection.map(|_| cursor)
3579 })
3580 .collect();
3581
3582 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3583 this.refresh_inline_completion(true, false, cx);
3584 });
3585 }
3586
3587 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3588 let buffer = self.buffer.read(cx);
3589 let snapshot = buffer.snapshot(cx);
3590
3591 let mut edits = Vec::new();
3592 let mut rows = Vec::new();
3593
3594 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3595 let cursor = selection.head();
3596 let row = cursor.row;
3597
3598 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3599
3600 let newline = "\n".to_string();
3601 edits.push((start_of_line..start_of_line, newline));
3602
3603 rows.push(row + rows_inserted as u32);
3604 }
3605
3606 self.transact(cx, |editor, cx| {
3607 editor.edit(edits, cx);
3608
3609 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3610 let mut index = 0;
3611 s.move_cursors_with(|map, _, _| {
3612 let row = rows[index];
3613 index += 1;
3614
3615 let point = Point::new(row, 0);
3616 let boundary = map.next_line_boundary(point).1;
3617 let clipped = map.clip_point(boundary, Bias::Left);
3618
3619 (clipped, SelectionGoal::None)
3620 });
3621 });
3622
3623 let mut indent_edits = Vec::new();
3624 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3625 for row in rows {
3626 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3627 for (row, indent) in indents {
3628 if indent.len == 0 {
3629 continue;
3630 }
3631
3632 let text = match indent.kind {
3633 IndentKind::Space => " ".repeat(indent.len as usize),
3634 IndentKind::Tab => "\t".repeat(indent.len as usize),
3635 };
3636 let point = Point::new(row.0, 0);
3637 indent_edits.push((point..point, text));
3638 }
3639 }
3640 editor.edit(indent_edits, cx);
3641 });
3642 }
3643
3644 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3645 let buffer = self.buffer.read(cx);
3646 let snapshot = buffer.snapshot(cx);
3647
3648 let mut edits = Vec::new();
3649 let mut rows = Vec::new();
3650 let mut rows_inserted = 0;
3651
3652 for selection in self.selections.all_adjusted(cx) {
3653 let cursor = selection.head();
3654 let row = cursor.row;
3655
3656 let point = Point::new(row + 1, 0);
3657 let start_of_line = snapshot.clip_point(point, Bias::Left);
3658
3659 let newline = "\n".to_string();
3660 edits.push((start_of_line..start_of_line, newline));
3661
3662 rows_inserted += 1;
3663 rows.push(row + rows_inserted);
3664 }
3665
3666 self.transact(cx, |editor, cx| {
3667 editor.edit(edits, cx);
3668
3669 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3670 let mut index = 0;
3671 s.move_cursors_with(|map, _, _| {
3672 let row = rows[index];
3673 index += 1;
3674
3675 let point = Point::new(row, 0);
3676 let boundary = map.next_line_boundary(point).1;
3677 let clipped = map.clip_point(boundary, Bias::Left);
3678
3679 (clipped, SelectionGoal::None)
3680 });
3681 });
3682
3683 let mut indent_edits = Vec::new();
3684 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3685 for row in rows {
3686 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3687 for (row, indent) in indents {
3688 if indent.len == 0 {
3689 continue;
3690 }
3691
3692 let text = match indent.kind {
3693 IndentKind::Space => " ".repeat(indent.len as usize),
3694 IndentKind::Tab => "\t".repeat(indent.len as usize),
3695 };
3696 let point = Point::new(row.0, 0);
3697 indent_edits.push((point..point, text));
3698 }
3699 }
3700 editor.edit(indent_edits, cx);
3701 });
3702 }
3703
3704 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3705 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3706 original_indent_columns: Vec::new(),
3707 });
3708 self.insert_with_autoindent_mode(text, autoindent, cx);
3709 }
3710
3711 fn insert_with_autoindent_mode(
3712 &mut self,
3713 text: &str,
3714 autoindent_mode: Option<AutoindentMode>,
3715 cx: &mut ViewContext<Self>,
3716 ) {
3717 if self.read_only(cx) {
3718 return;
3719 }
3720
3721 let text: Arc<str> = text.into();
3722 self.transact(cx, |this, cx| {
3723 let old_selections = this.selections.all_adjusted(cx);
3724 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3725 let anchors = {
3726 let snapshot = buffer.read(cx);
3727 old_selections
3728 .iter()
3729 .map(|s| {
3730 let anchor = snapshot.anchor_after(s.head());
3731 s.map(|_| anchor)
3732 })
3733 .collect::<Vec<_>>()
3734 };
3735 buffer.edit(
3736 old_selections
3737 .iter()
3738 .map(|s| (s.start..s.end, text.clone())),
3739 autoindent_mode,
3740 cx,
3741 );
3742 anchors
3743 });
3744
3745 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3746 s.select_anchors(selection_anchors);
3747 })
3748 });
3749 }
3750
3751 fn trigger_completion_on_input(
3752 &mut self,
3753 text: &str,
3754 trigger_in_words: bool,
3755 cx: &mut ViewContext<Self>,
3756 ) {
3757 if self.is_completion_trigger(text, trigger_in_words, cx) {
3758 self.show_completions(
3759 &ShowCompletions {
3760 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3761 },
3762 cx,
3763 );
3764 } else {
3765 self.hide_context_menu(cx);
3766 }
3767 }
3768
3769 fn is_completion_trigger(
3770 &self,
3771 text: &str,
3772 trigger_in_words: bool,
3773 cx: &mut ViewContext<Self>,
3774 ) -> bool {
3775 let position = self.selections.newest_anchor().head();
3776 let multibuffer = self.buffer.read(cx);
3777 let Some(buffer) = position
3778 .buffer_id
3779 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3780 else {
3781 return false;
3782 };
3783
3784 if let Some(completion_provider) = &self.completion_provider {
3785 completion_provider.is_completion_trigger(
3786 &buffer,
3787 position.text_anchor,
3788 text,
3789 trigger_in_words,
3790 cx,
3791 )
3792 } else {
3793 false
3794 }
3795 }
3796
3797 /// If any empty selections is touching the start of its innermost containing autoclose
3798 /// region, expand it to select the brackets.
3799 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3800 let selections = self.selections.all::<usize>(cx);
3801 let buffer = self.buffer.read(cx).read(cx);
3802 let new_selections = self
3803 .selections_with_autoclose_regions(selections, &buffer)
3804 .map(|(mut selection, region)| {
3805 if !selection.is_empty() {
3806 return selection;
3807 }
3808
3809 if let Some(region) = region {
3810 let mut range = region.range.to_offset(&buffer);
3811 if selection.start == range.start && range.start >= region.pair.start.len() {
3812 range.start -= region.pair.start.len();
3813 if buffer.contains_str_at(range.start, ®ion.pair.start)
3814 && buffer.contains_str_at(range.end, ®ion.pair.end)
3815 {
3816 range.end += region.pair.end.len();
3817 selection.start = range.start;
3818 selection.end = range.end;
3819
3820 return selection;
3821 }
3822 }
3823 }
3824
3825 let always_treat_brackets_as_autoclosed = buffer
3826 .settings_at(selection.start, cx)
3827 .always_treat_brackets_as_autoclosed;
3828
3829 if !always_treat_brackets_as_autoclosed {
3830 return selection;
3831 }
3832
3833 if let Some(scope) = buffer.language_scope_at(selection.start) {
3834 for (pair, enabled) in scope.brackets() {
3835 if !enabled || !pair.close {
3836 continue;
3837 }
3838
3839 if buffer.contains_str_at(selection.start, &pair.end) {
3840 let pair_start_len = pair.start.len();
3841 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3842 {
3843 selection.start -= pair_start_len;
3844 selection.end += pair.end.len();
3845
3846 return selection;
3847 }
3848 }
3849 }
3850 }
3851
3852 selection
3853 })
3854 .collect();
3855
3856 drop(buffer);
3857 self.change_selections(None, cx, |selections| selections.select(new_selections));
3858 }
3859
3860 /// Iterate the given selections, and for each one, find the smallest surrounding
3861 /// autoclose region. This uses the ordering of the selections and the autoclose
3862 /// regions to avoid repeated comparisons.
3863 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3864 &'a self,
3865 selections: impl IntoIterator<Item = Selection<D>>,
3866 buffer: &'a MultiBufferSnapshot,
3867 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3868 let mut i = 0;
3869 let mut regions = self.autoclose_regions.as_slice();
3870 selections.into_iter().map(move |selection| {
3871 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3872
3873 let mut enclosing = None;
3874 while let Some(pair_state) = regions.get(i) {
3875 if pair_state.range.end.to_offset(buffer) < range.start {
3876 regions = ®ions[i + 1..];
3877 i = 0;
3878 } else if pair_state.range.start.to_offset(buffer) > range.end {
3879 break;
3880 } else {
3881 if pair_state.selection_id == selection.id {
3882 enclosing = Some(pair_state);
3883 }
3884 i += 1;
3885 }
3886 }
3887
3888 (selection.clone(), enclosing)
3889 })
3890 }
3891
3892 /// Remove any autoclose regions that no longer contain their selection.
3893 fn invalidate_autoclose_regions(
3894 &mut self,
3895 mut selections: &[Selection<Anchor>],
3896 buffer: &MultiBufferSnapshot,
3897 ) {
3898 self.autoclose_regions.retain(|state| {
3899 let mut i = 0;
3900 while let Some(selection) = selections.get(i) {
3901 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3902 selections = &selections[1..];
3903 continue;
3904 }
3905 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3906 break;
3907 }
3908 if selection.id == state.selection_id {
3909 return true;
3910 } else {
3911 i += 1;
3912 }
3913 }
3914 false
3915 });
3916 }
3917
3918 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3919 let offset = position.to_offset(buffer);
3920 let (word_range, kind) = buffer.surrounding_word(offset, true);
3921 if offset > word_range.start && kind == Some(CharKind::Word) {
3922 Some(
3923 buffer
3924 .text_for_range(word_range.start..offset)
3925 .collect::<String>(),
3926 )
3927 } else {
3928 None
3929 }
3930 }
3931
3932 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3933 self.refresh_inlay_hints(
3934 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3935 cx,
3936 );
3937 }
3938
3939 pub fn inlay_hints_enabled(&self) -> bool {
3940 self.inlay_hint_cache.enabled
3941 }
3942
3943 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3944 if self.project.is_none() || self.mode != EditorMode::Full {
3945 return;
3946 }
3947
3948 let reason_description = reason.description();
3949 let ignore_debounce = matches!(
3950 reason,
3951 InlayHintRefreshReason::SettingsChange(_)
3952 | InlayHintRefreshReason::Toggle(_)
3953 | InlayHintRefreshReason::ExcerptsRemoved(_)
3954 );
3955 let (invalidate_cache, required_languages) = match reason {
3956 InlayHintRefreshReason::Toggle(enabled) => {
3957 self.inlay_hint_cache.enabled = enabled;
3958 if enabled {
3959 (InvalidationStrategy::RefreshRequested, None)
3960 } else {
3961 self.inlay_hint_cache.clear();
3962 self.splice_inlays(
3963 self.visible_inlay_hints(cx)
3964 .iter()
3965 .map(|inlay| inlay.id)
3966 .collect(),
3967 Vec::new(),
3968 cx,
3969 );
3970 return;
3971 }
3972 }
3973 InlayHintRefreshReason::SettingsChange(new_settings) => {
3974 match self.inlay_hint_cache.update_settings(
3975 &self.buffer,
3976 new_settings,
3977 self.visible_inlay_hints(cx),
3978 cx,
3979 ) {
3980 ControlFlow::Break(Some(InlaySplice {
3981 to_remove,
3982 to_insert,
3983 })) => {
3984 self.splice_inlays(to_remove, to_insert, cx);
3985 return;
3986 }
3987 ControlFlow::Break(None) => return,
3988 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3989 }
3990 }
3991 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3992 if let Some(InlaySplice {
3993 to_remove,
3994 to_insert,
3995 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3996 {
3997 self.splice_inlays(to_remove, to_insert, cx);
3998 }
3999 return;
4000 }
4001 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4002 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4003 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4004 }
4005 InlayHintRefreshReason::RefreshRequested => {
4006 (InvalidationStrategy::RefreshRequested, None)
4007 }
4008 };
4009
4010 if let Some(InlaySplice {
4011 to_remove,
4012 to_insert,
4013 }) = self.inlay_hint_cache.spawn_hint_refresh(
4014 reason_description,
4015 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4016 invalidate_cache,
4017 ignore_debounce,
4018 cx,
4019 ) {
4020 self.splice_inlays(to_remove, to_insert, cx);
4021 }
4022 }
4023
4024 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4025 self.display_map
4026 .read(cx)
4027 .current_inlays()
4028 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4029 .cloned()
4030 .collect()
4031 }
4032
4033 pub fn excerpts_for_inlay_hints_query(
4034 &self,
4035 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4036 cx: &mut ViewContext<Editor>,
4037 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4038 let Some(project) = self.project.as_ref() else {
4039 return HashMap::default();
4040 };
4041 let project = project.read(cx);
4042 let multi_buffer = self.buffer().read(cx);
4043 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4044 let multi_buffer_visible_start = self
4045 .scroll_manager
4046 .anchor()
4047 .anchor
4048 .to_point(&multi_buffer_snapshot);
4049 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4050 multi_buffer_visible_start
4051 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4052 Bias::Left,
4053 );
4054 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4055 multi_buffer
4056 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4057 .into_iter()
4058 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4059 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4060 let buffer = buffer_handle.read(cx);
4061 let buffer_file = project::File::from_dyn(buffer.file())?;
4062 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4063 let worktree_entry = buffer_worktree
4064 .read(cx)
4065 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4066 if worktree_entry.is_ignored {
4067 return None;
4068 }
4069
4070 let language = buffer.language()?;
4071 if let Some(restrict_to_languages) = restrict_to_languages {
4072 if !restrict_to_languages.contains(language) {
4073 return None;
4074 }
4075 }
4076 Some((
4077 excerpt_id,
4078 (
4079 buffer_handle,
4080 buffer.version().clone(),
4081 excerpt_visible_range,
4082 ),
4083 ))
4084 })
4085 .collect()
4086 }
4087
4088 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4089 TextLayoutDetails {
4090 text_system: cx.text_system().clone(),
4091 editor_style: self.style.clone().unwrap(),
4092 rem_size: cx.rem_size(),
4093 scroll_anchor: self.scroll_manager.anchor(),
4094 visible_rows: self.visible_line_count(),
4095 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4096 }
4097 }
4098
4099 fn splice_inlays(
4100 &self,
4101 to_remove: Vec<InlayId>,
4102 to_insert: Vec<Inlay>,
4103 cx: &mut ViewContext<Self>,
4104 ) {
4105 self.display_map.update(cx, |display_map, cx| {
4106 display_map.splice_inlays(to_remove, to_insert, cx);
4107 });
4108 cx.notify();
4109 }
4110
4111 fn trigger_on_type_formatting(
4112 &self,
4113 input: String,
4114 cx: &mut ViewContext<Self>,
4115 ) -> Option<Task<Result<()>>> {
4116 if input.len() != 1 {
4117 return None;
4118 }
4119
4120 let project = self.project.as_ref()?;
4121 let position = self.selections.newest_anchor().head();
4122 let (buffer, buffer_position) = self
4123 .buffer
4124 .read(cx)
4125 .text_anchor_for_position(position, cx)?;
4126
4127 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4128 // hence we do LSP request & edit on host side only — add formats to host's history.
4129 let push_to_lsp_host_history = true;
4130 // If this is not the host, append its history with new edits.
4131 let push_to_client_history = project.read(cx).is_via_collab();
4132
4133 let on_type_formatting = project.update(cx, |project, cx| {
4134 project.on_type_format(
4135 buffer.clone(),
4136 buffer_position,
4137 input,
4138 push_to_lsp_host_history,
4139 cx,
4140 )
4141 });
4142 Some(cx.spawn(|editor, mut cx| async move {
4143 if let Some(transaction) = on_type_formatting.await? {
4144 if push_to_client_history {
4145 buffer
4146 .update(&mut cx, |buffer, _| {
4147 buffer.push_transaction(transaction, Instant::now());
4148 })
4149 .ok();
4150 }
4151 editor.update(&mut cx, |editor, cx| {
4152 editor.refresh_document_highlights(cx);
4153 })?;
4154 }
4155 Ok(())
4156 }))
4157 }
4158
4159 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4160 if self.pending_rename.is_some() {
4161 return;
4162 }
4163
4164 let Some(provider) = self.completion_provider.as_ref() else {
4165 return;
4166 };
4167
4168 let position = self.selections.newest_anchor().head();
4169 let (buffer, buffer_position) =
4170 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4171 output
4172 } else {
4173 return;
4174 };
4175
4176 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4177 let is_followup_invoke = {
4178 let context_menu_state = self.context_menu.read();
4179 matches!(
4180 context_menu_state.deref(),
4181 Some(ContextMenu::Completions(_))
4182 )
4183 };
4184 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4185 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4186 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
4187 CompletionTriggerKind::TRIGGER_CHARACTER
4188 }
4189
4190 _ => CompletionTriggerKind::INVOKED,
4191 };
4192 let completion_context = CompletionContext {
4193 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4194 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4195 Some(String::from(trigger))
4196 } else {
4197 None
4198 }
4199 }),
4200 trigger_kind,
4201 };
4202 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4203 let sort_completions = provider.sort_completions();
4204
4205 let id = post_inc(&mut self.next_completion_id);
4206 let task = cx.spawn(|this, mut cx| {
4207 async move {
4208 this.update(&mut cx, |this, _| {
4209 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4210 })?;
4211 let completions = completions.await.log_err();
4212 let menu = if let Some(completions) = completions {
4213 let mut menu = CompletionsMenu {
4214 id,
4215 sort_completions,
4216 initial_position: position,
4217 match_candidates: completions
4218 .iter()
4219 .enumerate()
4220 .map(|(id, completion)| {
4221 StringMatchCandidate::new(
4222 id,
4223 completion.label.text[completion.label.filter_range.clone()]
4224 .into(),
4225 )
4226 })
4227 .collect(),
4228 buffer: buffer.clone(),
4229 completions: Arc::new(RwLock::new(completions.into())),
4230 matches: Vec::new().into(),
4231 selected_item: 0,
4232 scroll_handle: UniformListScrollHandle::new(),
4233 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4234 DebouncedDelay::new(),
4235 )),
4236 };
4237 menu.filter(query.as_deref(), cx.background_executor().clone())
4238 .await;
4239
4240 if menu.matches.is_empty() {
4241 None
4242 } else {
4243 this.update(&mut cx, |editor, cx| {
4244 let completions = menu.completions.clone();
4245 let matches = menu.matches.clone();
4246
4247 let delay_ms = EditorSettings::get_global(cx)
4248 .completion_documentation_secondary_query_debounce;
4249 let delay = Duration::from_millis(delay_ms);
4250 editor
4251 .completion_documentation_pre_resolve_debounce
4252 .fire_new(delay, cx, |editor, cx| {
4253 CompletionsMenu::pre_resolve_completion_documentation(
4254 buffer,
4255 completions,
4256 matches,
4257 editor,
4258 cx,
4259 )
4260 });
4261 })
4262 .ok();
4263 Some(menu)
4264 }
4265 } else {
4266 None
4267 };
4268
4269 this.update(&mut cx, |this, cx| {
4270 let mut context_menu = this.context_menu.write();
4271 match context_menu.as_ref() {
4272 None => {}
4273
4274 Some(ContextMenu::Completions(prev_menu)) => {
4275 if prev_menu.id > id {
4276 return;
4277 }
4278 }
4279
4280 _ => return,
4281 }
4282
4283 if this.focus_handle.is_focused(cx) && menu.is_some() {
4284 let menu = menu.unwrap();
4285 *context_menu = Some(ContextMenu::Completions(menu));
4286 drop(context_menu);
4287 this.discard_inline_completion(false, cx);
4288 cx.notify();
4289 } else if this.completion_tasks.len() <= 1 {
4290 // If there are no more completion tasks and the last menu was
4291 // empty, we should hide it. If it was already hidden, we should
4292 // also show the copilot completion when available.
4293 drop(context_menu);
4294 if this.hide_context_menu(cx).is_none() {
4295 this.update_visible_inline_completion(cx);
4296 }
4297 }
4298 })?;
4299
4300 Ok::<_, anyhow::Error>(())
4301 }
4302 .log_err()
4303 });
4304
4305 self.completion_tasks.push((id, task));
4306 }
4307
4308 pub fn confirm_completion(
4309 &mut self,
4310 action: &ConfirmCompletion,
4311 cx: &mut ViewContext<Self>,
4312 ) -> Option<Task<Result<()>>> {
4313 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4314 }
4315
4316 pub fn compose_completion(
4317 &mut self,
4318 action: &ComposeCompletion,
4319 cx: &mut ViewContext<Self>,
4320 ) -> Option<Task<Result<()>>> {
4321 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4322 }
4323
4324 fn do_completion(
4325 &mut self,
4326 item_ix: Option<usize>,
4327 intent: CompletionIntent,
4328 cx: &mut ViewContext<Editor>,
4329 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4330 use language::ToOffset as _;
4331
4332 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4333 menu
4334 } else {
4335 return None;
4336 };
4337
4338 let mat = completions_menu
4339 .matches
4340 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4341 let buffer_handle = completions_menu.buffer;
4342 let completions = completions_menu.completions.read();
4343 let completion = completions.get(mat.candidate_id)?;
4344 cx.stop_propagation();
4345
4346 let snippet;
4347 let text;
4348
4349 if completion.is_snippet() {
4350 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4351 text = snippet.as_ref().unwrap().text.clone();
4352 } else {
4353 snippet = None;
4354 text = completion.new_text.clone();
4355 };
4356 let selections = self.selections.all::<usize>(cx);
4357 let buffer = buffer_handle.read(cx);
4358 let old_range = completion.old_range.to_offset(buffer);
4359 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4360
4361 let newest_selection = self.selections.newest_anchor();
4362 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4363 return None;
4364 }
4365
4366 let lookbehind = newest_selection
4367 .start
4368 .text_anchor
4369 .to_offset(buffer)
4370 .saturating_sub(old_range.start);
4371 let lookahead = old_range
4372 .end
4373 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4374 let mut common_prefix_len = old_text
4375 .bytes()
4376 .zip(text.bytes())
4377 .take_while(|(a, b)| a == b)
4378 .count();
4379
4380 let snapshot = self.buffer.read(cx).snapshot(cx);
4381 let mut range_to_replace: Option<Range<isize>> = None;
4382 let mut ranges = Vec::new();
4383 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4384 for selection in &selections {
4385 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4386 let start = selection.start.saturating_sub(lookbehind);
4387 let end = selection.end + lookahead;
4388 if selection.id == newest_selection.id {
4389 range_to_replace = Some(
4390 ((start + common_prefix_len) as isize - selection.start as isize)
4391 ..(end as isize - selection.start as isize),
4392 );
4393 }
4394 ranges.push(start + common_prefix_len..end);
4395 } else {
4396 common_prefix_len = 0;
4397 ranges.clear();
4398 ranges.extend(selections.iter().map(|s| {
4399 if s.id == newest_selection.id {
4400 range_to_replace = Some(
4401 old_range.start.to_offset_utf16(&snapshot).0 as isize
4402 - selection.start as isize
4403 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4404 - selection.start as isize,
4405 );
4406 old_range.clone()
4407 } else {
4408 s.start..s.end
4409 }
4410 }));
4411 break;
4412 }
4413 if !self.linked_edit_ranges.is_empty() {
4414 let start_anchor = snapshot.anchor_before(selection.head());
4415 let end_anchor = snapshot.anchor_after(selection.tail());
4416 if let Some(ranges) = self
4417 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4418 {
4419 for (buffer, edits) in ranges {
4420 linked_edits.entry(buffer.clone()).or_default().extend(
4421 edits
4422 .into_iter()
4423 .map(|range| (range, text[common_prefix_len..].to_owned())),
4424 );
4425 }
4426 }
4427 }
4428 }
4429 let text = &text[common_prefix_len..];
4430
4431 cx.emit(EditorEvent::InputHandled {
4432 utf16_range_to_replace: range_to_replace,
4433 text: text.into(),
4434 });
4435
4436 self.transact(cx, |this, cx| {
4437 if let Some(mut snippet) = snippet {
4438 snippet.text = text.to_string();
4439 for tabstop in snippet.tabstops.iter_mut().flatten() {
4440 tabstop.start -= common_prefix_len as isize;
4441 tabstop.end -= common_prefix_len as isize;
4442 }
4443
4444 this.insert_snippet(&ranges, snippet, cx).log_err();
4445 } else {
4446 this.buffer.update(cx, |buffer, cx| {
4447 buffer.edit(
4448 ranges.iter().map(|range| (range.clone(), text)),
4449 this.autoindent_mode.clone(),
4450 cx,
4451 );
4452 });
4453 }
4454 for (buffer, edits) in linked_edits {
4455 buffer.update(cx, |buffer, cx| {
4456 let snapshot = buffer.snapshot();
4457 let edits = edits
4458 .into_iter()
4459 .map(|(range, text)| {
4460 use text::ToPoint as TP;
4461 let end_point = TP::to_point(&range.end, &snapshot);
4462 let start_point = TP::to_point(&range.start, &snapshot);
4463 (start_point..end_point, text)
4464 })
4465 .sorted_by_key(|(range, _)| range.start)
4466 .collect::<Vec<_>>();
4467 buffer.edit(edits, None, cx);
4468 })
4469 }
4470
4471 this.refresh_inline_completion(true, false, cx);
4472 });
4473
4474 let show_new_completions_on_confirm = completion
4475 .confirm
4476 .as_ref()
4477 .map_or(false, |confirm| confirm(intent, cx));
4478 if show_new_completions_on_confirm {
4479 self.show_completions(&ShowCompletions { trigger: None }, cx);
4480 }
4481
4482 let provider = self.completion_provider.as_ref()?;
4483 let apply_edits = provider.apply_additional_edits_for_completion(
4484 buffer_handle,
4485 completion.clone(),
4486 true,
4487 cx,
4488 );
4489
4490 let editor_settings = EditorSettings::get_global(cx);
4491 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4492 // After the code completion is finished, users often want to know what signatures are needed.
4493 // so we should automatically call signature_help
4494 self.show_signature_help(&ShowSignatureHelp, cx);
4495 }
4496
4497 Some(cx.foreground_executor().spawn(async move {
4498 apply_edits.await?;
4499 Ok(())
4500 }))
4501 }
4502
4503 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4504 let mut context_menu = self.context_menu.write();
4505 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4506 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4507 // Toggle if we're selecting the same one
4508 *context_menu = None;
4509 cx.notify();
4510 return;
4511 } else {
4512 // Otherwise, clear it and start a new one
4513 *context_menu = None;
4514 cx.notify();
4515 }
4516 }
4517 drop(context_menu);
4518 let snapshot = self.snapshot(cx);
4519 let deployed_from_indicator = action.deployed_from_indicator;
4520 let mut task = self.code_actions_task.take();
4521 let action = action.clone();
4522 cx.spawn(|editor, mut cx| async move {
4523 while let Some(prev_task) = task {
4524 prev_task.await;
4525 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4526 }
4527
4528 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4529 if editor.focus_handle.is_focused(cx) {
4530 let multibuffer_point = action
4531 .deployed_from_indicator
4532 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4533 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4534 let (buffer, buffer_row) = snapshot
4535 .buffer_snapshot
4536 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4537 .and_then(|(buffer_snapshot, range)| {
4538 editor
4539 .buffer
4540 .read(cx)
4541 .buffer(buffer_snapshot.remote_id())
4542 .map(|buffer| (buffer, range.start.row))
4543 })?;
4544 let (_, code_actions) = editor
4545 .available_code_actions
4546 .clone()
4547 .and_then(|(location, code_actions)| {
4548 let snapshot = location.buffer.read(cx).snapshot();
4549 let point_range = location.range.to_point(&snapshot);
4550 let point_range = point_range.start.row..=point_range.end.row;
4551 if point_range.contains(&buffer_row) {
4552 Some((location, code_actions))
4553 } else {
4554 None
4555 }
4556 })
4557 .unzip();
4558 let buffer_id = buffer.read(cx).remote_id();
4559 let tasks = editor
4560 .tasks
4561 .get(&(buffer_id, buffer_row))
4562 .map(|t| Arc::new(t.to_owned()));
4563 if tasks.is_none() && code_actions.is_none() {
4564 return None;
4565 }
4566
4567 editor.completion_tasks.clear();
4568 editor.discard_inline_completion(false, cx);
4569 let task_context =
4570 tasks
4571 .as_ref()
4572 .zip(editor.project.clone())
4573 .map(|(tasks, project)| {
4574 let position = Point::new(buffer_row, tasks.column);
4575 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4576 let location = Location {
4577 buffer: buffer.clone(),
4578 range: range_start..range_start,
4579 };
4580 // Fill in the environmental variables from the tree-sitter captures
4581 let mut captured_task_variables = TaskVariables::default();
4582 for (capture_name, value) in tasks.extra_variables.clone() {
4583 captured_task_variables.insert(
4584 task::VariableName::Custom(capture_name.into()),
4585 value.clone(),
4586 );
4587 }
4588 project.update(cx, |project, cx| {
4589 project.task_context_for_location(
4590 captured_task_variables,
4591 location,
4592 cx,
4593 )
4594 })
4595 });
4596
4597 Some(cx.spawn(|editor, mut cx| async move {
4598 let task_context = match task_context {
4599 Some(task_context) => task_context.await,
4600 None => None,
4601 };
4602 let resolved_tasks =
4603 tasks.zip(task_context).map(|(tasks, task_context)| {
4604 Arc::new(ResolvedTasks {
4605 templates: tasks
4606 .templates
4607 .iter()
4608 .filter_map(|(kind, template)| {
4609 template
4610 .resolve_task(&kind.to_id_base(), &task_context)
4611 .map(|task| (kind.clone(), task))
4612 })
4613 .collect(),
4614 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4615 multibuffer_point.row,
4616 tasks.column,
4617 )),
4618 })
4619 });
4620 let spawn_straight_away = resolved_tasks
4621 .as_ref()
4622 .map_or(false, |tasks| tasks.templates.len() == 1)
4623 && code_actions
4624 .as_ref()
4625 .map_or(true, |actions| actions.is_empty());
4626 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4627 *editor.context_menu.write() =
4628 Some(ContextMenu::CodeActions(CodeActionsMenu {
4629 buffer,
4630 actions: CodeActionContents {
4631 tasks: resolved_tasks,
4632 actions: code_actions,
4633 },
4634 selected_item: Default::default(),
4635 scroll_handle: UniformListScrollHandle::default(),
4636 deployed_from_indicator,
4637 }));
4638 if spawn_straight_away {
4639 if let Some(task) = editor.confirm_code_action(
4640 &ConfirmCodeAction { item_ix: Some(0) },
4641 cx,
4642 ) {
4643 cx.notify();
4644 return task;
4645 }
4646 }
4647 cx.notify();
4648 Task::ready(Ok(()))
4649 }) {
4650 task.await
4651 } else {
4652 Ok(())
4653 }
4654 }))
4655 } else {
4656 Some(Task::ready(Ok(())))
4657 }
4658 })?;
4659 if let Some(task) = spawned_test_task {
4660 task.await?;
4661 }
4662
4663 Ok::<_, anyhow::Error>(())
4664 })
4665 .detach_and_log_err(cx);
4666 }
4667
4668 pub fn confirm_code_action(
4669 &mut self,
4670 action: &ConfirmCodeAction,
4671 cx: &mut ViewContext<Self>,
4672 ) -> Option<Task<Result<()>>> {
4673 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4674 menu
4675 } else {
4676 return None;
4677 };
4678 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4679 let action = actions_menu.actions.get(action_ix)?;
4680 let title = action.label();
4681 let buffer = actions_menu.buffer;
4682 let workspace = self.workspace()?;
4683
4684 match action {
4685 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4686 workspace.update(cx, |workspace, cx| {
4687 workspace::tasks::schedule_resolved_task(
4688 workspace,
4689 task_source_kind,
4690 resolved_task,
4691 false,
4692 cx,
4693 );
4694
4695 Some(Task::ready(Ok(())))
4696 })
4697 }
4698 CodeActionsItem::CodeAction(action) => {
4699 let apply_code_actions = workspace
4700 .read(cx)
4701 .project()
4702 .clone()
4703 .update(cx, |project, cx| {
4704 project.apply_code_action(buffer, action, true, cx)
4705 });
4706 let workspace = workspace.downgrade();
4707 Some(cx.spawn(|editor, cx| async move {
4708 let project_transaction = apply_code_actions.await?;
4709 Self::open_project_transaction(
4710 &editor,
4711 workspace,
4712 project_transaction,
4713 title,
4714 cx,
4715 )
4716 .await
4717 }))
4718 }
4719 }
4720 }
4721
4722 pub async fn open_project_transaction(
4723 this: &WeakView<Editor>,
4724 workspace: WeakView<Workspace>,
4725 transaction: ProjectTransaction,
4726 title: String,
4727 mut cx: AsyncWindowContext,
4728 ) -> Result<()> {
4729 let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
4730
4731 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4732 cx.update(|cx| {
4733 entries.sort_unstable_by_key(|(buffer, _)| {
4734 buffer.read(cx).file().map(|f| f.path().clone())
4735 });
4736 })?;
4737
4738 // If the project transaction's edits are all contained within this editor, then
4739 // avoid opening a new editor to display them.
4740
4741 if let Some((buffer, transaction)) = entries.first() {
4742 if entries.len() == 1 {
4743 let excerpt = this.update(&mut cx, |editor, cx| {
4744 editor
4745 .buffer()
4746 .read(cx)
4747 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4748 })?;
4749 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4750 if excerpted_buffer == *buffer {
4751 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4752 let excerpt_range = excerpt_range.to_offset(buffer);
4753 buffer
4754 .edited_ranges_for_transaction::<usize>(transaction)
4755 .all(|range| {
4756 excerpt_range.start <= range.start
4757 && excerpt_range.end >= range.end
4758 })
4759 })?;
4760
4761 if all_edits_within_excerpt {
4762 return Ok(());
4763 }
4764 }
4765 }
4766 }
4767 } else {
4768 return Ok(());
4769 }
4770
4771 let mut ranges_to_highlight = Vec::new();
4772 let excerpt_buffer = cx.new_model(|cx| {
4773 let mut multibuffer =
4774 MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
4775 for (buffer_handle, transaction) in &entries {
4776 let buffer = buffer_handle.read(cx);
4777 ranges_to_highlight.extend(
4778 multibuffer.push_excerpts_with_context_lines(
4779 buffer_handle.clone(),
4780 buffer
4781 .edited_ranges_for_transaction::<usize>(transaction)
4782 .collect(),
4783 DEFAULT_MULTIBUFFER_CONTEXT,
4784 cx,
4785 ),
4786 );
4787 }
4788 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4789 multibuffer
4790 })?;
4791
4792 workspace.update(&mut cx, |workspace, cx| {
4793 let project = workspace.project().clone();
4794 let editor =
4795 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4796 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4797 editor.update(cx, |editor, cx| {
4798 editor.highlight_background::<Self>(
4799 &ranges_to_highlight,
4800 |theme| theme.editor_highlighted_line_background,
4801 cx,
4802 );
4803 });
4804 })?;
4805
4806 Ok(())
4807 }
4808
4809 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4810 let project = self.project.clone()?;
4811 let buffer = self.buffer.read(cx);
4812 let newest_selection = self.selections.newest_anchor().clone();
4813 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4814 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4815 if start_buffer != end_buffer {
4816 return None;
4817 }
4818
4819 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4820 cx.background_executor()
4821 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4822 .await;
4823
4824 let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
4825 project.code_actions(&start_buffer, start..end, cx)
4826 }) {
4827 code_actions.await
4828 } else {
4829 Vec::new()
4830 };
4831
4832 this.update(&mut cx, |this, cx| {
4833 this.available_code_actions = if actions.is_empty() {
4834 None
4835 } else {
4836 Some((
4837 Location {
4838 buffer: start_buffer,
4839 range: start..end,
4840 },
4841 actions.into(),
4842 ))
4843 };
4844 cx.notify();
4845 })
4846 .log_err();
4847 }));
4848 None
4849 }
4850
4851 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4852 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4853 self.show_git_blame_inline = false;
4854
4855 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4856 cx.background_executor().timer(delay).await;
4857
4858 this.update(&mut cx, |this, cx| {
4859 this.show_git_blame_inline = true;
4860 cx.notify();
4861 })
4862 .log_err();
4863 }));
4864 }
4865 }
4866
4867 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4868 if self.pending_rename.is_some() {
4869 return None;
4870 }
4871
4872 let project = self.project.clone()?;
4873 let buffer = self.buffer.read(cx);
4874 let newest_selection = self.selections.newest_anchor().clone();
4875 let cursor_position = newest_selection.head();
4876 let (cursor_buffer, cursor_buffer_position) =
4877 buffer.text_anchor_for_position(cursor_position, cx)?;
4878 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4879 if cursor_buffer != tail_buffer {
4880 return None;
4881 }
4882
4883 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4884 cx.background_executor()
4885 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
4886 .await;
4887
4888 let highlights = if let Some(highlights) = project
4889 .update(&mut cx, |project, cx| {
4890 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4891 })
4892 .log_err()
4893 {
4894 highlights.await.log_err()
4895 } else {
4896 None
4897 };
4898
4899 if let Some(highlights) = highlights {
4900 this.update(&mut cx, |this, cx| {
4901 if this.pending_rename.is_some() {
4902 return;
4903 }
4904
4905 let buffer_id = cursor_position.buffer_id;
4906 let buffer = this.buffer.read(cx);
4907 if !buffer
4908 .text_anchor_for_position(cursor_position, cx)
4909 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4910 {
4911 return;
4912 }
4913
4914 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4915 let mut write_ranges = Vec::new();
4916 let mut read_ranges = Vec::new();
4917 for highlight in highlights {
4918 for (excerpt_id, excerpt_range) in
4919 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4920 {
4921 let start = highlight
4922 .range
4923 .start
4924 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4925 let end = highlight
4926 .range
4927 .end
4928 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4929 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4930 continue;
4931 }
4932
4933 let range = Anchor {
4934 buffer_id,
4935 excerpt_id,
4936 text_anchor: start,
4937 }..Anchor {
4938 buffer_id,
4939 excerpt_id,
4940 text_anchor: end,
4941 };
4942 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4943 write_ranges.push(range);
4944 } else {
4945 read_ranges.push(range);
4946 }
4947 }
4948 }
4949
4950 this.highlight_background::<DocumentHighlightRead>(
4951 &read_ranges,
4952 |theme| theme.editor_document_highlight_read_background,
4953 cx,
4954 );
4955 this.highlight_background::<DocumentHighlightWrite>(
4956 &write_ranges,
4957 |theme| theme.editor_document_highlight_write_background,
4958 cx,
4959 );
4960 cx.notify();
4961 })
4962 .log_err();
4963 }
4964 }));
4965 None
4966 }
4967
4968 pub fn refresh_inline_completion(
4969 &mut self,
4970 debounce: bool,
4971 user_requested: bool,
4972 cx: &mut ViewContext<Self>,
4973 ) -> Option<()> {
4974 let provider = self.inline_completion_provider()?;
4975 let cursor = self.selections.newest_anchor().head();
4976 let (buffer, cursor_buffer_position) =
4977 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4978
4979 if !user_requested
4980 && (!self.enable_inline_completions
4981 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
4982 {
4983 self.discard_inline_completion(false, cx);
4984 return None;
4985 }
4986
4987 self.update_visible_inline_completion(cx);
4988 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4989 Some(())
4990 }
4991
4992 fn cycle_inline_completion(
4993 &mut self,
4994 direction: Direction,
4995 cx: &mut ViewContext<Self>,
4996 ) -> Option<()> {
4997 let provider = self.inline_completion_provider()?;
4998 let cursor = self.selections.newest_anchor().head();
4999 let (buffer, cursor_buffer_position) =
5000 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5001 if !self.enable_inline_completions
5002 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5003 {
5004 return None;
5005 }
5006
5007 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5008 self.update_visible_inline_completion(cx);
5009
5010 Some(())
5011 }
5012
5013 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5014 if !self.has_active_inline_completion(cx) {
5015 self.refresh_inline_completion(false, true, cx);
5016 return;
5017 }
5018
5019 self.update_visible_inline_completion(cx);
5020 }
5021
5022 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5023 self.show_cursor_names(cx);
5024 }
5025
5026 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5027 self.show_cursor_names = true;
5028 cx.notify();
5029 cx.spawn(|this, mut cx| async move {
5030 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5031 this.update(&mut cx, |this, cx| {
5032 this.show_cursor_names = false;
5033 cx.notify()
5034 })
5035 .ok()
5036 })
5037 .detach();
5038 }
5039
5040 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5041 if self.has_active_inline_completion(cx) {
5042 self.cycle_inline_completion(Direction::Next, cx);
5043 } else {
5044 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5045 if is_copilot_disabled {
5046 cx.propagate();
5047 }
5048 }
5049 }
5050
5051 pub fn previous_inline_completion(
5052 &mut self,
5053 _: &PreviousInlineCompletion,
5054 cx: &mut ViewContext<Self>,
5055 ) {
5056 if self.has_active_inline_completion(cx) {
5057 self.cycle_inline_completion(Direction::Prev, cx);
5058 } else {
5059 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5060 if is_copilot_disabled {
5061 cx.propagate();
5062 }
5063 }
5064 }
5065
5066 pub fn accept_inline_completion(
5067 &mut self,
5068 _: &AcceptInlineCompletion,
5069 cx: &mut ViewContext<Self>,
5070 ) {
5071 let Some((completion, delete_range)) = self.take_active_inline_completion(cx) else {
5072 return;
5073 };
5074 if let Some(provider) = self.inline_completion_provider() {
5075 provider.accept(cx);
5076 }
5077
5078 cx.emit(EditorEvent::InputHandled {
5079 utf16_range_to_replace: None,
5080 text: completion.text.to_string().into(),
5081 });
5082
5083 if let Some(range) = delete_range {
5084 self.change_selections(None, cx, |s| s.select_ranges([range]))
5085 }
5086 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5087 self.refresh_inline_completion(true, true, cx);
5088 cx.notify();
5089 }
5090
5091 pub fn accept_partial_inline_completion(
5092 &mut self,
5093 _: &AcceptPartialInlineCompletion,
5094 cx: &mut ViewContext<Self>,
5095 ) {
5096 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5097 if let Some((completion, delete_range)) = self.take_active_inline_completion(cx) {
5098 let mut partial_completion = completion
5099 .text
5100 .chars()
5101 .by_ref()
5102 .take_while(|c| c.is_alphabetic())
5103 .collect::<String>();
5104 if partial_completion.is_empty() {
5105 partial_completion = completion
5106 .text
5107 .chars()
5108 .by_ref()
5109 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5110 .collect::<String>();
5111 }
5112
5113 cx.emit(EditorEvent::InputHandled {
5114 utf16_range_to_replace: None,
5115 text: partial_completion.clone().into(),
5116 });
5117
5118 if let Some(range) = delete_range {
5119 self.change_selections(None, cx, |s| s.select_ranges([range]))
5120 }
5121 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5122
5123 self.refresh_inline_completion(true, true, cx);
5124 cx.notify();
5125 }
5126 }
5127 }
5128
5129 fn discard_inline_completion(
5130 &mut self,
5131 should_report_inline_completion_event: bool,
5132 cx: &mut ViewContext<Self>,
5133 ) -> bool {
5134 if let Some(provider) = self.inline_completion_provider() {
5135 provider.discard(should_report_inline_completion_event, cx);
5136 }
5137
5138 self.take_active_inline_completion(cx).is_some()
5139 }
5140
5141 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5142 if let Some(completion) = self.active_inline_completion.as_ref() {
5143 let buffer = self.buffer.read(cx).read(cx);
5144 completion.0.position.is_valid(&buffer)
5145 } else {
5146 false
5147 }
5148 }
5149
5150 fn take_active_inline_completion(
5151 &mut self,
5152 cx: &mut ViewContext<Self>,
5153 ) -> Option<(Inlay, Option<Range<Anchor>>)> {
5154 let completion = self.active_inline_completion.take()?;
5155 self.display_map.update(cx, |map, cx| {
5156 map.splice_inlays(vec![completion.0.id], Default::default(), cx);
5157 });
5158 let buffer = self.buffer.read(cx).read(cx);
5159
5160 if completion.0.position.is_valid(&buffer) {
5161 Some(completion)
5162 } else {
5163 None
5164 }
5165 }
5166
5167 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5168 let selection = self.selections.newest_anchor();
5169 let cursor = selection.head();
5170
5171 let excerpt_id = cursor.excerpt_id;
5172
5173 if self.context_menu.read().is_none()
5174 && self.completion_tasks.is_empty()
5175 && selection.start == selection.end
5176 {
5177 if let Some(provider) = self.inline_completion_provider() {
5178 if let Some((buffer, cursor_buffer_position)) =
5179 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5180 {
5181 if let Some((text, text_anchor_range)) =
5182 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5183 {
5184 let text = Rope::from(text);
5185 let mut to_remove = Vec::new();
5186 if let Some(completion) = self.active_inline_completion.take() {
5187 to_remove.push(completion.0.id);
5188 }
5189
5190 let completion_inlay =
5191 Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
5192
5193 let multibuffer_anchor_range = text_anchor_range.and_then(|range| {
5194 let snapshot = self.buffer.read(cx).snapshot(cx);
5195 Some(
5196 snapshot.anchor_in_excerpt(excerpt_id, range.start)?
5197 ..snapshot.anchor_in_excerpt(excerpt_id, range.end)?,
5198 )
5199 });
5200 self.active_inline_completion =
5201 Some((completion_inlay.clone(), multibuffer_anchor_range));
5202
5203 self.display_map.update(cx, move |map, cx| {
5204 map.splice_inlays(to_remove, vec![completion_inlay], cx)
5205 });
5206 cx.notify();
5207 return;
5208 }
5209 }
5210 }
5211 }
5212
5213 self.discard_inline_completion(false, cx);
5214 }
5215
5216 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5217 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5218 }
5219
5220 fn render_code_actions_indicator(
5221 &self,
5222 _style: &EditorStyle,
5223 row: DisplayRow,
5224 is_active: bool,
5225 cx: &mut ViewContext<Self>,
5226 ) -> Option<IconButton> {
5227 if self.available_code_actions.is_some() {
5228 Some(
5229 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5230 .shape(ui::IconButtonShape::Square)
5231 .icon_size(IconSize::XSmall)
5232 .icon_color(Color::Muted)
5233 .selected(is_active)
5234 .on_click(cx.listener(move |editor, _e, cx| {
5235 editor.focus(cx);
5236 editor.toggle_code_actions(
5237 &ToggleCodeActions {
5238 deployed_from_indicator: Some(row),
5239 },
5240 cx,
5241 );
5242 })),
5243 )
5244 } else {
5245 None
5246 }
5247 }
5248
5249 fn clear_tasks(&mut self) {
5250 self.tasks.clear()
5251 }
5252
5253 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5254 if self.tasks.insert(key, value).is_some() {
5255 // This case should hopefully be rare, but just in case...
5256 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5257 }
5258 }
5259
5260 fn render_run_indicator(
5261 &self,
5262 _style: &EditorStyle,
5263 is_active: bool,
5264 row: DisplayRow,
5265 cx: &mut ViewContext<Self>,
5266 ) -> IconButton {
5267 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5268 .shape(ui::IconButtonShape::Square)
5269 .icon_size(IconSize::XSmall)
5270 .icon_color(Color::Muted)
5271 .selected(is_active)
5272 .on_click(cx.listener(move |editor, _e, cx| {
5273 editor.focus(cx);
5274 editor.toggle_code_actions(
5275 &ToggleCodeActions {
5276 deployed_from_indicator: Some(row),
5277 },
5278 cx,
5279 );
5280 }))
5281 }
5282
5283 fn close_hunk_diff_button(
5284 &self,
5285 hunk: HoveredHunk,
5286 row: DisplayRow,
5287 cx: &mut ViewContext<Self>,
5288 ) -> IconButton {
5289 IconButton::new(
5290 ("close_hunk_diff_indicator", row.0 as usize),
5291 ui::IconName::Close,
5292 )
5293 .shape(ui::IconButtonShape::Square)
5294 .icon_size(IconSize::XSmall)
5295 .icon_color(Color::Muted)
5296 .tooltip(|cx| Tooltip::for_action("Close hunk diff", &ToggleHunkDiff, cx))
5297 .on_click(cx.listener(move |editor, _e, cx| editor.toggle_hovered_hunk(&hunk, cx)))
5298 }
5299
5300 pub fn context_menu_visible(&self) -> bool {
5301 self.context_menu
5302 .read()
5303 .as_ref()
5304 .map_or(false, |menu| menu.visible())
5305 }
5306
5307 fn render_context_menu(
5308 &self,
5309 cursor_position: DisplayPoint,
5310 style: &EditorStyle,
5311 max_height: Pixels,
5312 cx: &mut ViewContext<Editor>,
5313 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5314 self.context_menu.read().as_ref().map(|menu| {
5315 menu.render(
5316 cursor_position,
5317 style,
5318 max_height,
5319 self.workspace.as_ref().map(|(w, _)| w.clone()),
5320 cx,
5321 )
5322 })
5323 }
5324
5325 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5326 cx.notify();
5327 self.completion_tasks.clear();
5328 let context_menu = self.context_menu.write().take();
5329 if context_menu.is_some() {
5330 self.update_visible_inline_completion(cx);
5331 }
5332 context_menu
5333 }
5334
5335 pub fn insert_snippet(
5336 &mut self,
5337 insertion_ranges: &[Range<usize>],
5338 snippet: Snippet,
5339 cx: &mut ViewContext<Self>,
5340 ) -> Result<()> {
5341 struct Tabstop<T> {
5342 is_end_tabstop: bool,
5343 ranges: Vec<Range<T>>,
5344 }
5345
5346 let tabstops = self.buffer.update(cx, |buffer, cx| {
5347 let snippet_text: Arc<str> = snippet.text.clone().into();
5348 buffer.edit(
5349 insertion_ranges
5350 .iter()
5351 .cloned()
5352 .map(|range| (range, snippet_text.clone())),
5353 Some(AutoindentMode::EachLine),
5354 cx,
5355 );
5356
5357 let snapshot = &*buffer.read(cx);
5358 let snippet = &snippet;
5359 snippet
5360 .tabstops
5361 .iter()
5362 .map(|tabstop| {
5363 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5364 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5365 });
5366 let mut tabstop_ranges = tabstop
5367 .iter()
5368 .flat_map(|tabstop_range| {
5369 let mut delta = 0_isize;
5370 insertion_ranges.iter().map(move |insertion_range| {
5371 let insertion_start = insertion_range.start as isize + delta;
5372 delta +=
5373 snippet.text.len() as isize - insertion_range.len() as isize;
5374
5375 let start = ((insertion_start + tabstop_range.start) as usize)
5376 .min(snapshot.len());
5377 let end = ((insertion_start + tabstop_range.end) as usize)
5378 .min(snapshot.len());
5379 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5380 })
5381 })
5382 .collect::<Vec<_>>();
5383 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5384
5385 Tabstop {
5386 is_end_tabstop,
5387 ranges: tabstop_ranges,
5388 }
5389 })
5390 .collect::<Vec<_>>()
5391 });
5392 if let Some(tabstop) = tabstops.first() {
5393 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5394 s.select_ranges(tabstop.ranges.iter().cloned());
5395 });
5396
5397 // If we're already at the last tabstop and it's at the end of the snippet,
5398 // we're done, we don't need to keep the state around.
5399 if !tabstop.is_end_tabstop {
5400 let ranges = tabstops
5401 .into_iter()
5402 .map(|tabstop| tabstop.ranges)
5403 .collect::<Vec<_>>();
5404 self.snippet_stack.push(SnippetState {
5405 active_index: 0,
5406 ranges,
5407 });
5408 }
5409
5410 // Check whether the just-entered snippet ends with an auto-closable bracket.
5411 if self.autoclose_regions.is_empty() {
5412 let snapshot = self.buffer.read(cx).snapshot(cx);
5413 for selection in &mut self.selections.all::<Point>(cx) {
5414 let selection_head = selection.head();
5415 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5416 continue;
5417 };
5418
5419 let mut bracket_pair = None;
5420 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5421 let prev_chars = snapshot
5422 .reversed_chars_at(selection_head)
5423 .collect::<String>();
5424 for (pair, enabled) in scope.brackets() {
5425 if enabled
5426 && pair.close
5427 && prev_chars.starts_with(pair.start.as_str())
5428 && next_chars.starts_with(pair.end.as_str())
5429 {
5430 bracket_pair = Some(pair.clone());
5431 break;
5432 }
5433 }
5434 if let Some(pair) = bracket_pair {
5435 let start = snapshot.anchor_after(selection_head);
5436 let end = snapshot.anchor_after(selection_head);
5437 self.autoclose_regions.push(AutocloseRegion {
5438 selection_id: selection.id,
5439 range: start..end,
5440 pair,
5441 });
5442 }
5443 }
5444 }
5445 }
5446 Ok(())
5447 }
5448
5449 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5450 self.move_to_snippet_tabstop(Bias::Right, cx)
5451 }
5452
5453 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5454 self.move_to_snippet_tabstop(Bias::Left, cx)
5455 }
5456
5457 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5458 if let Some(mut snippet) = self.snippet_stack.pop() {
5459 match bias {
5460 Bias::Left => {
5461 if snippet.active_index > 0 {
5462 snippet.active_index -= 1;
5463 } else {
5464 self.snippet_stack.push(snippet);
5465 return false;
5466 }
5467 }
5468 Bias::Right => {
5469 if snippet.active_index + 1 < snippet.ranges.len() {
5470 snippet.active_index += 1;
5471 } else {
5472 self.snippet_stack.push(snippet);
5473 return false;
5474 }
5475 }
5476 }
5477 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5478 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5479 s.select_anchor_ranges(current_ranges.iter().cloned())
5480 });
5481 // If snippet state is not at the last tabstop, push it back on the stack
5482 if snippet.active_index + 1 < snippet.ranges.len() {
5483 self.snippet_stack.push(snippet);
5484 }
5485 return true;
5486 }
5487 }
5488
5489 false
5490 }
5491
5492 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5493 self.transact(cx, |this, cx| {
5494 this.select_all(&SelectAll, cx);
5495 this.insert("", cx);
5496 });
5497 }
5498
5499 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5500 self.transact(cx, |this, cx| {
5501 this.select_autoclose_pair(cx);
5502 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5503 if !this.linked_edit_ranges.is_empty() {
5504 let selections = this.selections.all::<MultiBufferPoint>(cx);
5505 let snapshot = this.buffer.read(cx).snapshot(cx);
5506
5507 for selection in selections.iter() {
5508 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5509 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5510 if selection_start.buffer_id != selection_end.buffer_id {
5511 continue;
5512 }
5513 if let Some(ranges) =
5514 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5515 {
5516 for (buffer, entries) in ranges {
5517 linked_ranges.entry(buffer).or_default().extend(entries);
5518 }
5519 }
5520 }
5521 }
5522
5523 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5524 if !this.selections.line_mode {
5525 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5526 for selection in &mut selections {
5527 if selection.is_empty() {
5528 let old_head = selection.head();
5529 let mut new_head =
5530 movement::left(&display_map, old_head.to_display_point(&display_map))
5531 .to_point(&display_map);
5532 if let Some((buffer, line_buffer_range)) = display_map
5533 .buffer_snapshot
5534 .buffer_line_for_row(MultiBufferRow(old_head.row))
5535 {
5536 let indent_size =
5537 buffer.indent_size_for_line(line_buffer_range.start.row);
5538 let indent_len = match indent_size.kind {
5539 IndentKind::Space => {
5540 buffer.settings_at(line_buffer_range.start, cx).tab_size
5541 }
5542 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5543 };
5544 if old_head.column <= indent_size.len && old_head.column > 0 {
5545 let indent_len = indent_len.get();
5546 new_head = cmp::min(
5547 new_head,
5548 MultiBufferPoint::new(
5549 old_head.row,
5550 ((old_head.column - 1) / indent_len) * indent_len,
5551 ),
5552 );
5553 }
5554 }
5555
5556 selection.set_head(new_head, SelectionGoal::None);
5557 }
5558 }
5559 }
5560
5561 this.signature_help_state.set_backspace_pressed(true);
5562 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5563 this.insert("", cx);
5564 let empty_str: Arc<str> = Arc::from("");
5565 for (buffer, edits) in linked_ranges {
5566 let snapshot = buffer.read(cx).snapshot();
5567 use text::ToPoint as TP;
5568
5569 let edits = edits
5570 .into_iter()
5571 .map(|range| {
5572 let end_point = TP::to_point(&range.end, &snapshot);
5573 let mut start_point = TP::to_point(&range.start, &snapshot);
5574
5575 if end_point == start_point {
5576 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5577 .saturating_sub(1);
5578 start_point = TP::to_point(&offset, &snapshot);
5579 };
5580
5581 (start_point..end_point, empty_str.clone())
5582 })
5583 .sorted_by_key(|(range, _)| range.start)
5584 .collect::<Vec<_>>();
5585 buffer.update(cx, |this, cx| {
5586 this.edit(edits, None, cx);
5587 })
5588 }
5589 this.refresh_inline_completion(true, false, cx);
5590 linked_editing_ranges::refresh_linked_ranges(this, cx);
5591 });
5592 }
5593
5594 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5595 self.transact(cx, |this, cx| {
5596 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5597 let line_mode = s.line_mode;
5598 s.move_with(|map, selection| {
5599 if selection.is_empty() && !line_mode {
5600 let cursor = movement::right(map, selection.head());
5601 selection.end = cursor;
5602 selection.reversed = true;
5603 selection.goal = SelectionGoal::None;
5604 }
5605 })
5606 });
5607 this.insert("", cx);
5608 this.refresh_inline_completion(true, false, cx);
5609 });
5610 }
5611
5612 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5613 if self.move_to_prev_snippet_tabstop(cx) {
5614 return;
5615 }
5616
5617 self.outdent(&Outdent, cx);
5618 }
5619
5620 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5621 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5622 return;
5623 }
5624
5625 let mut selections = self.selections.all_adjusted(cx);
5626 let buffer = self.buffer.read(cx);
5627 let snapshot = buffer.snapshot(cx);
5628 let rows_iter = selections.iter().map(|s| s.head().row);
5629 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5630
5631 let mut edits = Vec::new();
5632 let mut prev_edited_row = 0;
5633 let mut row_delta = 0;
5634 for selection in &mut selections {
5635 if selection.start.row != prev_edited_row {
5636 row_delta = 0;
5637 }
5638 prev_edited_row = selection.end.row;
5639
5640 // If the selection is non-empty, then increase the indentation of the selected lines.
5641 if !selection.is_empty() {
5642 row_delta =
5643 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5644 continue;
5645 }
5646
5647 // If the selection is empty and the cursor is in the leading whitespace before the
5648 // suggested indentation, then auto-indent the line.
5649 let cursor = selection.head();
5650 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5651 if let Some(suggested_indent) =
5652 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5653 {
5654 if cursor.column < suggested_indent.len
5655 && cursor.column <= current_indent.len
5656 && current_indent.len <= suggested_indent.len
5657 {
5658 selection.start = Point::new(cursor.row, suggested_indent.len);
5659 selection.end = selection.start;
5660 if row_delta == 0 {
5661 edits.extend(Buffer::edit_for_indent_size_adjustment(
5662 cursor.row,
5663 current_indent,
5664 suggested_indent,
5665 ));
5666 row_delta = suggested_indent.len - current_indent.len;
5667 }
5668 continue;
5669 }
5670 }
5671
5672 // Otherwise, insert a hard or soft tab.
5673 let settings = buffer.settings_at(cursor, cx);
5674 let tab_size = if settings.hard_tabs {
5675 IndentSize::tab()
5676 } else {
5677 let tab_size = settings.tab_size.get();
5678 let char_column = snapshot
5679 .text_for_range(Point::new(cursor.row, 0)..cursor)
5680 .flat_map(str::chars)
5681 .count()
5682 + row_delta as usize;
5683 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5684 IndentSize::spaces(chars_to_next_tab_stop)
5685 };
5686 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5687 selection.end = selection.start;
5688 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5689 row_delta += tab_size.len;
5690 }
5691
5692 self.transact(cx, |this, cx| {
5693 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5694 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5695 this.refresh_inline_completion(true, false, cx);
5696 });
5697 }
5698
5699 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5700 if self.read_only(cx) {
5701 return;
5702 }
5703 let mut selections = self.selections.all::<Point>(cx);
5704 let mut prev_edited_row = 0;
5705 let mut row_delta = 0;
5706 let mut edits = Vec::new();
5707 let buffer = self.buffer.read(cx);
5708 let snapshot = buffer.snapshot(cx);
5709 for selection in &mut selections {
5710 if selection.start.row != prev_edited_row {
5711 row_delta = 0;
5712 }
5713 prev_edited_row = selection.end.row;
5714
5715 row_delta =
5716 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5717 }
5718
5719 self.transact(cx, |this, cx| {
5720 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5721 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5722 });
5723 }
5724
5725 fn indent_selection(
5726 buffer: &MultiBuffer,
5727 snapshot: &MultiBufferSnapshot,
5728 selection: &mut Selection<Point>,
5729 edits: &mut Vec<(Range<Point>, String)>,
5730 delta_for_start_row: u32,
5731 cx: &AppContext,
5732 ) -> u32 {
5733 let settings = buffer.settings_at(selection.start, cx);
5734 let tab_size = settings.tab_size.get();
5735 let indent_kind = if settings.hard_tabs {
5736 IndentKind::Tab
5737 } else {
5738 IndentKind::Space
5739 };
5740 let mut start_row = selection.start.row;
5741 let mut end_row = selection.end.row + 1;
5742
5743 // If a selection ends at the beginning of a line, don't indent
5744 // that last line.
5745 if selection.end.column == 0 && selection.end.row > selection.start.row {
5746 end_row -= 1;
5747 }
5748
5749 // Avoid re-indenting a row that has already been indented by a
5750 // previous selection, but still update this selection's column
5751 // to reflect that indentation.
5752 if delta_for_start_row > 0 {
5753 start_row += 1;
5754 selection.start.column += delta_for_start_row;
5755 if selection.end.row == selection.start.row {
5756 selection.end.column += delta_for_start_row;
5757 }
5758 }
5759
5760 let mut delta_for_end_row = 0;
5761 let has_multiple_rows = start_row + 1 != end_row;
5762 for row in start_row..end_row {
5763 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5764 let indent_delta = match (current_indent.kind, indent_kind) {
5765 (IndentKind::Space, IndentKind::Space) => {
5766 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5767 IndentSize::spaces(columns_to_next_tab_stop)
5768 }
5769 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5770 (_, IndentKind::Tab) => IndentSize::tab(),
5771 };
5772
5773 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5774 0
5775 } else {
5776 selection.start.column
5777 };
5778 let row_start = Point::new(row, start);
5779 edits.push((
5780 row_start..row_start,
5781 indent_delta.chars().collect::<String>(),
5782 ));
5783
5784 // Update this selection's endpoints to reflect the indentation.
5785 if row == selection.start.row {
5786 selection.start.column += indent_delta.len;
5787 }
5788 if row == selection.end.row {
5789 selection.end.column += indent_delta.len;
5790 delta_for_end_row = indent_delta.len;
5791 }
5792 }
5793
5794 if selection.start.row == selection.end.row {
5795 delta_for_start_row + delta_for_end_row
5796 } else {
5797 delta_for_end_row
5798 }
5799 }
5800
5801 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5802 if self.read_only(cx) {
5803 return;
5804 }
5805 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5806 let selections = self.selections.all::<Point>(cx);
5807 let mut deletion_ranges = Vec::new();
5808 let mut last_outdent = None;
5809 {
5810 let buffer = self.buffer.read(cx);
5811 let snapshot = buffer.snapshot(cx);
5812 for selection in &selections {
5813 let settings = buffer.settings_at(selection.start, cx);
5814 let tab_size = settings.tab_size.get();
5815 let mut rows = selection.spanned_rows(false, &display_map);
5816
5817 // Avoid re-outdenting a row that has already been outdented by a
5818 // previous selection.
5819 if let Some(last_row) = last_outdent {
5820 if last_row == rows.start {
5821 rows.start = rows.start.next_row();
5822 }
5823 }
5824 let has_multiple_rows = rows.len() > 1;
5825 for row in rows.iter_rows() {
5826 let indent_size = snapshot.indent_size_for_line(row);
5827 if indent_size.len > 0 {
5828 let deletion_len = match indent_size.kind {
5829 IndentKind::Space => {
5830 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5831 if columns_to_prev_tab_stop == 0 {
5832 tab_size
5833 } else {
5834 columns_to_prev_tab_stop
5835 }
5836 }
5837 IndentKind::Tab => 1,
5838 };
5839 let start = if has_multiple_rows
5840 || deletion_len > selection.start.column
5841 || indent_size.len < selection.start.column
5842 {
5843 0
5844 } else {
5845 selection.start.column - deletion_len
5846 };
5847 deletion_ranges.push(
5848 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5849 );
5850 last_outdent = Some(row);
5851 }
5852 }
5853 }
5854 }
5855
5856 self.transact(cx, |this, cx| {
5857 this.buffer.update(cx, |buffer, cx| {
5858 let empty_str: Arc<str> = Arc::default();
5859 buffer.edit(
5860 deletion_ranges
5861 .into_iter()
5862 .map(|range| (range, empty_str.clone())),
5863 None,
5864 cx,
5865 );
5866 });
5867 let selections = this.selections.all::<usize>(cx);
5868 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5869 });
5870 }
5871
5872 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5873 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5874 let selections = self.selections.all::<Point>(cx);
5875
5876 let mut new_cursors = Vec::new();
5877 let mut edit_ranges = Vec::new();
5878 let mut selections = selections.iter().peekable();
5879 while let Some(selection) = selections.next() {
5880 let mut rows = selection.spanned_rows(false, &display_map);
5881 let goal_display_column = selection.head().to_display_point(&display_map).column();
5882
5883 // Accumulate contiguous regions of rows that we want to delete.
5884 while let Some(next_selection) = selections.peek() {
5885 let next_rows = next_selection.spanned_rows(false, &display_map);
5886 if next_rows.start <= rows.end {
5887 rows.end = next_rows.end;
5888 selections.next().unwrap();
5889 } else {
5890 break;
5891 }
5892 }
5893
5894 let buffer = &display_map.buffer_snapshot;
5895 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5896 let edit_end;
5897 let cursor_buffer_row;
5898 if buffer.max_point().row >= rows.end.0 {
5899 // If there's a line after the range, delete the \n from the end of the row range
5900 // and position the cursor on the next line.
5901 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5902 cursor_buffer_row = rows.end;
5903 } else {
5904 // If there isn't a line after the range, delete the \n from the line before the
5905 // start of the row range and position the cursor there.
5906 edit_start = edit_start.saturating_sub(1);
5907 edit_end = buffer.len();
5908 cursor_buffer_row = rows.start.previous_row();
5909 }
5910
5911 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5912 *cursor.column_mut() =
5913 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5914
5915 new_cursors.push((
5916 selection.id,
5917 buffer.anchor_after(cursor.to_point(&display_map)),
5918 ));
5919 edit_ranges.push(edit_start..edit_end);
5920 }
5921
5922 self.transact(cx, |this, cx| {
5923 let buffer = this.buffer.update(cx, |buffer, cx| {
5924 let empty_str: Arc<str> = Arc::default();
5925 buffer.edit(
5926 edit_ranges
5927 .into_iter()
5928 .map(|range| (range, empty_str.clone())),
5929 None,
5930 cx,
5931 );
5932 buffer.snapshot(cx)
5933 });
5934 let new_selections = new_cursors
5935 .into_iter()
5936 .map(|(id, cursor)| {
5937 let cursor = cursor.to_point(&buffer);
5938 Selection {
5939 id,
5940 start: cursor,
5941 end: cursor,
5942 reversed: false,
5943 goal: SelectionGoal::None,
5944 }
5945 })
5946 .collect();
5947
5948 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5949 s.select(new_selections);
5950 });
5951 });
5952 }
5953
5954 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5955 if self.read_only(cx) {
5956 return;
5957 }
5958 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5959 for selection in self.selections.all::<Point>(cx) {
5960 let start = MultiBufferRow(selection.start.row);
5961 let end = if selection.start.row == selection.end.row {
5962 MultiBufferRow(selection.start.row + 1)
5963 } else {
5964 MultiBufferRow(selection.end.row)
5965 };
5966
5967 if let Some(last_row_range) = row_ranges.last_mut() {
5968 if start <= last_row_range.end {
5969 last_row_range.end = end;
5970 continue;
5971 }
5972 }
5973 row_ranges.push(start..end);
5974 }
5975
5976 let snapshot = self.buffer.read(cx).snapshot(cx);
5977 let mut cursor_positions = Vec::new();
5978 for row_range in &row_ranges {
5979 let anchor = snapshot.anchor_before(Point::new(
5980 row_range.end.previous_row().0,
5981 snapshot.line_len(row_range.end.previous_row()),
5982 ));
5983 cursor_positions.push(anchor..anchor);
5984 }
5985
5986 self.transact(cx, |this, cx| {
5987 for row_range in row_ranges.into_iter().rev() {
5988 for row in row_range.iter_rows().rev() {
5989 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5990 let next_line_row = row.next_row();
5991 let indent = snapshot.indent_size_for_line(next_line_row);
5992 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5993
5994 let replace = if snapshot.line_len(next_line_row) > indent.len {
5995 " "
5996 } else {
5997 ""
5998 };
5999
6000 this.buffer.update(cx, |buffer, cx| {
6001 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6002 });
6003 }
6004 }
6005
6006 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6007 s.select_anchor_ranges(cursor_positions)
6008 });
6009 });
6010 }
6011
6012 pub fn sort_lines_case_sensitive(
6013 &mut self,
6014 _: &SortLinesCaseSensitive,
6015 cx: &mut ViewContext<Self>,
6016 ) {
6017 self.manipulate_lines(cx, |lines| lines.sort())
6018 }
6019
6020 pub fn sort_lines_case_insensitive(
6021 &mut self,
6022 _: &SortLinesCaseInsensitive,
6023 cx: &mut ViewContext<Self>,
6024 ) {
6025 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6026 }
6027
6028 pub fn unique_lines_case_insensitive(
6029 &mut self,
6030 _: &UniqueLinesCaseInsensitive,
6031 cx: &mut ViewContext<Self>,
6032 ) {
6033 self.manipulate_lines(cx, |lines| {
6034 let mut seen = HashSet::default();
6035 lines.retain(|line| seen.insert(line.to_lowercase()));
6036 })
6037 }
6038
6039 pub fn unique_lines_case_sensitive(
6040 &mut self,
6041 _: &UniqueLinesCaseSensitive,
6042 cx: &mut ViewContext<Self>,
6043 ) {
6044 self.manipulate_lines(cx, |lines| {
6045 let mut seen = HashSet::default();
6046 lines.retain(|line| seen.insert(*line));
6047 })
6048 }
6049
6050 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6051 let mut revert_changes = HashMap::default();
6052 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6053 for hunk in hunks_for_rows(
6054 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6055 &multi_buffer_snapshot,
6056 ) {
6057 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6058 }
6059 if !revert_changes.is_empty() {
6060 self.transact(cx, |editor, cx| {
6061 editor.revert(revert_changes, cx);
6062 });
6063 }
6064 }
6065
6066 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6067 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6068 if !revert_changes.is_empty() {
6069 self.transact(cx, |editor, cx| {
6070 editor.revert(revert_changes, cx);
6071 });
6072 }
6073 }
6074
6075 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6076 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6077 let project_path = buffer.read(cx).project_path(cx)?;
6078 let project = self.project.as_ref()?.read(cx);
6079 let entry = project.entry_for_path(&project_path, cx)?;
6080 let abs_path = project.absolute_path(&project_path, cx)?;
6081 let parent = if entry.is_symlink {
6082 abs_path.canonicalize().ok()?
6083 } else {
6084 abs_path
6085 }
6086 .parent()?
6087 .to_path_buf();
6088 Some(parent)
6089 }) {
6090 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6091 }
6092 }
6093
6094 fn gather_revert_changes(
6095 &mut self,
6096 selections: &[Selection<Anchor>],
6097 cx: &mut ViewContext<'_, Editor>,
6098 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6099 let mut revert_changes = HashMap::default();
6100 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6101 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6102 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6103 }
6104 revert_changes
6105 }
6106
6107 pub fn prepare_revert_change(
6108 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6109 multi_buffer: &Model<MultiBuffer>,
6110 hunk: &DiffHunk<MultiBufferRow>,
6111 cx: &AppContext,
6112 ) -> Option<()> {
6113 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6114 let buffer = buffer.read(cx);
6115 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6116 let buffer_snapshot = buffer.snapshot();
6117 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6118 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6119 probe
6120 .0
6121 .start
6122 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6123 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6124 }) {
6125 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6126 Some(())
6127 } else {
6128 None
6129 }
6130 }
6131
6132 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6133 self.manipulate_lines(cx, |lines| lines.reverse())
6134 }
6135
6136 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6137 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6138 }
6139
6140 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6141 where
6142 Fn: FnMut(&mut Vec<&str>),
6143 {
6144 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6145 let buffer = self.buffer.read(cx).snapshot(cx);
6146
6147 let mut edits = Vec::new();
6148
6149 let selections = self.selections.all::<Point>(cx);
6150 let mut selections = selections.iter().peekable();
6151 let mut contiguous_row_selections = Vec::new();
6152 let mut new_selections = Vec::new();
6153 let mut added_lines = 0;
6154 let mut removed_lines = 0;
6155
6156 while let Some(selection) = selections.next() {
6157 let (start_row, end_row) = consume_contiguous_rows(
6158 &mut contiguous_row_selections,
6159 selection,
6160 &display_map,
6161 &mut selections,
6162 );
6163
6164 let start_point = Point::new(start_row.0, 0);
6165 let end_point = Point::new(
6166 end_row.previous_row().0,
6167 buffer.line_len(end_row.previous_row()),
6168 );
6169 let text = buffer
6170 .text_for_range(start_point..end_point)
6171 .collect::<String>();
6172
6173 let mut lines = text.split('\n').collect_vec();
6174
6175 let lines_before = lines.len();
6176 callback(&mut lines);
6177 let lines_after = lines.len();
6178
6179 edits.push((start_point..end_point, lines.join("\n")));
6180
6181 // Selections must change based on added and removed line count
6182 let start_row =
6183 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6184 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6185 new_selections.push(Selection {
6186 id: selection.id,
6187 start: start_row,
6188 end: end_row,
6189 goal: SelectionGoal::None,
6190 reversed: selection.reversed,
6191 });
6192
6193 if lines_after > lines_before {
6194 added_lines += lines_after - lines_before;
6195 } else if lines_before > lines_after {
6196 removed_lines += lines_before - lines_after;
6197 }
6198 }
6199
6200 self.transact(cx, |this, cx| {
6201 let buffer = this.buffer.update(cx, |buffer, cx| {
6202 buffer.edit(edits, None, cx);
6203 buffer.snapshot(cx)
6204 });
6205
6206 // Recalculate offsets on newly edited buffer
6207 let new_selections = new_selections
6208 .iter()
6209 .map(|s| {
6210 let start_point = Point::new(s.start.0, 0);
6211 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6212 Selection {
6213 id: s.id,
6214 start: buffer.point_to_offset(start_point),
6215 end: buffer.point_to_offset(end_point),
6216 goal: s.goal,
6217 reversed: s.reversed,
6218 }
6219 })
6220 .collect();
6221
6222 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6223 s.select(new_selections);
6224 });
6225
6226 this.request_autoscroll(Autoscroll::fit(), cx);
6227 });
6228 }
6229
6230 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6231 self.manipulate_text(cx, |text| text.to_uppercase())
6232 }
6233
6234 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6235 self.manipulate_text(cx, |text| text.to_lowercase())
6236 }
6237
6238 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6239 self.manipulate_text(cx, |text| {
6240 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6241 // https://github.com/rutrum/convert-case/issues/16
6242 text.split('\n')
6243 .map(|line| line.to_case(Case::Title))
6244 .join("\n")
6245 })
6246 }
6247
6248 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6249 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6250 }
6251
6252 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6253 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6254 }
6255
6256 pub fn convert_to_upper_camel_case(
6257 &mut self,
6258 _: &ConvertToUpperCamelCase,
6259 cx: &mut ViewContext<Self>,
6260 ) {
6261 self.manipulate_text(cx, |text| {
6262 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6263 // https://github.com/rutrum/convert-case/issues/16
6264 text.split('\n')
6265 .map(|line| line.to_case(Case::UpperCamel))
6266 .join("\n")
6267 })
6268 }
6269
6270 pub fn convert_to_lower_camel_case(
6271 &mut self,
6272 _: &ConvertToLowerCamelCase,
6273 cx: &mut ViewContext<Self>,
6274 ) {
6275 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6276 }
6277
6278 pub fn convert_to_opposite_case(
6279 &mut self,
6280 _: &ConvertToOppositeCase,
6281 cx: &mut ViewContext<Self>,
6282 ) {
6283 self.manipulate_text(cx, |text| {
6284 text.chars()
6285 .fold(String::with_capacity(text.len()), |mut t, c| {
6286 if c.is_uppercase() {
6287 t.extend(c.to_lowercase());
6288 } else {
6289 t.extend(c.to_uppercase());
6290 }
6291 t
6292 })
6293 })
6294 }
6295
6296 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6297 where
6298 Fn: FnMut(&str) -> String,
6299 {
6300 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6301 let buffer = self.buffer.read(cx).snapshot(cx);
6302
6303 let mut new_selections = Vec::new();
6304 let mut edits = Vec::new();
6305 let mut selection_adjustment = 0i32;
6306
6307 for selection in self.selections.all::<usize>(cx) {
6308 let selection_is_empty = selection.is_empty();
6309
6310 let (start, end) = if selection_is_empty {
6311 let word_range = movement::surrounding_word(
6312 &display_map,
6313 selection.start.to_display_point(&display_map),
6314 );
6315 let start = word_range.start.to_offset(&display_map, Bias::Left);
6316 let end = word_range.end.to_offset(&display_map, Bias::Left);
6317 (start, end)
6318 } else {
6319 (selection.start, selection.end)
6320 };
6321
6322 let text = buffer.text_for_range(start..end).collect::<String>();
6323 let old_length = text.len() as i32;
6324 let text = callback(&text);
6325
6326 new_selections.push(Selection {
6327 start: (start as i32 - selection_adjustment) as usize,
6328 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6329 goal: SelectionGoal::None,
6330 ..selection
6331 });
6332
6333 selection_adjustment += old_length - text.len() as i32;
6334
6335 edits.push((start..end, text));
6336 }
6337
6338 self.transact(cx, |this, cx| {
6339 this.buffer.update(cx, |buffer, cx| {
6340 buffer.edit(edits, None, cx);
6341 });
6342
6343 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6344 s.select(new_selections);
6345 });
6346
6347 this.request_autoscroll(Autoscroll::fit(), cx);
6348 });
6349 }
6350
6351 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6352 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6353 let buffer = &display_map.buffer_snapshot;
6354 let selections = self.selections.all::<Point>(cx);
6355
6356 let mut edits = Vec::new();
6357 let mut selections_iter = selections.iter().peekable();
6358 while let Some(selection) = selections_iter.next() {
6359 // Avoid duplicating the same lines twice.
6360 let mut rows = selection.spanned_rows(false, &display_map);
6361
6362 while let Some(next_selection) = selections_iter.peek() {
6363 let next_rows = next_selection.spanned_rows(false, &display_map);
6364 if next_rows.start < rows.end {
6365 rows.end = next_rows.end;
6366 selections_iter.next().unwrap();
6367 } else {
6368 break;
6369 }
6370 }
6371
6372 // Copy the text from the selected row region and splice it either at the start
6373 // or end of the region.
6374 let start = Point::new(rows.start.0, 0);
6375 let end = Point::new(
6376 rows.end.previous_row().0,
6377 buffer.line_len(rows.end.previous_row()),
6378 );
6379 let text = buffer
6380 .text_for_range(start..end)
6381 .chain(Some("\n"))
6382 .collect::<String>();
6383 let insert_location = if upwards {
6384 Point::new(rows.end.0, 0)
6385 } else {
6386 start
6387 };
6388 edits.push((insert_location..insert_location, text));
6389 }
6390
6391 self.transact(cx, |this, cx| {
6392 this.buffer.update(cx, |buffer, cx| {
6393 buffer.edit(edits, None, cx);
6394 });
6395
6396 this.request_autoscroll(Autoscroll::fit(), cx);
6397 });
6398 }
6399
6400 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6401 self.duplicate_line(true, cx);
6402 }
6403
6404 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6405 self.duplicate_line(false, cx);
6406 }
6407
6408 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6409 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6410 let buffer = self.buffer.read(cx).snapshot(cx);
6411
6412 let mut edits = Vec::new();
6413 let mut unfold_ranges = Vec::new();
6414 let mut refold_ranges = Vec::new();
6415
6416 let selections = self.selections.all::<Point>(cx);
6417 let mut selections = selections.iter().peekable();
6418 let mut contiguous_row_selections = Vec::new();
6419 let mut new_selections = Vec::new();
6420
6421 while let Some(selection) = selections.next() {
6422 // Find all the selections that span a contiguous row range
6423 let (start_row, end_row) = consume_contiguous_rows(
6424 &mut contiguous_row_selections,
6425 selection,
6426 &display_map,
6427 &mut selections,
6428 );
6429
6430 // Move the text spanned by the row range to be before the line preceding the row range
6431 if start_row.0 > 0 {
6432 let range_to_move = Point::new(
6433 start_row.previous_row().0,
6434 buffer.line_len(start_row.previous_row()),
6435 )
6436 ..Point::new(
6437 end_row.previous_row().0,
6438 buffer.line_len(end_row.previous_row()),
6439 );
6440 let insertion_point = display_map
6441 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6442 .0;
6443
6444 // Don't move lines across excerpts
6445 if buffer
6446 .excerpt_boundaries_in_range((
6447 Bound::Excluded(insertion_point),
6448 Bound::Included(range_to_move.end),
6449 ))
6450 .next()
6451 .is_none()
6452 {
6453 let text = buffer
6454 .text_for_range(range_to_move.clone())
6455 .flat_map(|s| s.chars())
6456 .skip(1)
6457 .chain(['\n'])
6458 .collect::<String>();
6459
6460 edits.push((
6461 buffer.anchor_after(range_to_move.start)
6462 ..buffer.anchor_before(range_to_move.end),
6463 String::new(),
6464 ));
6465 let insertion_anchor = buffer.anchor_after(insertion_point);
6466 edits.push((insertion_anchor..insertion_anchor, text));
6467
6468 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6469
6470 // Move selections up
6471 new_selections.extend(contiguous_row_selections.drain(..).map(
6472 |mut selection| {
6473 selection.start.row -= row_delta;
6474 selection.end.row -= row_delta;
6475 selection
6476 },
6477 ));
6478
6479 // Move folds up
6480 unfold_ranges.push(range_to_move.clone());
6481 for fold in display_map.folds_in_range(
6482 buffer.anchor_before(range_to_move.start)
6483 ..buffer.anchor_after(range_to_move.end),
6484 ) {
6485 let mut start = fold.range.start.to_point(&buffer);
6486 let mut end = fold.range.end.to_point(&buffer);
6487 start.row -= row_delta;
6488 end.row -= row_delta;
6489 refold_ranges.push((start..end, fold.placeholder.clone()));
6490 }
6491 }
6492 }
6493
6494 // If we didn't move line(s), preserve the existing selections
6495 new_selections.append(&mut contiguous_row_selections);
6496 }
6497
6498 self.transact(cx, |this, cx| {
6499 this.unfold_ranges(unfold_ranges, true, true, cx);
6500 this.buffer.update(cx, |buffer, cx| {
6501 for (range, text) in edits {
6502 buffer.edit([(range, text)], None, cx);
6503 }
6504 });
6505 this.fold_ranges(refold_ranges, true, cx);
6506 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6507 s.select(new_selections);
6508 })
6509 });
6510 }
6511
6512 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6513 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6514 let buffer = self.buffer.read(cx).snapshot(cx);
6515
6516 let mut edits = Vec::new();
6517 let mut unfold_ranges = Vec::new();
6518 let mut refold_ranges = Vec::new();
6519
6520 let selections = self.selections.all::<Point>(cx);
6521 let mut selections = selections.iter().peekable();
6522 let mut contiguous_row_selections = Vec::new();
6523 let mut new_selections = Vec::new();
6524
6525 while let Some(selection) = selections.next() {
6526 // Find all the selections that span a contiguous row range
6527 let (start_row, end_row) = consume_contiguous_rows(
6528 &mut contiguous_row_selections,
6529 selection,
6530 &display_map,
6531 &mut selections,
6532 );
6533
6534 // Move the text spanned by the row range to be after the last line of the row range
6535 if end_row.0 <= buffer.max_point().row {
6536 let range_to_move =
6537 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6538 let insertion_point = display_map
6539 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6540 .0;
6541
6542 // Don't move lines across excerpt boundaries
6543 if buffer
6544 .excerpt_boundaries_in_range((
6545 Bound::Excluded(range_to_move.start),
6546 Bound::Included(insertion_point),
6547 ))
6548 .next()
6549 .is_none()
6550 {
6551 let mut text = String::from("\n");
6552 text.extend(buffer.text_for_range(range_to_move.clone()));
6553 text.pop(); // Drop trailing newline
6554 edits.push((
6555 buffer.anchor_after(range_to_move.start)
6556 ..buffer.anchor_before(range_to_move.end),
6557 String::new(),
6558 ));
6559 let insertion_anchor = buffer.anchor_after(insertion_point);
6560 edits.push((insertion_anchor..insertion_anchor, text));
6561
6562 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6563
6564 // Move selections down
6565 new_selections.extend(contiguous_row_selections.drain(..).map(
6566 |mut selection| {
6567 selection.start.row += row_delta;
6568 selection.end.row += row_delta;
6569 selection
6570 },
6571 ));
6572
6573 // Move folds down
6574 unfold_ranges.push(range_to_move.clone());
6575 for fold in display_map.folds_in_range(
6576 buffer.anchor_before(range_to_move.start)
6577 ..buffer.anchor_after(range_to_move.end),
6578 ) {
6579 let mut start = fold.range.start.to_point(&buffer);
6580 let mut end = fold.range.end.to_point(&buffer);
6581 start.row += row_delta;
6582 end.row += row_delta;
6583 refold_ranges.push((start..end, fold.placeholder.clone()));
6584 }
6585 }
6586 }
6587
6588 // If we didn't move line(s), preserve the existing selections
6589 new_selections.append(&mut contiguous_row_selections);
6590 }
6591
6592 self.transact(cx, |this, cx| {
6593 this.unfold_ranges(unfold_ranges, true, true, cx);
6594 this.buffer.update(cx, |buffer, cx| {
6595 for (range, text) in edits {
6596 buffer.edit([(range, text)], None, cx);
6597 }
6598 });
6599 this.fold_ranges(refold_ranges, true, cx);
6600 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6601 });
6602 }
6603
6604 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6605 let text_layout_details = &self.text_layout_details(cx);
6606 self.transact(cx, |this, cx| {
6607 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6608 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6609 let line_mode = s.line_mode;
6610 s.move_with(|display_map, selection| {
6611 if !selection.is_empty() || line_mode {
6612 return;
6613 }
6614
6615 let mut head = selection.head();
6616 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6617 if head.column() == display_map.line_len(head.row()) {
6618 transpose_offset = display_map
6619 .buffer_snapshot
6620 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6621 }
6622
6623 if transpose_offset == 0 {
6624 return;
6625 }
6626
6627 *head.column_mut() += 1;
6628 head = display_map.clip_point(head, Bias::Right);
6629 let goal = SelectionGoal::HorizontalPosition(
6630 display_map
6631 .x_for_display_point(head, text_layout_details)
6632 .into(),
6633 );
6634 selection.collapse_to(head, goal);
6635
6636 let transpose_start = display_map
6637 .buffer_snapshot
6638 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6639 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6640 let transpose_end = display_map
6641 .buffer_snapshot
6642 .clip_offset(transpose_offset + 1, Bias::Right);
6643 if let Some(ch) =
6644 display_map.buffer_snapshot.chars_at(transpose_start).next()
6645 {
6646 edits.push((transpose_start..transpose_offset, String::new()));
6647 edits.push((transpose_end..transpose_end, ch.to_string()));
6648 }
6649 }
6650 });
6651 edits
6652 });
6653 this.buffer
6654 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6655 let selections = this.selections.all::<usize>(cx);
6656 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6657 s.select(selections);
6658 });
6659 });
6660 }
6661
6662 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6663 let mut text = String::new();
6664 let buffer = self.buffer.read(cx).snapshot(cx);
6665 let mut selections = self.selections.all::<Point>(cx);
6666 let mut clipboard_selections = Vec::with_capacity(selections.len());
6667 {
6668 let max_point = buffer.max_point();
6669 let mut is_first = true;
6670 for selection in &mut selections {
6671 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6672 if is_entire_line {
6673 selection.start = Point::new(selection.start.row, 0);
6674 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6675 selection.goal = SelectionGoal::None;
6676 }
6677 if is_first {
6678 is_first = false;
6679 } else {
6680 text += "\n";
6681 }
6682 let mut len = 0;
6683 for chunk in buffer.text_for_range(selection.start..selection.end) {
6684 text.push_str(chunk);
6685 len += chunk.len();
6686 }
6687 clipboard_selections.push(ClipboardSelection {
6688 len,
6689 is_entire_line,
6690 first_line_indent: buffer
6691 .indent_size_for_line(MultiBufferRow(selection.start.row))
6692 .len,
6693 });
6694 }
6695 }
6696
6697 self.transact(cx, |this, cx| {
6698 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6699 s.select(selections);
6700 });
6701 this.insert("", cx);
6702 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6703 text,
6704 clipboard_selections,
6705 ));
6706 });
6707 }
6708
6709 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6710 let selections = self.selections.all::<Point>(cx);
6711 let buffer = self.buffer.read(cx).read(cx);
6712 let mut text = String::new();
6713
6714 let mut clipboard_selections = Vec::with_capacity(selections.len());
6715 {
6716 let max_point = buffer.max_point();
6717 let mut is_first = true;
6718 for selection in selections.iter() {
6719 let mut start = selection.start;
6720 let mut end = selection.end;
6721 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6722 if is_entire_line {
6723 start = Point::new(start.row, 0);
6724 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6725 }
6726 if is_first {
6727 is_first = false;
6728 } else {
6729 text += "\n";
6730 }
6731 let mut len = 0;
6732 for chunk in buffer.text_for_range(start..end) {
6733 text.push_str(chunk);
6734 len += chunk.len();
6735 }
6736 clipboard_selections.push(ClipboardSelection {
6737 len,
6738 is_entire_line,
6739 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6740 });
6741 }
6742 }
6743
6744 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6745 text,
6746 clipboard_selections,
6747 ));
6748 }
6749
6750 pub fn do_paste(
6751 &mut self,
6752 text: &String,
6753 clipboard_selections: Option<Vec<ClipboardSelection>>,
6754 handle_entire_lines: bool,
6755 cx: &mut ViewContext<Self>,
6756 ) {
6757 if self.read_only(cx) {
6758 return;
6759 }
6760
6761 let clipboard_text = Cow::Borrowed(text);
6762
6763 self.transact(cx, |this, cx| {
6764 if let Some(mut clipboard_selections) = clipboard_selections {
6765 let old_selections = this.selections.all::<usize>(cx);
6766 let all_selections_were_entire_line =
6767 clipboard_selections.iter().all(|s| s.is_entire_line);
6768 let first_selection_indent_column =
6769 clipboard_selections.first().map(|s| s.first_line_indent);
6770 if clipboard_selections.len() != old_selections.len() {
6771 clipboard_selections.drain(..);
6772 }
6773
6774 this.buffer.update(cx, |buffer, cx| {
6775 let snapshot = buffer.read(cx);
6776 let mut start_offset = 0;
6777 let mut edits = Vec::new();
6778 let mut original_indent_columns = Vec::new();
6779 for (ix, selection) in old_selections.iter().enumerate() {
6780 let to_insert;
6781 let entire_line;
6782 let original_indent_column;
6783 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6784 let end_offset = start_offset + clipboard_selection.len;
6785 to_insert = &clipboard_text[start_offset..end_offset];
6786 entire_line = clipboard_selection.is_entire_line;
6787 start_offset = end_offset + 1;
6788 original_indent_column = Some(clipboard_selection.first_line_indent);
6789 } else {
6790 to_insert = clipboard_text.as_str();
6791 entire_line = all_selections_were_entire_line;
6792 original_indent_column = first_selection_indent_column
6793 }
6794
6795 // If the corresponding selection was empty when this slice of the
6796 // clipboard text was written, then the entire line containing the
6797 // selection was copied. If this selection is also currently empty,
6798 // then paste the line before the current line of the buffer.
6799 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6800 let column = selection.start.to_point(&snapshot).column as usize;
6801 let line_start = selection.start - column;
6802 line_start..line_start
6803 } else {
6804 selection.range()
6805 };
6806
6807 edits.push((range, to_insert));
6808 original_indent_columns.extend(original_indent_column);
6809 }
6810 drop(snapshot);
6811
6812 buffer.edit(
6813 edits,
6814 Some(AutoindentMode::Block {
6815 original_indent_columns,
6816 }),
6817 cx,
6818 );
6819 });
6820
6821 let selections = this.selections.all::<usize>(cx);
6822 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6823 } else {
6824 this.insert(&clipboard_text, cx);
6825 }
6826 });
6827 }
6828
6829 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
6830 if let Some(item) = cx.read_from_clipboard() {
6831 let entries = item.entries();
6832
6833 match entries.first() {
6834 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
6835 // of all the pasted entries.
6836 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
6837 .do_paste(
6838 clipboard_string.text(),
6839 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
6840 true,
6841 cx,
6842 ),
6843 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
6844 }
6845 }
6846 }
6847
6848 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
6849 if self.read_only(cx) {
6850 return;
6851 }
6852
6853 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
6854 if let Some((selections, _)) =
6855 self.selection_history.transaction(transaction_id).cloned()
6856 {
6857 self.change_selections(None, cx, |s| {
6858 s.select_anchors(selections.to_vec());
6859 });
6860 }
6861 self.request_autoscroll(Autoscroll::fit(), cx);
6862 self.unmark_text(cx);
6863 self.refresh_inline_completion(true, false, cx);
6864 cx.emit(EditorEvent::Edited { transaction_id });
6865 cx.emit(EditorEvent::TransactionUndone { transaction_id });
6866 }
6867 }
6868
6869 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
6870 if self.read_only(cx) {
6871 return;
6872 }
6873
6874 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
6875 if let Some((_, Some(selections))) =
6876 self.selection_history.transaction(transaction_id).cloned()
6877 {
6878 self.change_selections(None, cx, |s| {
6879 s.select_anchors(selections.to_vec());
6880 });
6881 }
6882 self.request_autoscroll(Autoscroll::fit(), cx);
6883 self.unmark_text(cx);
6884 self.refresh_inline_completion(true, false, cx);
6885 cx.emit(EditorEvent::Edited { transaction_id });
6886 }
6887 }
6888
6889 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
6890 self.buffer
6891 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
6892 }
6893
6894 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
6895 self.buffer
6896 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
6897 }
6898
6899 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
6900 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6901 let line_mode = s.line_mode;
6902 s.move_with(|map, selection| {
6903 let cursor = if selection.is_empty() && !line_mode {
6904 movement::left(map, selection.start)
6905 } else {
6906 selection.start
6907 };
6908 selection.collapse_to(cursor, SelectionGoal::None);
6909 });
6910 })
6911 }
6912
6913 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
6914 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6915 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
6916 })
6917 }
6918
6919 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
6920 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6921 let line_mode = s.line_mode;
6922 s.move_with(|map, selection| {
6923 let cursor = if selection.is_empty() && !line_mode {
6924 movement::right(map, selection.end)
6925 } else {
6926 selection.end
6927 };
6928 selection.collapse_to(cursor, SelectionGoal::None)
6929 });
6930 })
6931 }
6932
6933 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
6934 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6935 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
6936 })
6937 }
6938
6939 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
6940 if self.take_rename(true, cx).is_some() {
6941 return;
6942 }
6943
6944 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6945 cx.propagate();
6946 return;
6947 }
6948
6949 let text_layout_details = &self.text_layout_details(cx);
6950 let selection_count = self.selections.count();
6951 let first_selection = self.selections.first_anchor();
6952
6953 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6954 let line_mode = s.line_mode;
6955 s.move_with(|map, selection| {
6956 if !selection.is_empty() && !line_mode {
6957 selection.goal = SelectionGoal::None;
6958 }
6959 let (cursor, goal) = movement::up(
6960 map,
6961 selection.start,
6962 selection.goal,
6963 false,
6964 text_layout_details,
6965 );
6966 selection.collapse_to(cursor, goal);
6967 });
6968 });
6969
6970 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
6971 {
6972 cx.propagate();
6973 }
6974 }
6975
6976 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
6977 if self.take_rename(true, cx).is_some() {
6978 return;
6979 }
6980
6981 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6982 cx.propagate();
6983 return;
6984 }
6985
6986 let text_layout_details = &self.text_layout_details(cx);
6987
6988 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6989 let line_mode = s.line_mode;
6990 s.move_with(|map, selection| {
6991 if !selection.is_empty() && !line_mode {
6992 selection.goal = SelectionGoal::None;
6993 }
6994 let (cursor, goal) = movement::up_by_rows(
6995 map,
6996 selection.start,
6997 action.lines,
6998 selection.goal,
6999 false,
7000 text_layout_details,
7001 );
7002 selection.collapse_to(cursor, goal);
7003 });
7004 })
7005 }
7006
7007 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7008 if self.take_rename(true, cx).is_some() {
7009 return;
7010 }
7011
7012 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7013 cx.propagate();
7014 return;
7015 }
7016
7017 let text_layout_details = &self.text_layout_details(cx);
7018
7019 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7020 let line_mode = s.line_mode;
7021 s.move_with(|map, selection| {
7022 if !selection.is_empty() && !line_mode {
7023 selection.goal = SelectionGoal::None;
7024 }
7025 let (cursor, goal) = movement::down_by_rows(
7026 map,
7027 selection.start,
7028 action.lines,
7029 selection.goal,
7030 false,
7031 text_layout_details,
7032 );
7033 selection.collapse_to(cursor, goal);
7034 });
7035 })
7036 }
7037
7038 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7039 let text_layout_details = &self.text_layout_details(cx);
7040 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7041 s.move_heads_with(|map, head, goal| {
7042 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7043 })
7044 })
7045 }
7046
7047 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7048 let text_layout_details = &self.text_layout_details(cx);
7049 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7050 s.move_heads_with(|map, head, goal| {
7051 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7052 })
7053 })
7054 }
7055
7056 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7057 let Some(row_count) = self.visible_row_count() else {
7058 return;
7059 };
7060
7061 let text_layout_details = &self.text_layout_details(cx);
7062
7063 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7064 s.move_heads_with(|map, head, goal| {
7065 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7066 })
7067 })
7068 }
7069
7070 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7071 if self.take_rename(true, cx).is_some() {
7072 return;
7073 }
7074
7075 if self
7076 .context_menu
7077 .write()
7078 .as_mut()
7079 .map(|menu| menu.select_first(self.project.as_ref(), cx))
7080 .unwrap_or(false)
7081 {
7082 return;
7083 }
7084
7085 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7086 cx.propagate();
7087 return;
7088 }
7089
7090 let Some(row_count) = self.visible_row_count() else {
7091 return;
7092 };
7093
7094 let autoscroll = if action.center_cursor {
7095 Autoscroll::center()
7096 } else {
7097 Autoscroll::fit()
7098 };
7099
7100 let text_layout_details = &self.text_layout_details(cx);
7101
7102 self.change_selections(Some(autoscroll), cx, |s| {
7103 let line_mode = s.line_mode;
7104 s.move_with(|map, selection| {
7105 if !selection.is_empty() && !line_mode {
7106 selection.goal = SelectionGoal::None;
7107 }
7108 let (cursor, goal) = movement::up_by_rows(
7109 map,
7110 selection.end,
7111 row_count,
7112 selection.goal,
7113 false,
7114 text_layout_details,
7115 );
7116 selection.collapse_to(cursor, goal);
7117 });
7118 });
7119 }
7120
7121 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7122 let text_layout_details = &self.text_layout_details(cx);
7123 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7124 s.move_heads_with(|map, head, goal| {
7125 movement::up(map, head, goal, false, text_layout_details)
7126 })
7127 })
7128 }
7129
7130 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7131 self.take_rename(true, cx);
7132
7133 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7134 cx.propagate();
7135 return;
7136 }
7137
7138 let text_layout_details = &self.text_layout_details(cx);
7139 let selection_count = self.selections.count();
7140 let first_selection = self.selections.first_anchor();
7141
7142 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7143 let line_mode = s.line_mode;
7144 s.move_with(|map, selection| {
7145 if !selection.is_empty() && !line_mode {
7146 selection.goal = SelectionGoal::None;
7147 }
7148 let (cursor, goal) = movement::down(
7149 map,
7150 selection.end,
7151 selection.goal,
7152 false,
7153 text_layout_details,
7154 );
7155 selection.collapse_to(cursor, goal);
7156 });
7157 });
7158
7159 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7160 {
7161 cx.propagate();
7162 }
7163 }
7164
7165 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7166 let Some(row_count) = self.visible_row_count() else {
7167 return;
7168 };
7169
7170 let text_layout_details = &self.text_layout_details(cx);
7171
7172 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7173 s.move_heads_with(|map, head, goal| {
7174 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7175 })
7176 })
7177 }
7178
7179 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7180 if self.take_rename(true, cx).is_some() {
7181 return;
7182 }
7183
7184 if self
7185 .context_menu
7186 .write()
7187 .as_mut()
7188 .map(|menu| menu.select_last(self.project.as_ref(), cx))
7189 .unwrap_or(false)
7190 {
7191 return;
7192 }
7193
7194 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7195 cx.propagate();
7196 return;
7197 }
7198
7199 let Some(row_count) = self.visible_row_count() else {
7200 return;
7201 };
7202
7203 let autoscroll = if action.center_cursor {
7204 Autoscroll::center()
7205 } else {
7206 Autoscroll::fit()
7207 };
7208
7209 let text_layout_details = &self.text_layout_details(cx);
7210 self.change_selections(Some(autoscroll), cx, |s| {
7211 let line_mode = s.line_mode;
7212 s.move_with(|map, selection| {
7213 if !selection.is_empty() && !line_mode {
7214 selection.goal = SelectionGoal::None;
7215 }
7216 let (cursor, goal) = movement::down_by_rows(
7217 map,
7218 selection.end,
7219 row_count,
7220 selection.goal,
7221 false,
7222 text_layout_details,
7223 );
7224 selection.collapse_to(cursor, goal);
7225 });
7226 });
7227 }
7228
7229 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7230 let text_layout_details = &self.text_layout_details(cx);
7231 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7232 s.move_heads_with(|map, head, goal| {
7233 movement::down(map, head, goal, false, text_layout_details)
7234 })
7235 });
7236 }
7237
7238 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7239 if let Some(context_menu) = self.context_menu.write().as_mut() {
7240 context_menu.select_first(self.project.as_ref(), cx);
7241 }
7242 }
7243
7244 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7245 if let Some(context_menu) = self.context_menu.write().as_mut() {
7246 context_menu.select_prev(self.project.as_ref(), cx);
7247 }
7248 }
7249
7250 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7251 if let Some(context_menu) = self.context_menu.write().as_mut() {
7252 context_menu.select_next(self.project.as_ref(), cx);
7253 }
7254 }
7255
7256 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7257 if let Some(context_menu) = self.context_menu.write().as_mut() {
7258 context_menu.select_last(self.project.as_ref(), cx);
7259 }
7260 }
7261
7262 pub fn move_to_previous_word_start(
7263 &mut self,
7264 _: &MoveToPreviousWordStart,
7265 cx: &mut ViewContext<Self>,
7266 ) {
7267 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7268 s.move_cursors_with(|map, head, _| {
7269 (
7270 movement::previous_word_start(map, head),
7271 SelectionGoal::None,
7272 )
7273 });
7274 })
7275 }
7276
7277 pub fn move_to_previous_subword_start(
7278 &mut self,
7279 _: &MoveToPreviousSubwordStart,
7280 cx: &mut ViewContext<Self>,
7281 ) {
7282 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7283 s.move_cursors_with(|map, head, _| {
7284 (
7285 movement::previous_subword_start(map, head),
7286 SelectionGoal::None,
7287 )
7288 });
7289 })
7290 }
7291
7292 pub fn select_to_previous_word_start(
7293 &mut self,
7294 _: &SelectToPreviousWordStart,
7295 cx: &mut ViewContext<Self>,
7296 ) {
7297 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7298 s.move_heads_with(|map, head, _| {
7299 (
7300 movement::previous_word_start(map, head),
7301 SelectionGoal::None,
7302 )
7303 });
7304 })
7305 }
7306
7307 pub fn select_to_previous_subword_start(
7308 &mut self,
7309 _: &SelectToPreviousSubwordStart,
7310 cx: &mut ViewContext<Self>,
7311 ) {
7312 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7313 s.move_heads_with(|map, head, _| {
7314 (
7315 movement::previous_subword_start(map, head),
7316 SelectionGoal::None,
7317 )
7318 });
7319 })
7320 }
7321
7322 pub fn delete_to_previous_word_start(
7323 &mut self,
7324 action: &DeleteToPreviousWordStart,
7325 cx: &mut ViewContext<Self>,
7326 ) {
7327 self.transact(cx, |this, cx| {
7328 this.select_autoclose_pair(cx);
7329 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7330 let line_mode = s.line_mode;
7331 s.move_with(|map, selection| {
7332 if selection.is_empty() && !line_mode {
7333 let cursor = if action.ignore_newlines {
7334 movement::previous_word_start(map, selection.head())
7335 } else {
7336 movement::previous_word_start_or_newline(map, selection.head())
7337 };
7338 selection.set_head(cursor, SelectionGoal::None);
7339 }
7340 });
7341 });
7342 this.insert("", cx);
7343 });
7344 }
7345
7346 pub fn delete_to_previous_subword_start(
7347 &mut self,
7348 _: &DeleteToPreviousSubwordStart,
7349 cx: &mut ViewContext<Self>,
7350 ) {
7351 self.transact(cx, |this, cx| {
7352 this.select_autoclose_pair(cx);
7353 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7354 let line_mode = s.line_mode;
7355 s.move_with(|map, selection| {
7356 if selection.is_empty() && !line_mode {
7357 let cursor = movement::previous_subword_start(map, selection.head());
7358 selection.set_head(cursor, SelectionGoal::None);
7359 }
7360 });
7361 });
7362 this.insert("", cx);
7363 });
7364 }
7365
7366 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7367 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7368 s.move_cursors_with(|map, head, _| {
7369 (movement::next_word_end(map, head), SelectionGoal::None)
7370 });
7371 })
7372 }
7373
7374 pub fn move_to_next_subword_end(
7375 &mut self,
7376 _: &MoveToNextSubwordEnd,
7377 cx: &mut ViewContext<Self>,
7378 ) {
7379 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7380 s.move_cursors_with(|map, head, _| {
7381 (movement::next_subword_end(map, head), SelectionGoal::None)
7382 });
7383 })
7384 }
7385
7386 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7387 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7388 s.move_heads_with(|map, head, _| {
7389 (movement::next_word_end(map, head), SelectionGoal::None)
7390 });
7391 })
7392 }
7393
7394 pub fn select_to_next_subword_end(
7395 &mut self,
7396 _: &SelectToNextSubwordEnd,
7397 cx: &mut ViewContext<Self>,
7398 ) {
7399 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7400 s.move_heads_with(|map, head, _| {
7401 (movement::next_subword_end(map, head), SelectionGoal::None)
7402 });
7403 })
7404 }
7405
7406 pub fn delete_to_next_word_end(
7407 &mut self,
7408 action: &DeleteToNextWordEnd,
7409 cx: &mut ViewContext<Self>,
7410 ) {
7411 self.transact(cx, |this, cx| {
7412 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7413 let line_mode = s.line_mode;
7414 s.move_with(|map, selection| {
7415 if selection.is_empty() && !line_mode {
7416 let cursor = if action.ignore_newlines {
7417 movement::next_word_end(map, selection.head())
7418 } else {
7419 movement::next_word_end_or_newline(map, selection.head())
7420 };
7421 selection.set_head(cursor, SelectionGoal::None);
7422 }
7423 });
7424 });
7425 this.insert("", cx);
7426 });
7427 }
7428
7429 pub fn delete_to_next_subword_end(
7430 &mut self,
7431 _: &DeleteToNextSubwordEnd,
7432 cx: &mut ViewContext<Self>,
7433 ) {
7434 self.transact(cx, |this, cx| {
7435 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7436 s.move_with(|map, selection| {
7437 if selection.is_empty() {
7438 let cursor = movement::next_subword_end(map, selection.head());
7439 selection.set_head(cursor, SelectionGoal::None);
7440 }
7441 });
7442 });
7443 this.insert("", cx);
7444 });
7445 }
7446
7447 pub fn move_to_beginning_of_line(
7448 &mut self,
7449 action: &MoveToBeginningOfLine,
7450 cx: &mut ViewContext<Self>,
7451 ) {
7452 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7453 s.move_cursors_with(|map, head, _| {
7454 (
7455 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7456 SelectionGoal::None,
7457 )
7458 });
7459 })
7460 }
7461
7462 pub fn select_to_beginning_of_line(
7463 &mut self,
7464 action: &SelectToBeginningOfLine,
7465 cx: &mut ViewContext<Self>,
7466 ) {
7467 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7468 s.move_heads_with(|map, head, _| {
7469 (
7470 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7471 SelectionGoal::None,
7472 )
7473 });
7474 });
7475 }
7476
7477 pub fn delete_to_beginning_of_line(
7478 &mut self,
7479 _: &DeleteToBeginningOfLine,
7480 cx: &mut ViewContext<Self>,
7481 ) {
7482 self.transact(cx, |this, cx| {
7483 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7484 s.move_with(|_, selection| {
7485 selection.reversed = true;
7486 });
7487 });
7488
7489 this.select_to_beginning_of_line(
7490 &SelectToBeginningOfLine {
7491 stop_at_soft_wraps: false,
7492 },
7493 cx,
7494 );
7495 this.backspace(&Backspace, cx);
7496 });
7497 }
7498
7499 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7500 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7501 s.move_cursors_with(|map, head, _| {
7502 (
7503 movement::line_end(map, head, action.stop_at_soft_wraps),
7504 SelectionGoal::None,
7505 )
7506 });
7507 })
7508 }
7509
7510 pub fn select_to_end_of_line(
7511 &mut self,
7512 action: &SelectToEndOfLine,
7513 cx: &mut ViewContext<Self>,
7514 ) {
7515 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7516 s.move_heads_with(|map, head, _| {
7517 (
7518 movement::line_end(map, head, action.stop_at_soft_wraps),
7519 SelectionGoal::None,
7520 )
7521 });
7522 })
7523 }
7524
7525 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7526 self.transact(cx, |this, cx| {
7527 this.select_to_end_of_line(
7528 &SelectToEndOfLine {
7529 stop_at_soft_wraps: false,
7530 },
7531 cx,
7532 );
7533 this.delete(&Delete, cx);
7534 });
7535 }
7536
7537 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7538 self.transact(cx, |this, cx| {
7539 this.select_to_end_of_line(
7540 &SelectToEndOfLine {
7541 stop_at_soft_wraps: false,
7542 },
7543 cx,
7544 );
7545 this.cut(&Cut, cx);
7546 });
7547 }
7548
7549 pub fn move_to_start_of_paragraph(
7550 &mut self,
7551 _: &MoveToStartOfParagraph,
7552 cx: &mut ViewContext<Self>,
7553 ) {
7554 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7555 cx.propagate();
7556 return;
7557 }
7558
7559 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7560 s.move_with(|map, selection| {
7561 selection.collapse_to(
7562 movement::start_of_paragraph(map, selection.head(), 1),
7563 SelectionGoal::None,
7564 )
7565 });
7566 })
7567 }
7568
7569 pub fn move_to_end_of_paragraph(
7570 &mut self,
7571 _: &MoveToEndOfParagraph,
7572 cx: &mut ViewContext<Self>,
7573 ) {
7574 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7575 cx.propagate();
7576 return;
7577 }
7578
7579 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7580 s.move_with(|map, selection| {
7581 selection.collapse_to(
7582 movement::end_of_paragraph(map, selection.head(), 1),
7583 SelectionGoal::None,
7584 )
7585 });
7586 })
7587 }
7588
7589 pub fn select_to_start_of_paragraph(
7590 &mut self,
7591 _: &SelectToStartOfParagraph,
7592 cx: &mut ViewContext<Self>,
7593 ) {
7594 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7595 cx.propagate();
7596 return;
7597 }
7598
7599 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7600 s.move_heads_with(|map, head, _| {
7601 (
7602 movement::start_of_paragraph(map, head, 1),
7603 SelectionGoal::None,
7604 )
7605 });
7606 })
7607 }
7608
7609 pub fn select_to_end_of_paragraph(
7610 &mut self,
7611 _: &SelectToEndOfParagraph,
7612 cx: &mut ViewContext<Self>,
7613 ) {
7614 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7615 cx.propagate();
7616 return;
7617 }
7618
7619 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7620 s.move_heads_with(|map, head, _| {
7621 (
7622 movement::end_of_paragraph(map, head, 1),
7623 SelectionGoal::None,
7624 )
7625 });
7626 })
7627 }
7628
7629 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7630 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7631 cx.propagate();
7632 return;
7633 }
7634
7635 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7636 s.select_ranges(vec![0..0]);
7637 });
7638 }
7639
7640 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7641 let mut selection = self.selections.last::<Point>(cx);
7642 selection.set_head(Point::zero(), SelectionGoal::None);
7643
7644 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7645 s.select(vec![selection]);
7646 });
7647 }
7648
7649 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7650 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7651 cx.propagate();
7652 return;
7653 }
7654
7655 let cursor = self.buffer.read(cx).read(cx).len();
7656 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7657 s.select_ranges(vec![cursor..cursor])
7658 });
7659 }
7660
7661 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7662 self.nav_history = nav_history;
7663 }
7664
7665 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7666 self.nav_history.as_ref()
7667 }
7668
7669 fn push_to_nav_history(
7670 &mut self,
7671 cursor_anchor: Anchor,
7672 new_position: Option<Point>,
7673 cx: &mut ViewContext<Self>,
7674 ) {
7675 if let Some(nav_history) = self.nav_history.as_mut() {
7676 let buffer = self.buffer.read(cx).read(cx);
7677 let cursor_position = cursor_anchor.to_point(&buffer);
7678 let scroll_state = self.scroll_manager.anchor();
7679 let scroll_top_row = scroll_state.top_row(&buffer);
7680 drop(buffer);
7681
7682 if let Some(new_position) = new_position {
7683 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7684 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7685 return;
7686 }
7687 }
7688
7689 nav_history.push(
7690 Some(NavigationData {
7691 cursor_anchor,
7692 cursor_position,
7693 scroll_anchor: scroll_state,
7694 scroll_top_row,
7695 }),
7696 cx,
7697 );
7698 }
7699 }
7700
7701 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7702 let buffer = self.buffer.read(cx).snapshot(cx);
7703 let mut selection = self.selections.first::<usize>(cx);
7704 selection.set_head(buffer.len(), SelectionGoal::None);
7705 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7706 s.select(vec![selection]);
7707 });
7708 }
7709
7710 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7711 let end = self.buffer.read(cx).read(cx).len();
7712 self.change_selections(None, cx, |s| {
7713 s.select_ranges(vec![0..end]);
7714 });
7715 }
7716
7717 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7718 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7719 let mut selections = self.selections.all::<Point>(cx);
7720 let max_point = display_map.buffer_snapshot.max_point();
7721 for selection in &mut selections {
7722 let rows = selection.spanned_rows(true, &display_map);
7723 selection.start = Point::new(rows.start.0, 0);
7724 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7725 selection.reversed = false;
7726 }
7727 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7728 s.select(selections);
7729 });
7730 }
7731
7732 pub fn split_selection_into_lines(
7733 &mut self,
7734 _: &SplitSelectionIntoLines,
7735 cx: &mut ViewContext<Self>,
7736 ) {
7737 let mut to_unfold = Vec::new();
7738 let mut new_selection_ranges = Vec::new();
7739 {
7740 let selections = self.selections.all::<Point>(cx);
7741 let buffer = self.buffer.read(cx).read(cx);
7742 for selection in selections {
7743 for row in selection.start.row..selection.end.row {
7744 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7745 new_selection_ranges.push(cursor..cursor);
7746 }
7747 new_selection_ranges.push(selection.end..selection.end);
7748 to_unfold.push(selection.start..selection.end);
7749 }
7750 }
7751 self.unfold_ranges(to_unfold, true, true, cx);
7752 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7753 s.select_ranges(new_selection_ranges);
7754 });
7755 }
7756
7757 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7758 self.add_selection(true, cx);
7759 }
7760
7761 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7762 self.add_selection(false, cx);
7763 }
7764
7765 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7766 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7767 let mut selections = self.selections.all::<Point>(cx);
7768 let text_layout_details = self.text_layout_details(cx);
7769 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7770 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7771 let range = oldest_selection.display_range(&display_map).sorted();
7772
7773 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7774 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7775 let positions = start_x.min(end_x)..start_x.max(end_x);
7776
7777 selections.clear();
7778 let mut stack = Vec::new();
7779 for row in range.start.row().0..=range.end.row().0 {
7780 if let Some(selection) = self.selections.build_columnar_selection(
7781 &display_map,
7782 DisplayRow(row),
7783 &positions,
7784 oldest_selection.reversed,
7785 &text_layout_details,
7786 ) {
7787 stack.push(selection.id);
7788 selections.push(selection);
7789 }
7790 }
7791
7792 if above {
7793 stack.reverse();
7794 }
7795
7796 AddSelectionsState { above, stack }
7797 });
7798
7799 let last_added_selection = *state.stack.last().unwrap();
7800 let mut new_selections = Vec::new();
7801 if above == state.above {
7802 let end_row = if above {
7803 DisplayRow(0)
7804 } else {
7805 display_map.max_point().row()
7806 };
7807
7808 'outer: for selection in selections {
7809 if selection.id == last_added_selection {
7810 let range = selection.display_range(&display_map).sorted();
7811 debug_assert_eq!(range.start.row(), range.end.row());
7812 let mut row = range.start.row();
7813 let positions =
7814 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7815 px(start)..px(end)
7816 } else {
7817 let start_x =
7818 display_map.x_for_display_point(range.start, &text_layout_details);
7819 let end_x =
7820 display_map.x_for_display_point(range.end, &text_layout_details);
7821 start_x.min(end_x)..start_x.max(end_x)
7822 };
7823
7824 while row != end_row {
7825 if above {
7826 row.0 -= 1;
7827 } else {
7828 row.0 += 1;
7829 }
7830
7831 if let Some(new_selection) = self.selections.build_columnar_selection(
7832 &display_map,
7833 row,
7834 &positions,
7835 selection.reversed,
7836 &text_layout_details,
7837 ) {
7838 state.stack.push(new_selection.id);
7839 if above {
7840 new_selections.push(new_selection);
7841 new_selections.push(selection);
7842 } else {
7843 new_selections.push(selection);
7844 new_selections.push(new_selection);
7845 }
7846
7847 continue 'outer;
7848 }
7849 }
7850 }
7851
7852 new_selections.push(selection);
7853 }
7854 } else {
7855 new_selections = selections;
7856 new_selections.retain(|s| s.id != last_added_selection);
7857 state.stack.pop();
7858 }
7859
7860 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7861 s.select(new_selections);
7862 });
7863 if state.stack.len() > 1 {
7864 self.add_selections_state = Some(state);
7865 }
7866 }
7867
7868 pub fn select_next_match_internal(
7869 &mut self,
7870 display_map: &DisplaySnapshot,
7871 replace_newest: bool,
7872 autoscroll: Option<Autoscroll>,
7873 cx: &mut ViewContext<Self>,
7874 ) -> Result<()> {
7875 fn select_next_match_ranges(
7876 this: &mut Editor,
7877 range: Range<usize>,
7878 replace_newest: bool,
7879 auto_scroll: Option<Autoscroll>,
7880 cx: &mut ViewContext<Editor>,
7881 ) {
7882 this.unfold_ranges([range.clone()], false, true, cx);
7883 this.change_selections(auto_scroll, cx, |s| {
7884 if replace_newest {
7885 s.delete(s.newest_anchor().id);
7886 }
7887 s.insert_range(range.clone());
7888 });
7889 }
7890
7891 let buffer = &display_map.buffer_snapshot;
7892 let mut selections = self.selections.all::<usize>(cx);
7893 if let Some(mut select_next_state) = self.select_next_state.take() {
7894 let query = &select_next_state.query;
7895 if !select_next_state.done {
7896 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7897 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7898 let mut next_selected_range = None;
7899
7900 let bytes_after_last_selection =
7901 buffer.bytes_in_range(last_selection.end..buffer.len());
7902 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
7903 let query_matches = query
7904 .stream_find_iter(bytes_after_last_selection)
7905 .map(|result| (last_selection.end, result))
7906 .chain(
7907 query
7908 .stream_find_iter(bytes_before_first_selection)
7909 .map(|result| (0, result)),
7910 );
7911
7912 for (start_offset, query_match) in query_matches {
7913 let query_match = query_match.unwrap(); // can only fail due to I/O
7914 let offset_range =
7915 start_offset + query_match.start()..start_offset + query_match.end();
7916 let display_range = offset_range.start.to_display_point(display_map)
7917 ..offset_range.end.to_display_point(display_map);
7918
7919 if !select_next_state.wordwise
7920 || (!movement::is_inside_word(display_map, display_range.start)
7921 && !movement::is_inside_word(display_map, display_range.end))
7922 {
7923 // TODO: This is n^2, because we might check all the selections
7924 if !selections
7925 .iter()
7926 .any(|selection| selection.range().overlaps(&offset_range))
7927 {
7928 next_selected_range = Some(offset_range);
7929 break;
7930 }
7931 }
7932 }
7933
7934 if let Some(next_selected_range) = next_selected_range {
7935 select_next_match_ranges(
7936 self,
7937 next_selected_range,
7938 replace_newest,
7939 autoscroll,
7940 cx,
7941 );
7942 } else {
7943 select_next_state.done = true;
7944 }
7945 }
7946
7947 self.select_next_state = Some(select_next_state);
7948 } else {
7949 let mut only_carets = true;
7950 let mut same_text_selected = true;
7951 let mut selected_text = None;
7952
7953 let mut selections_iter = selections.iter().peekable();
7954 while let Some(selection) = selections_iter.next() {
7955 if selection.start != selection.end {
7956 only_carets = false;
7957 }
7958
7959 if same_text_selected {
7960 if selected_text.is_none() {
7961 selected_text =
7962 Some(buffer.text_for_range(selection.range()).collect::<String>());
7963 }
7964
7965 if let Some(next_selection) = selections_iter.peek() {
7966 if next_selection.range().len() == selection.range().len() {
7967 let next_selected_text = buffer
7968 .text_for_range(next_selection.range())
7969 .collect::<String>();
7970 if Some(next_selected_text) != selected_text {
7971 same_text_selected = false;
7972 selected_text = None;
7973 }
7974 } else {
7975 same_text_selected = false;
7976 selected_text = None;
7977 }
7978 }
7979 }
7980 }
7981
7982 if only_carets {
7983 for selection in &mut selections {
7984 let word_range = movement::surrounding_word(
7985 display_map,
7986 selection.start.to_display_point(display_map),
7987 );
7988 selection.start = word_range.start.to_offset(display_map, Bias::Left);
7989 selection.end = word_range.end.to_offset(display_map, Bias::Left);
7990 selection.goal = SelectionGoal::None;
7991 selection.reversed = false;
7992 select_next_match_ranges(
7993 self,
7994 selection.start..selection.end,
7995 replace_newest,
7996 autoscroll,
7997 cx,
7998 );
7999 }
8000
8001 if selections.len() == 1 {
8002 let selection = selections
8003 .last()
8004 .expect("ensured that there's only one selection");
8005 let query = buffer
8006 .text_for_range(selection.start..selection.end)
8007 .collect::<String>();
8008 let is_empty = query.is_empty();
8009 let select_state = SelectNextState {
8010 query: AhoCorasick::new(&[query])?,
8011 wordwise: true,
8012 done: is_empty,
8013 };
8014 self.select_next_state = Some(select_state);
8015 } else {
8016 self.select_next_state = None;
8017 }
8018 } else if let Some(selected_text) = selected_text {
8019 self.select_next_state = Some(SelectNextState {
8020 query: AhoCorasick::new(&[selected_text])?,
8021 wordwise: false,
8022 done: false,
8023 });
8024 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8025 }
8026 }
8027 Ok(())
8028 }
8029
8030 pub fn select_all_matches(
8031 &mut self,
8032 _action: &SelectAllMatches,
8033 cx: &mut ViewContext<Self>,
8034 ) -> Result<()> {
8035 self.push_to_selection_history();
8036 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8037
8038 self.select_next_match_internal(&display_map, false, None, cx)?;
8039 let Some(select_next_state) = self.select_next_state.as_mut() else {
8040 return Ok(());
8041 };
8042 if select_next_state.done {
8043 return Ok(());
8044 }
8045
8046 let mut new_selections = self.selections.all::<usize>(cx);
8047
8048 let buffer = &display_map.buffer_snapshot;
8049 let query_matches = select_next_state
8050 .query
8051 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8052
8053 for query_match in query_matches {
8054 let query_match = query_match.unwrap(); // can only fail due to I/O
8055 let offset_range = query_match.start()..query_match.end();
8056 let display_range = offset_range.start.to_display_point(&display_map)
8057 ..offset_range.end.to_display_point(&display_map);
8058
8059 if !select_next_state.wordwise
8060 || (!movement::is_inside_word(&display_map, display_range.start)
8061 && !movement::is_inside_word(&display_map, display_range.end))
8062 {
8063 self.selections.change_with(cx, |selections| {
8064 new_selections.push(Selection {
8065 id: selections.new_selection_id(),
8066 start: offset_range.start,
8067 end: offset_range.end,
8068 reversed: false,
8069 goal: SelectionGoal::None,
8070 });
8071 });
8072 }
8073 }
8074
8075 new_selections.sort_by_key(|selection| selection.start);
8076 let mut ix = 0;
8077 while ix + 1 < new_selections.len() {
8078 let current_selection = &new_selections[ix];
8079 let next_selection = &new_selections[ix + 1];
8080 if current_selection.range().overlaps(&next_selection.range()) {
8081 if current_selection.id < next_selection.id {
8082 new_selections.remove(ix + 1);
8083 } else {
8084 new_selections.remove(ix);
8085 }
8086 } else {
8087 ix += 1;
8088 }
8089 }
8090
8091 select_next_state.done = true;
8092 self.unfold_ranges(
8093 new_selections.iter().map(|selection| selection.range()),
8094 false,
8095 false,
8096 cx,
8097 );
8098 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8099 selections.select(new_selections)
8100 });
8101
8102 Ok(())
8103 }
8104
8105 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8106 self.push_to_selection_history();
8107 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8108 self.select_next_match_internal(
8109 &display_map,
8110 action.replace_newest,
8111 Some(Autoscroll::newest()),
8112 cx,
8113 )?;
8114 Ok(())
8115 }
8116
8117 pub fn select_previous(
8118 &mut self,
8119 action: &SelectPrevious,
8120 cx: &mut ViewContext<Self>,
8121 ) -> Result<()> {
8122 self.push_to_selection_history();
8123 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8124 let buffer = &display_map.buffer_snapshot;
8125 let mut selections = self.selections.all::<usize>(cx);
8126 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8127 let query = &select_prev_state.query;
8128 if !select_prev_state.done {
8129 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8130 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8131 let mut next_selected_range = None;
8132 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8133 let bytes_before_last_selection =
8134 buffer.reversed_bytes_in_range(0..last_selection.start);
8135 let bytes_after_first_selection =
8136 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8137 let query_matches = query
8138 .stream_find_iter(bytes_before_last_selection)
8139 .map(|result| (last_selection.start, result))
8140 .chain(
8141 query
8142 .stream_find_iter(bytes_after_first_selection)
8143 .map(|result| (buffer.len(), result)),
8144 );
8145 for (end_offset, query_match) in query_matches {
8146 let query_match = query_match.unwrap(); // can only fail due to I/O
8147 let offset_range =
8148 end_offset - query_match.end()..end_offset - query_match.start();
8149 let display_range = offset_range.start.to_display_point(&display_map)
8150 ..offset_range.end.to_display_point(&display_map);
8151
8152 if !select_prev_state.wordwise
8153 || (!movement::is_inside_word(&display_map, display_range.start)
8154 && !movement::is_inside_word(&display_map, display_range.end))
8155 {
8156 next_selected_range = Some(offset_range);
8157 break;
8158 }
8159 }
8160
8161 if let Some(next_selected_range) = next_selected_range {
8162 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8163 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8164 if action.replace_newest {
8165 s.delete(s.newest_anchor().id);
8166 }
8167 s.insert_range(next_selected_range);
8168 });
8169 } else {
8170 select_prev_state.done = true;
8171 }
8172 }
8173
8174 self.select_prev_state = Some(select_prev_state);
8175 } else {
8176 let mut only_carets = true;
8177 let mut same_text_selected = true;
8178 let mut selected_text = None;
8179
8180 let mut selections_iter = selections.iter().peekable();
8181 while let Some(selection) = selections_iter.next() {
8182 if selection.start != selection.end {
8183 only_carets = false;
8184 }
8185
8186 if same_text_selected {
8187 if selected_text.is_none() {
8188 selected_text =
8189 Some(buffer.text_for_range(selection.range()).collect::<String>());
8190 }
8191
8192 if let Some(next_selection) = selections_iter.peek() {
8193 if next_selection.range().len() == selection.range().len() {
8194 let next_selected_text = buffer
8195 .text_for_range(next_selection.range())
8196 .collect::<String>();
8197 if Some(next_selected_text) != selected_text {
8198 same_text_selected = false;
8199 selected_text = None;
8200 }
8201 } else {
8202 same_text_selected = false;
8203 selected_text = None;
8204 }
8205 }
8206 }
8207 }
8208
8209 if only_carets {
8210 for selection in &mut selections {
8211 let word_range = movement::surrounding_word(
8212 &display_map,
8213 selection.start.to_display_point(&display_map),
8214 );
8215 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8216 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8217 selection.goal = SelectionGoal::None;
8218 selection.reversed = false;
8219 }
8220 if selections.len() == 1 {
8221 let selection = selections
8222 .last()
8223 .expect("ensured that there's only one selection");
8224 let query = buffer
8225 .text_for_range(selection.start..selection.end)
8226 .collect::<String>();
8227 let is_empty = query.is_empty();
8228 let select_state = SelectNextState {
8229 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8230 wordwise: true,
8231 done: is_empty,
8232 };
8233 self.select_prev_state = Some(select_state);
8234 } else {
8235 self.select_prev_state = None;
8236 }
8237
8238 self.unfold_ranges(
8239 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8240 false,
8241 true,
8242 cx,
8243 );
8244 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8245 s.select(selections);
8246 });
8247 } else if let Some(selected_text) = selected_text {
8248 self.select_prev_state = Some(SelectNextState {
8249 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8250 wordwise: false,
8251 done: false,
8252 });
8253 self.select_previous(action, cx)?;
8254 }
8255 }
8256 Ok(())
8257 }
8258
8259 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8260 let text_layout_details = &self.text_layout_details(cx);
8261 self.transact(cx, |this, cx| {
8262 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8263 let mut edits = Vec::new();
8264 let mut selection_edit_ranges = Vec::new();
8265 let mut last_toggled_row = None;
8266 let snapshot = this.buffer.read(cx).read(cx);
8267 let empty_str: Arc<str> = Arc::default();
8268 let mut suffixes_inserted = Vec::new();
8269
8270 fn comment_prefix_range(
8271 snapshot: &MultiBufferSnapshot,
8272 row: MultiBufferRow,
8273 comment_prefix: &str,
8274 comment_prefix_whitespace: &str,
8275 ) -> Range<Point> {
8276 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8277
8278 let mut line_bytes = snapshot
8279 .bytes_in_range(start..snapshot.max_point())
8280 .flatten()
8281 .copied();
8282
8283 // If this line currently begins with the line comment prefix, then record
8284 // the range containing the prefix.
8285 if line_bytes
8286 .by_ref()
8287 .take(comment_prefix.len())
8288 .eq(comment_prefix.bytes())
8289 {
8290 // Include any whitespace that matches the comment prefix.
8291 let matching_whitespace_len = line_bytes
8292 .zip(comment_prefix_whitespace.bytes())
8293 .take_while(|(a, b)| a == b)
8294 .count() as u32;
8295 let end = Point::new(
8296 start.row,
8297 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8298 );
8299 start..end
8300 } else {
8301 start..start
8302 }
8303 }
8304
8305 fn comment_suffix_range(
8306 snapshot: &MultiBufferSnapshot,
8307 row: MultiBufferRow,
8308 comment_suffix: &str,
8309 comment_suffix_has_leading_space: bool,
8310 ) -> Range<Point> {
8311 let end = Point::new(row.0, snapshot.line_len(row));
8312 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8313
8314 let mut line_end_bytes = snapshot
8315 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8316 .flatten()
8317 .copied();
8318
8319 let leading_space_len = if suffix_start_column > 0
8320 && line_end_bytes.next() == Some(b' ')
8321 && comment_suffix_has_leading_space
8322 {
8323 1
8324 } else {
8325 0
8326 };
8327
8328 // If this line currently begins with the line comment prefix, then record
8329 // the range containing the prefix.
8330 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8331 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8332 start..end
8333 } else {
8334 end..end
8335 }
8336 }
8337
8338 // TODO: Handle selections that cross excerpts
8339 for selection in &mut selections {
8340 let start_column = snapshot
8341 .indent_size_for_line(MultiBufferRow(selection.start.row))
8342 .len;
8343 let language = if let Some(language) =
8344 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8345 {
8346 language
8347 } else {
8348 continue;
8349 };
8350
8351 selection_edit_ranges.clear();
8352
8353 // If multiple selections contain a given row, avoid processing that
8354 // row more than once.
8355 let mut start_row = MultiBufferRow(selection.start.row);
8356 if last_toggled_row == Some(start_row) {
8357 start_row = start_row.next_row();
8358 }
8359 let end_row =
8360 if selection.end.row > selection.start.row && selection.end.column == 0 {
8361 MultiBufferRow(selection.end.row - 1)
8362 } else {
8363 MultiBufferRow(selection.end.row)
8364 };
8365 last_toggled_row = Some(end_row);
8366
8367 if start_row > end_row {
8368 continue;
8369 }
8370
8371 // If the language has line comments, toggle those.
8372 let full_comment_prefixes = language.line_comment_prefixes();
8373 if !full_comment_prefixes.is_empty() {
8374 let first_prefix = full_comment_prefixes
8375 .first()
8376 .expect("prefixes is non-empty");
8377 let prefix_trimmed_lengths = full_comment_prefixes
8378 .iter()
8379 .map(|p| p.trim_end_matches(' ').len())
8380 .collect::<SmallVec<[usize; 4]>>();
8381
8382 let mut all_selection_lines_are_comments = true;
8383
8384 for row in start_row.0..=end_row.0 {
8385 let row = MultiBufferRow(row);
8386 if start_row < end_row && snapshot.is_line_blank(row) {
8387 continue;
8388 }
8389
8390 let prefix_range = full_comment_prefixes
8391 .iter()
8392 .zip(prefix_trimmed_lengths.iter().copied())
8393 .map(|(prefix, trimmed_prefix_len)| {
8394 comment_prefix_range(
8395 snapshot.deref(),
8396 row,
8397 &prefix[..trimmed_prefix_len],
8398 &prefix[trimmed_prefix_len..],
8399 )
8400 })
8401 .max_by_key(|range| range.end.column - range.start.column)
8402 .expect("prefixes is non-empty");
8403
8404 if prefix_range.is_empty() {
8405 all_selection_lines_are_comments = false;
8406 }
8407
8408 selection_edit_ranges.push(prefix_range);
8409 }
8410
8411 if all_selection_lines_are_comments {
8412 edits.extend(
8413 selection_edit_ranges
8414 .iter()
8415 .cloned()
8416 .map(|range| (range, empty_str.clone())),
8417 );
8418 } else {
8419 let min_column = selection_edit_ranges
8420 .iter()
8421 .map(|range| range.start.column)
8422 .min()
8423 .unwrap_or(0);
8424 edits.extend(selection_edit_ranges.iter().map(|range| {
8425 let position = Point::new(range.start.row, min_column);
8426 (position..position, first_prefix.clone())
8427 }));
8428 }
8429 } else if let Some((full_comment_prefix, comment_suffix)) =
8430 language.block_comment_delimiters()
8431 {
8432 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8433 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8434 let prefix_range = comment_prefix_range(
8435 snapshot.deref(),
8436 start_row,
8437 comment_prefix,
8438 comment_prefix_whitespace,
8439 );
8440 let suffix_range = comment_suffix_range(
8441 snapshot.deref(),
8442 end_row,
8443 comment_suffix.trim_start_matches(' '),
8444 comment_suffix.starts_with(' '),
8445 );
8446
8447 if prefix_range.is_empty() || suffix_range.is_empty() {
8448 edits.push((
8449 prefix_range.start..prefix_range.start,
8450 full_comment_prefix.clone(),
8451 ));
8452 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8453 suffixes_inserted.push((end_row, comment_suffix.len()));
8454 } else {
8455 edits.push((prefix_range, empty_str.clone()));
8456 edits.push((suffix_range, empty_str.clone()));
8457 }
8458 } else {
8459 continue;
8460 }
8461 }
8462
8463 drop(snapshot);
8464 this.buffer.update(cx, |buffer, cx| {
8465 buffer.edit(edits, None, cx);
8466 });
8467
8468 // Adjust selections so that they end before any comment suffixes that
8469 // were inserted.
8470 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8471 let mut selections = this.selections.all::<Point>(cx);
8472 let snapshot = this.buffer.read(cx).read(cx);
8473 for selection in &mut selections {
8474 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8475 match row.cmp(&MultiBufferRow(selection.end.row)) {
8476 Ordering::Less => {
8477 suffixes_inserted.next();
8478 continue;
8479 }
8480 Ordering::Greater => break,
8481 Ordering::Equal => {
8482 if selection.end.column == snapshot.line_len(row) {
8483 if selection.is_empty() {
8484 selection.start.column -= suffix_len as u32;
8485 }
8486 selection.end.column -= suffix_len as u32;
8487 }
8488 break;
8489 }
8490 }
8491 }
8492 }
8493
8494 drop(snapshot);
8495 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8496
8497 let selections = this.selections.all::<Point>(cx);
8498 let selections_on_single_row = selections.windows(2).all(|selections| {
8499 selections[0].start.row == selections[1].start.row
8500 && selections[0].end.row == selections[1].end.row
8501 && selections[0].start.row == selections[0].end.row
8502 });
8503 let selections_selecting = selections
8504 .iter()
8505 .any(|selection| selection.start != selection.end);
8506 let advance_downwards = action.advance_downwards
8507 && selections_on_single_row
8508 && !selections_selecting
8509 && !matches!(this.mode, EditorMode::SingleLine { .. });
8510
8511 if advance_downwards {
8512 let snapshot = this.buffer.read(cx).snapshot(cx);
8513
8514 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8515 s.move_cursors_with(|display_snapshot, display_point, _| {
8516 let mut point = display_point.to_point(display_snapshot);
8517 point.row += 1;
8518 point = snapshot.clip_point(point, Bias::Left);
8519 let display_point = point.to_display_point(display_snapshot);
8520 let goal = SelectionGoal::HorizontalPosition(
8521 display_snapshot
8522 .x_for_display_point(display_point, text_layout_details)
8523 .into(),
8524 );
8525 (display_point, goal)
8526 })
8527 });
8528 }
8529 });
8530 }
8531
8532 pub fn select_enclosing_symbol(
8533 &mut self,
8534 _: &SelectEnclosingSymbol,
8535 cx: &mut ViewContext<Self>,
8536 ) {
8537 let buffer = self.buffer.read(cx).snapshot(cx);
8538 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8539
8540 fn update_selection(
8541 selection: &Selection<usize>,
8542 buffer_snap: &MultiBufferSnapshot,
8543 ) -> Option<Selection<usize>> {
8544 let cursor = selection.head();
8545 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8546 for symbol in symbols.iter().rev() {
8547 let start = symbol.range.start.to_offset(buffer_snap);
8548 let end = symbol.range.end.to_offset(buffer_snap);
8549 let new_range = start..end;
8550 if start < selection.start || end > selection.end {
8551 return Some(Selection {
8552 id: selection.id,
8553 start: new_range.start,
8554 end: new_range.end,
8555 goal: SelectionGoal::None,
8556 reversed: selection.reversed,
8557 });
8558 }
8559 }
8560 None
8561 }
8562
8563 let mut selected_larger_symbol = false;
8564 let new_selections = old_selections
8565 .iter()
8566 .map(|selection| match update_selection(selection, &buffer) {
8567 Some(new_selection) => {
8568 if new_selection.range() != selection.range() {
8569 selected_larger_symbol = true;
8570 }
8571 new_selection
8572 }
8573 None => selection.clone(),
8574 })
8575 .collect::<Vec<_>>();
8576
8577 if selected_larger_symbol {
8578 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8579 s.select(new_selections);
8580 });
8581 }
8582 }
8583
8584 pub fn select_larger_syntax_node(
8585 &mut self,
8586 _: &SelectLargerSyntaxNode,
8587 cx: &mut ViewContext<Self>,
8588 ) {
8589 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8590 let buffer = self.buffer.read(cx).snapshot(cx);
8591 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8592
8593 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8594 let mut selected_larger_node = false;
8595 let new_selections = old_selections
8596 .iter()
8597 .map(|selection| {
8598 let old_range = selection.start..selection.end;
8599 let mut new_range = old_range.clone();
8600 while let Some(containing_range) =
8601 buffer.range_for_syntax_ancestor(new_range.clone())
8602 {
8603 new_range = containing_range;
8604 if !display_map.intersects_fold(new_range.start)
8605 && !display_map.intersects_fold(new_range.end)
8606 {
8607 break;
8608 }
8609 }
8610
8611 selected_larger_node |= new_range != old_range;
8612 Selection {
8613 id: selection.id,
8614 start: new_range.start,
8615 end: new_range.end,
8616 goal: SelectionGoal::None,
8617 reversed: selection.reversed,
8618 }
8619 })
8620 .collect::<Vec<_>>();
8621
8622 if selected_larger_node {
8623 stack.push(old_selections);
8624 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8625 s.select(new_selections);
8626 });
8627 }
8628 self.select_larger_syntax_node_stack = stack;
8629 }
8630
8631 pub fn select_smaller_syntax_node(
8632 &mut self,
8633 _: &SelectSmallerSyntaxNode,
8634 cx: &mut ViewContext<Self>,
8635 ) {
8636 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8637 if let Some(selections) = stack.pop() {
8638 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8639 s.select(selections.to_vec());
8640 });
8641 }
8642 self.select_larger_syntax_node_stack = stack;
8643 }
8644
8645 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8646 if !EditorSettings::get_global(cx).gutter.runnables {
8647 self.clear_tasks();
8648 return Task::ready(());
8649 }
8650 let project = self.project.clone();
8651 cx.spawn(|this, mut cx| async move {
8652 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8653 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8654 }) else {
8655 return;
8656 };
8657
8658 let Some(project) = project else {
8659 return;
8660 };
8661
8662 let hide_runnables = project
8663 .update(&mut cx, |project, cx| {
8664 // Do not display any test indicators in non-dev server remote projects.
8665 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8666 })
8667 .unwrap_or(true);
8668 if hide_runnables {
8669 return;
8670 }
8671 let new_rows =
8672 cx.background_executor()
8673 .spawn({
8674 let snapshot = display_snapshot.clone();
8675 async move {
8676 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8677 }
8678 })
8679 .await;
8680 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8681
8682 this.update(&mut cx, |this, _| {
8683 this.clear_tasks();
8684 for (key, value) in rows {
8685 this.insert_tasks(key, value);
8686 }
8687 })
8688 .ok();
8689 })
8690 }
8691 fn fetch_runnable_ranges(
8692 snapshot: &DisplaySnapshot,
8693 range: Range<Anchor>,
8694 ) -> Vec<language::RunnableRange> {
8695 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8696 }
8697
8698 fn runnable_rows(
8699 project: Model<Project>,
8700 snapshot: DisplaySnapshot,
8701 runnable_ranges: Vec<RunnableRange>,
8702 mut cx: AsyncWindowContext,
8703 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8704 runnable_ranges
8705 .into_iter()
8706 .filter_map(|mut runnable| {
8707 let tasks = cx
8708 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8709 .ok()?;
8710 if tasks.is_empty() {
8711 return None;
8712 }
8713
8714 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8715
8716 let row = snapshot
8717 .buffer_snapshot
8718 .buffer_line_for_row(MultiBufferRow(point.row))?
8719 .1
8720 .start
8721 .row;
8722
8723 let context_range =
8724 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8725 Some((
8726 (runnable.buffer_id, row),
8727 RunnableTasks {
8728 templates: tasks,
8729 offset: MultiBufferOffset(runnable.run_range.start),
8730 context_range,
8731 column: point.column,
8732 extra_variables: runnable.extra_captures,
8733 },
8734 ))
8735 })
8736 .collect()
8737 }
8738
8739 fn templates_with_tags(
8740 project: &Model<Project>,
8741 runnable: &mut Runnable,
8742 cx: &WindowContext<'_>,
8743 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8744 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8745 let (worktree_id, file) = project
8746 .buffer_for_id(runnable.buffer, cx)
8747 .and_then(|buffer| buffer.read(cx).file())
8748 .map(|file| (file.worktree_id(cx), file.clone()))
8749 .unzip();
8750
8751 (project.task_inventory().clone(), worktree_id, file)
8752 });
8753
8754 let inventory = inventory.read(cx);
8755 let tags = mem::take(&mut runnable.tags);
8756 let mut tags: Vec<_> = tags
8757 .into_iter()
8758 .flat_map(|tag| {
8759 let tag = tag.0.clone();
8760 inventory
8761 .list_tasks(
8762 file.clone(),
8763 Some(runnable.language.clone()),
8764 worktree_id,
8765 cx,
8766 )
8767 .into_iter()
8768 .filter(move |(_, template)| {
8769 template.tags.iter().any(|source_tag| source_tag == &tag)
8770 })
8771 })
8772 .sorted_by_key(|(kind, _)| kind.to_owned())
8773 .collect();
8774 if let Some((leading_tag_source, _)) = tags.first() {
8775 // Strongest source wins; if we have worktree tag binding, prefer that to
8776 // global and language bindings;
8777 // if we have a global binding, prefer that to language binding.
8778 let first_mismatch = tags
8779 .iter()
8780 .position(|(tag_source, _)| tag_source != leading_tag_source);
8781 if let Some(index) = first_mismatch {
8782 tags.truncate(index);
8783 }
8784 }
8785
8786 tags
8787 }
8788
8789 pub fn move_to_enclosing_bracket(
8790 &mut self,
8791 _: &MoveToEnclosingBracket,
8792 cx: &mut ViewContext<Self>,
8793 ) {
8794 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8795 s.move_offsets_with(|snapshot, selection| {
8796 let Some(enclosing_bracket_ranges) =
8797 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
8798 else {
8799 return;
8800 };
8801
8802 let mut best_length = usize::MAX;
8803 let mut best_inside = false;
8804 let mut best_in_bracket_range = false;
8805 let mut best_destination = None;
8806 for (open, close) in enclosing_bracket_ranges {
8807 let close = close.to_inclusive();
8808 let length = close.end() - open.start;
8809 let inside = selection.start >= open.end && selection.end <= *close.start();
8810 let in_bracket_range = open.to_inclusive().contains(&selection.head())
8811 || close.contains(&selection.head());
8812
8813 // If best is next to a bracket and current isn't, skip
8814 if !in_bracket_range && best_in_bracket_range {
8815 continue;
8816 }
8817
8818 // Prefer smaller lengths unless best is inside and current isn't
8819 if length > best_length && (best_inside || !inside) {
8820 continue;
8821 }
8822
8823 best_length = length;
8824 best_inside = inside;
8825 best_in_bracket_range = in_bracket_range;
8826 best_destination = Some(
8827 if close.contains(&selection.start) && close.contains(&selection.end) {
8828 if inside {
8829 open.end
8830 } else {
8831 open.start
8832 }
8833 } else if inside {
8834 *close.start()
8835 } else {
8836 *close.end()
8837 },
8838 );
8839 }
8840
8841 if let Some(destination) = best_destination {
8842 selection.collapse_to(destination, SelectionGoal::None);
8843 }
8844 })
8845 });
8846 }
8847
8848 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
8849 self.end_selection(cx);
8850 self.selection_history.mode = SelectionHistoryMode::Undoing;
8851 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
8852 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8853 self.select_next_state = entry.select_next_state;
8854 self.select_prev_state = entry.select_prev_state;
8855 self.add_selections_state = entry.add_selections_state;
8856 self.request_autoscroll(Autoscroll::newest(), cx);
8857 }
8858 self.selection_history.mode = SelectionHistoryMode::Normal;
8859 }
8860
8861 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
8862 self.end_selection(cx);
8863 self.selection_history.mode = SelectionHistoryMode::Redoing;
8864 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
8865 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8866 self.select_next_state = entry.select_next_state;
8867 self.select_prev_state = entry.select_prev_state;
8868 self.add_selections_state = entry.add_selections_state;
8869 self.request_autoscroll(Autoscroll::newest(), cx);
8870 }
8871 self.selection_history.mode = SelectionHistoryMode::Normal;
8872 }
8873
8874 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
8875 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
8876 }
8877
8878 pub fn expand_excerpts_down(
8879 &mut self,
8880 action: &ExpandExcerptsDown,
8881 cx: &mut ViewContext<Self>,
8882 ) {
8883 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
8884 }
8885
8886 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
8887 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
8888 }
8889
8890 pub fn expand_excerpts_for_direction(
8891 &mut self,
8892 lines: u32,
8893 direction: ExpandExcerptDirection,
8894 cx: &mut ViewContext<Self>,
8895 ) {
8896 let selections = self.selections.disjoint_anchors();
8897
8898 let lines = if lines == 0 {
8899 EditorSettings::get_global(cx).expand_excerpt_lines
8900 } else {
8901 lines
8902 };
8903
8904 self.buffer.update(cx, |buffer, cx| {
8905 buffer.expand_excerpts(
8906 selections
8907 .iter()
8908 .map(|selection| selection.head().excerpt_id)
8909 .dedup(),
8910 lines,
8911 direction,
8912 cx,
8913 )
8914 })
8915 }
8916
8917 pub fn expand_excerpt(
8918 &mut self,
8919 excerpt: ExcerptId,
8920 direction: ExpandExcerptDirection,
8921 cx: &mut ViewContext<Self>,
8922 ) {
8923 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
8924 self.buffer.update(cx, |buffer, cx| {
8925 buffer.expand_excerpts([excerpt], lines, direction, cx)
8926 })
8927 }
8928
8929 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
8930 self.go_to_diagnostic_impl(Direction::Next, cx)
8931 }
8932
8933 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
8934 self.go_to_diagnostic_impl(Direction::Prev, cx)
8935 }
8936
8937 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
8938 let buffer = self.buffer.read(cx).snapshot(cx);
8939 let selection = self.selections.newest::<usize>(cx);
8940
8941 // If there is an active Diagnostic Popover jump to its diagnostic instead.
8942 if direction == Direction::Next {
8943 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
8944 let (group_id, jump_to) = popover.activation_info();
8945 if self.activate_diagnostics(group_id, cx) {
8946 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8947 let mut new_selection = s.newest_anchor().clone();
8948 new_selection.collapse_to(jump_to, SelectionGoal::None);
8949 s.select_anchors(vec![new_selection.clone()]);
8950 });
8951 }
8952 return;
8953 }
8954 }
8955
8956 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
8957 active_diagnostics
8958 .primary_range
8959 .to_offset(&buffer)
8960 .to_inclusive()
8961 });
8962 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
8963 if active_primary_range.contains(&selection.head()) {
8964 *active_primary_range.start()
8965 } else {
8966 selection.head()
8967 }
8968 } else {
8969 selection.head()
8970 };
8971 let snapshot = self.snapshot(cx);
8972 loop {
8973 let diagnostics = if direction == Direction::Prev {
8974 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
8975 } else {
8976 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
8977 }
8978 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
8979 let group = diagnostics
8980 // relies on diagnostics_in_range to return diagnostics with the same starting range to
8981 // be sorted in a stable way
8982 // skip until we are at current active diagnostic, if it exists
8983 .skip_while(|entry| {
8984 (match direction {
8985 Direction::Prev => entry.range.start >= search_start,
8986 Direction::Next => entry.range.start <= search_start,
8987 }) && self
8988 .active_diagnostics
8989 .as_ref()
8990 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
8991 })
8992 .find_map(|entry| {
8993 if entry.diagnostic.is_primary
8994 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
8995 && !entry.range.is_empty()
8996 // if we match with the active diagnostic, skip it
8997 && Some(entry.diagnostic.group_id)
8998 != self.active_diagnostics.as_ref().map(|d| d.group_id)
8999 {
9000 Some((entry.range, entry.diagnostic.group_id))
9001 } else {
9002 None
9003 }
9004 });
9005
9006 if let Some((primary_range, group_id)) = group {
9007 if self.activate_diagnostics(group_id, cx) {
9008 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9009 s.select(vec![Selection {
9010 id: selection.id,
9011 start: primary_range.start,
9012 end: primary_range.start,
9013 reversed: false,
9014 goal: SelectionGoal::None,
9015 }]);
9016 });
9017 }
9018 break;
9019 } else {
9020 // Cycle around to the start of the buffer, potentially moving back to the start of
9021 // the currently active diagnostic.
9022 active_primary_range.take();
9023 if direction == Direction::Prev {
9024 if search_start == buffer.len() {
9025 break;
9026 } else {
9027 search_start = buffer.len();
9028 }
9029 } else if search_start == 0 {
9030 break;
9031 } else {
9032 search_start = 0;
9033 }
9034 }
9035 }
9036 }
9037
9038 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9039 let snapshot = self
9040 .display_map
9041 .update(cx, |display_map, cx| display_map.snapshot(cx));
9042 let selection = self.selections.newest::<Point>(cx);
9043
9044 if !self.seek_in_direction(
9045 &snapshot,
9046 selection.head(),
9047 false,
9048 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9049 MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
9050 ),
9051 cx,
9052 ) {
9053 let wrapped_point = Point::zero();
9054 self.seek_in_direction(
9055 &snapshot,
9056 wrapped_point,
9057 true,
9058 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9059 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9060 ),
9061 cx,
9062 );
9063 }
9064 }
9065
9066 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9067 let snapshot = self
9068 .display_map
9069 .update(cx, |display_map, cx| display_map.snapshot(cx));
9070 let selection = self.selections.newest::<Point>(cx);
9071
9072 if !self.seek_in_direction(
9073 &snapshot,
9074 selection.head(),
9075 false,
9076 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9077 MultiBufferRow(0)..MultiBufferRow(selection.head().row),
9078 ),
9079 cx,
9080 ) {
9081 let wrapped_point = snapshot.buffer_snapshot.max_point();
9082 self.seek_in_direction(
9083 &snapshot,
9084 wrapped_point,
9085 true,
9086 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9087 MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
9088 ),
9089 cx,
9090 );
9091 }
9092 }
9093
9094 fn seek_in_direction(
9095 &mut self,
9096 snapshot: &DisplaySnapshot,
9097 initial_point: Point,
9098 is_wrapped: bool,
9099 hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
9100 cx: &mut ViewContext<Editor>,
9101 ) -> bool {
9102 let display_point = initial_point.to_display_point(snapshot);
9103 let mut hunks = hunks
9104 .map(|hunk| diff_hunk_to_display(&hunk, snapshot))
9105 .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
9106 .dedup();
9107
9108 if let Some(hunk) = hunks.next() {
9109 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9110 let row = hunk.start_display_row();
9111 let point = DisplayPoint::new(row, 0);
9112 s.select_display_ranges([point..point]);
9113 });
9114
9115 true
9116 } else {
9117 false
9118 }
9119 }
9120
9121 pub fn go_to_definition(
9122 &mut self,
9123 _: &GoToDefinition,
9124 cx: &mut ViewContext<Self>,
9125 ) -> Task<Result<Navigated>> {
9126 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9127 cx.spawn(|editor, mut cx| async move {
9128 if definition.await? == Navigated::Yes {
9129 return Ok(Navigated::Yes);
9130 }
9131 match editor.update(&mut cx, |editor, cx| {
9132 editor.find_all_references(&FindAllReferences, cx)
9133 })? {
9134 Some(references) => references.await,
9135 None => Ok(Navigated::No),
9136 }
9137 })
9138 }
9139
9140 pub fn go_to_declaration(
9141 &mut self,
9142 _: &GoToDeclaration,
9143 cx: &mut ViewContext<Self>,
9144 ) -> Task<Result<Navigated>> {
9145 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9146 }
9147
9148 pub fn go_to_declaration_split(
9149 &mut self,
9150 _: &GoToDeclaration,
9151 cx: &mut ViewContext<Self>,
9152 ) -> Task<Result<Navigated>> {
9153 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9154 }
9155
9156 pub fn go_to_implementation(
9157 &mut self,
9158 _: &GoToImplementation,
9159 cx: &mut ViewContext<Self>,
9160 ) -> Task<Result<Navigated>> {
9161 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9162 }
9163
9164 pub fn go_to_implementation_split(
9165 &mut self,
9166 _: &GoToImplementationSplit,
9167 cx: &mut ViewContext<Self>,
9168 ) -> Task<Result<Navigated>> {
9169 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9170 }
9171
9172 pub fn go_to_type_definition(
9173 &mut self,
9174 _: &GoToTypeDefinition,
9175 cx: &mut ViewContext<Self>,
9176 ) -> Task<Result<Navigated>> {
9177 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9178 }
9179
9180 pub fn go_to_definition_split(
9181 &mut self,
9182 _: &GoToDefinitionSplit,
9183 cx: &mut ViewContext<Self>,
9184 ) -> Task<Result<Navigated>> {
9185 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9186 }
9187
9188 pub fn go_to_type_definition_split(
9189 &mut self,
9190 _: &GoToTypeDefinitionSplit,
9191 cx: &mut ViewContext<Self>,
9192 ) -> Task<Result<Navigated>> {
9193 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9194 }
9195
9196 fn go_to_definition_of_kind(
9197 &mut self,
9198 kind: GotoDefinitionKind,
9199 split: bool,
9200 cx: &mut ViewContext<Self>,
9201 ) -> Task<Result<Navigated>> {
9202 let Some(workspace) = self.workspace() else {
9203 return Task::ready(Ok(Navigated::No));
9204 };
9205 let buffer = self.buffer.read(cx);
9206 let head = self.selections.newest::<usize>(cx).head();
9207 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9208 text_anchor
9209 } else {
9210 return Task::ready(Ok(Navigated::No));
9211 };
9212
9213 let project = workspace.read(cx).project().clone();
9214 let definitions = project.update(cx, |project, cx| match kind {
9215 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
9216 GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
9217 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
9218 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
9219 });
9220
9221 cx.spawn(|editor, mut cx| async move {
9222 let definitions = definitions.await?;
9223 let navigated = editor
9224 .update(&mut cx, |editor, cx| {
9225 editor.navigate_to_hover_links(
9226 Some(kind),
9227 definitions
9228 .into_iter()
9229 .filter(|location| {
9230 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9231 })
9232 .map(HoverLink::Text)
9233 .collect::<Vec<_>>(),
9234 split,
9235 cx,
9236 )
9237 })?
9238 .await?;
9239 anyhow::Ok(navigated)
9240 })
9241 }
9242
9243 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9244 let position = self.selections.newest_anchor().head();
9245 let Some((buffer, buffer_position)) =
9246 self.buffer.read(cx).text_anchor_for_position(position, cx)
9247 else {
9248 return;
9249 };
9250
9251 cx.spawn(|editor, mut cx| async move {
9252 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9253 editor.update(&mut cx, |_, cx| {
9254 cx.open_url(&url);
9255 })
9256 } else {
9257 Ok(())
9258 }
9259 })
9260 .detach();
9261 }
9262
9263 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9264 let Some(workspace) = self.workspace() else {
9265 return;
9266 };
9267
9268 let position = self.selections.newest_anchor().head();
9269
9270 let Some((buffer, buffer_position)) =
9271 self.buffer.read(cx).text_anchor_for_position(position, cx)
9272 else {
9273 return;
9274 };
9275
9276 let Some(project) = self.project.clone() else {
9277 return;
9278 };
9279
9280 cx.spawn(|_, mut cx| async move {
9281 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9282
9283 if let Some((_, path)) = result {
9284 workspace
9285 .update(&mut cx, |workspace, cx| {
9286 workspace.open_resolved_path(path, cx)
9287 })?
9288 .await?;
9289 }
9290 anyhow::Ok(())
9291 })
9292 .detach();
9293 }
9294
9295 pub(crate) fn navigate_to_hover_links(
9296 &mut self,
9297 kind: Option<GotoDefinitionKind>,
9298 mut definitions: Vec<HoverLink>,
9299 split: bool,
9300 cx: &mut ViewContext<Editor>,
9301 ) -> Task<Result<Navigated>> {
9302 // If there is one definition, just open it directly
9303 if definitions.len() == 1 {
9304 let definition = definitions.pop().unwrap();
9305
9306 enum TargetTaskResult {
9307 Location(Option<Location>),
9308 AlreadyNavigated,
9309 }
9310
9311 let target_task = match definition {
9312 HoverLink::Text(link) => {
9313 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9314 }
9315 HoverLink::InlayHint(lsp_location, server_id) => {
9316 let computation = self.compute_target_location(lsp_location, server_id, cx);
9317 cx.background_executor().spawn(async move {
9318 let location = computation.await?;
9319 Ok(TargetTaskResult::Location(location))
9320 })
9321 }
9322 HoverLink::Url(url) => {
9323 cx.open_url(&url);
9324 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9325 }
9326 HoverLink::File(path) => {
9327 if let Some(workspace) = self.workspace() {
9328 cx.spawn(|_, mut cx| async move {
9329 workspace
9330 .update(&mut cx, |workspace, cx| {
9331 workspace.open_resolved_path(path, cx)
9332 })?
9333 .await
9334 .map(|_| TargetTaskResult::AlreadyNavigated)
9335 })
9336 } else {
9337 Task::ready(Ok(TargetTaskResult::Location(None)))
9338 }
9339 }
9340 };
9341 cx.spawn(|editor, mut cx| async move {
9342 let target = match target_task.await.context("target resolution task")? {
9343 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9344 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9345 TargetTaskResult::Location(Some(target)) => target,
9346 };
9347
9348 editor.update(&mut cx, |editor, cx| {
9349 let Some(workspace) = editor.workspace() else {
9350 return Navigated::No;
9351 };
9352 let pane = workspace.read(cx).active_pane().clone();
9353
9354 let range = target.range.to_offset(target.buffer.read(cx));
9355 let range = editor.range_for_match(&range);
9356
9357 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9358 let buffer = target.buffer.read(cx);
9359 let range = check_multiline_range(buffer, range);
9360 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
9361 s.select_ranges([range]);
9362 });
9363 } else {
9364 cx.window_context().defer(move |cx| {
9365 let target_editor: View<Self> =
9366 workspace.update(cx, |workspace, cx| {
9367 let pane = if split {
9368 workspace.adjacent_pane(cx)
9369 } else {
9370 workspace.active_pane().clone()
9371 };
9372
9373 workspace.open_project_item(
9374 pane,
9375 target.buffer.clone(),
9376 true,
9377 true,
9378 cx,
9379 )
9380 });
9381 target_editor.update(cx, |target_editor, cx| {
9382 // When selecting a definition in a different buffer, disable the nav history
9383 // to avoid creating a history entry at the previous cursor location.
9384 pane.update(cx, |pane, _| pane.disable_history());
9385 let buffer = target.buffer.read(cx);
9386 let range = check_multiline_range(buffer, range);
9387 target_editor.change_selections(
9388 Some(Autoscroll::focused()),
9389 cx,
9390 |s| {
9391 s.select_ranges([range]);
9392 },
9393 );
9394 pane.update(cx, |pane, _| pane.enable_history());
9395 });
9396 });
9397 }
9398 Navigated::Yes
9399 })
9400 })
9401 } else if !definitions.is_empty() {
9402 let replica_id = self.replica_id(cx);
9403 cx.spawn(|editor, mut cx| async move {
9404 let (title, location_tasks, workspace) = editor
9405 .update(&mut cx, |editor, cx| {
9406 let tab_kind = match kind {
9407 Some(GotoDefinitionKind::Implementation) => "Implementations",
9408 _ => "Definitions",
9409 };
9410 let title = definitions
9411 .iter()
9412 .find_map(|definition| match definition {
9413 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9414 let buffer = origin.buffer.read(cx);
9415 format!(
9416 "{} for {}",
9417 tab_kind,
9418 buffer
9419 .text_for_range(origin.range.clone())
9420 .collect::<String>()
9421 )
9422 }),
9423 HoverLink::InlayHint(_, _) => None,
9424 HoverLink::Url(_) => None,
9425 HoverLink::File(_) => None,
9426 })
9427 .unwrap_or(tab_kind.to_string());
9428 let location_tasks = definitions
9429 .into_iter()
9430 .map(|definition| match definition {
9431 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9432 HoverLink::InlayHint(lsp_location, server_id) => {
9433 editor.compute_target_location(lsp_location, server_id, cx)
9434 }
9435 HoverLink::Url(_) => Task::ready(Ok(None)),
9436 HoverLink::File(_) => Task::ready(Ok(None)),
9437 })
9438 .collect::<Vec<_>>();
9439 (title, location_tasks, editor.workspace().clone())
9440 })
9441 .context("location tasks preparation")?;
9442
9443 let locations = futures::future::join_all(location_tasks)
9444 .await
9445 .into_iter()
9446 .filter_map(|location| location.transpose())
9447 .collect::<Result<_>>()
9448 .context("location tasks")?;
9449
9450 let Some(workspace) = workspace else {
9451 return Ok(Navigated::No);
9452 };
9453 let opened = workspace
9454 .update(&mut cx, |workspace, cx| {
9455 Self::open_locations_in_multibuffer(
9456 workspace, locations, replica_id, title, split, cx,
9457 )
9458 })
9459 .ok();
9460
9461 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9462 })
9463 } else {
9464 Task::ready(Ok(Navigated::No))
9465 }
9466 }
9467
9468 fn compute_target_location(
9469 &self,
9470 lsp_location: lsp::Location,
9471 server_id: LanguageServerId,
9472 cx: &mut ViewContext<Editor>,
9473 ) -> Task<anyhow::Result<Option<Location>>> {
9474 let Some(project) = self.project.clone() else {
9475 return Task::Ready(Some(Ok(None)));
9476 };
9477
9478 cx.spawn(move |editor, mut cx| async move {
9479 let location_task = editor.update(&mut cx, |editor, cx| {
9480 project.update(cx, |project, cx| {
9481 let language_server_name =
9482 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9483 project
9484 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9485 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9486 });
9487 language_server_name.map(|language_server_name| {
9488 project.open_local_buffer_via_lsp(
9489 lsp_location.uri.clone(),
9490 server_id,
9491 language_server_name,
9492 cx,
9493 )
9494 })
9495 })
9496 })?;
9497 let location = match location_task {
9498 Some(task) => Some({
9499 let target_buffer_handle = task.await.context("open local buffer")?;
9500 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9501 let target_start = target_buffer
9502 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9503 let target_end = target_buffer
9504 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9505 target_buffer.anchor_after(target_start)
9506 ..target_buffer.anchor_before(target_end)
9507 })?;
9508 Location {
9509 buffer: target_buffer_handle,
9510 range,
9511 }
9512 }),
9513 None => None,
9514 };
9515 Ok(location)
9516 })
9517 }
9518
9519 pub fn find_all_references(
9520 &mut self,
9521 _: &FindAllReferences,
9522 cx: &mut ViewContext<Self>,
9523 ) -> Option<Task<Result<Navigated>>> {
9524 let multi_buffer = self.buffer.read(cx);
9525 let selection = self.selections.newest::<usize>(cx);
9526 let head = selection.head();
9527
9528 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9529 let head_anchor = multi_buffer_snapshot.anchor_at(
9530 head,
9531 if head < selection.tail() {
9532 Bias::Right
9533 } else {
9534 Bias::Left
9535 },
9536 );
9537
9538 match self
9539 .find_all_references_task_sources
9540 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9541 {
9542 Ok(_) => {
9543 log::info!(
9544 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9545 );
9546 return None;
9547 }
9548 Err(i) => {
9549 self.find_all_references_task_sources.insert(i, head_anchor);
9550 }
9551 }
9552
9553 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9554 let replica_id = self.replica_id(cx);
9555 let workspace = self.workspace()?;
9556 let project = workspace.read(cx).project().clone();
9557 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9558 Some(cx.spawn(|editor, mut cx| async move {
9559 let _cleanup = defer({
9560 let mut cx = cx.clone();
9561 move || {
9562 let _ = editor.update(&mut cx, |editor, _| {
9563 if let Ok(i) =
9564 editor
9565 .find_all_references_task_sources
9566 .binary_search_by(|anchor| {
9567 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9568 })
9569 {
9570 editor.find_all_references_task_sources.remove(i);
9571 }
9572 });
9573 }
9574 });
9575
9576 let locations = references.await?;
9577 if locations.is_empty() {
9578 return anyhow::Ok(Navigated::No);
9579 }
9580
9581 workspace.update(&mut cx, |workspace, cx| {
9582 let title = locations
9583 .first()
9584 .as_ref()
9585 .map(|location| {
9586 let buffer = location.buffer.read(cx);
9587 format!(
9588 "References to `{}`",
9589 buffer
9590 .text_for_range(location.range.clone())
9591 .collect::<String>()
9592 )
9593 })
9594 .unwrap();
9595 Self::open_locations_in_multibuffer(
9596 workspace, locations, replica_id, title, false, cx,
9597 );
9598 Navigated::Yes
9599 })
9600 }))
9601 }
9602
9603 /// Opens a multibuffer with the given project locations in it
9604 pub fn open_locations_in_multibuffer(
9605 workspace: &mut Workspace,
9606 mut locations: Vec<Location>,
9607 replica_id: ReplicaId,
9608 title: String,
9609 split: bool,
9610 cx: &mut ViewContext<Workspace>,
9611 ) {
9612 // If there are multiple definitions, open them in a multibuffer
9613 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9614 let mut locations = locations.into_iter().peekable();
9615 let mut ranges_to_highlight = Vec::new();
9616 let capability = workspace.project().read(cx).capability();
9617
9618 let excerpt_buffer = cx.new_model(|cx| {
9619 let mut multibuffer = MultiBuffer::new(replica_id, capability);
9620 while let Some(location) = locations.next() {
9621 let buffer = location.buffer.read(cx);
9622 let mut ranges_for_buffer = Vec::new();
9623 let range = location.range.to_offset(buffer);
9624 ranges_for_buffer.push(range.clone());
9625
9626 while let Some(next_location) = locations.peek() {
9627 if next_location.buffer == location.buffer {
9628 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9629 locations.next();
9630 } else {
9631 break;
9632 }
9633 }
9634
9635 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9636 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9637 location.buffer.clone(),
9638 ranges_for_buffer,
9639 DEFAULT_MULTIBUFFER_CONTEXT,
9640 cx,
9641 ))
9642 }
9643
9644 multibuffer.with_title(title)
9645 });
9646
9647 let editor = cx.new_view(|cx| {
9648 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9649 });
9650 editor.update(cx, |editor, cx| {
9651 if let Some(first_range) = ranges_to_highlight.first() {
9652 editor.change_selections(None, cx, |selections| {
9653 selections.clear_disjoint();
9654 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9655 });
9656 }
9657 editor.highlight_background::<Self>(
9658 &ranges_to_highlight,
9659 |theme| theme.editor_highlighted_line_background,
9660 cx,
9661 );
9662 });
9663
9664 let item = Box::new(editor);
9665 let item_id = item.item_id();
9666
9667 if split {
9668 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9669 } else {
9670 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9671 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9672 pane.close_current_preview_item(cx)
9673 } else {
9674 None
9675 }
9676 });
9677 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9678 }
9679 workspace.active_pane().update(cx, |pane, cx| {
9680 pane.set_preview_item_id(Some(item_id), cx);
9681 });
9682 }
9683
9684 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9685 use language::ToOffset as _;
9686
9687 let project = self.project.clone()?;
9688 let selection = self.selections.newest_anchor().clone();
9689 let (cursor_buffer, cursor_buffer_position) = self
9690 .buffer
9691 .read(cx)
9692 .text_anchor_for_position(selection.head(), cx)?;
9693 let (tail_buffer, cursor_buffer_position_end) = self
9694 .buffer
9695 .read(cx)
9696 .text_anchor_for_position(selection.tail(), cx)?;
9697 if tail_buffer != cursor_buffer {
9698 return None;
9699 }
9700
9701 let snapshot = cursor_buffer.read(cx).snapshot();
9702 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9703 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9704 let prepare_rename = project.update(cx, |project, cx| {
9705 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
9706 });
9707 drop(snapshot);
9708
9709 Some(cx.spawn(|this, mut cx| async move {
9710 let rename_range = if let Some(range) = prepare_rename.await? {
9711 Some(range)
9712 } else {
9713 this.update(&mut cx, |this, cx| {
9714 let buffer = this.buffer.read(cx).snapshot(cx);
9715 let mut buffer_highlights = this
9716 .document_highlights_for_position(selection.head(), &buffer)
9717 .filter(|highlight| {
9718 highlight.start.excerpt_id == selection.head().excerpt_id
9719 && highlight.end.excerpt_id == selection.head().excerpt_id
9720 });
9721 buffer_highlights
9722 .next()
9723 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9724 })?
9725 };
9726 if let Some(rename_range) = rename_range {
9727 this.update(&mut cx, |this, cx| {
9728 let snapshot = cursor_buffer.read(cx).snapshot();
9729 let rename_buffer_range = rename_range.to_offset(&snapshot);
9730 let cursor_offset_in_rename_range =
9731 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9732 let cursor_offset_in_rename_range_end =
9733 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9734
9735 this.take_rename(false, cx);
9736 let buffer = this.buffer.read(cx).read(cx);
9737 let cursor_offset = selection.head().to_offset(&buffer);
9738 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9739 let rename_end = rename_start + rename_buffer_range.len();
9740 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9741 let mut old_highlight_id = None;
9742 let old_name: Arc<str> = buffer
9743 .chunks(rename_start..rename_end, true)
9744 .map(|chunk| {
9745 if old_highlight_id.is_none() {
9746 old_highlight_id = chunk.syntax_highlight_id;
9747 }
9748 chunk.text
9749 })
9750 .collect::<String>()
9751 .into();
9752
9753 drop(buffer);
9754
9755 // Position the selection in the rename editor so that it matches the current selection.
9756 this.show_local_selections = false;
9757 let rename_editor = cx.new_view(|cx| {
9758 let mut editor = Editor::single_line(cx);
9759 editor.buffer.update(cx, |buffer, cx| {
9760 buffer.edit([(0..0, old_name.clone())], None, cx)
9761 });
9762 let rename_selection_range = match cursor_offset_in_rename_range
9763 .cmp(&cursor_offset_in_rename_range_end)
9764 {
9765 Ordering::Equal => {
9766 editor.select_all(&SelectAll, cx);
9767 return editor;
9768 }
9769 Ordering::Less => {
9770 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9771 }
9772 Ordering::Greater => {
9773 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9774 }
9775 };
9776 if rename_selection_range.end > old_name.len() {
9777 editor.select_all(&SelectAll, cx);
9778 } else {
9779 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9780 s.select_ranges([rename_selection_range]);
9781 });
9782 }
9783 editor
9784 });
9785 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
9786 if e == &EditorEvent::Focused {
9787 cx.emit(EditorEvent::FocusedIn)
9788 }
9789 })
9790 .detach();
9791
9792 let write_highlights =
9793 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
9794 let read_highlights =
9795 this.clear_background_highlights::<DocumentHighlightRead>(cx);
9796 let ranges = write_highlights
9797 .iter()
9798 .flat_map(|(_, ranges)| ranges.iter())
9799 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
9800 .cloned()
9801 .collect();
9802
9803 this.highlight_text::<Rename>(
9804 ranges,
9805 HighlightStyle {
9806 fade_out: Some(0.6),
9807 ..Default::default()
9808 },
9809 cx,
9810 );
9811 let rename_focus_handle = rename_editor.focus_handle(cx);
9812 cx.focus(&rename_focus_handle);
9813 let block_id = this.insert_blocks(
9814 [BlockProperties {
9815 style: BlockStyle::Flex,
9816 position: range.start,
9817 height: 1,
9818 render: Box::new({
9819 let rename_editor = rename_editor.clone();
9820 move |cx: &mut BlockContext| {
9821 let mut text_style = cx.editor_style.text.clone();
9822 if let Some(highlight_style) = old_highlight_id
9823 .and_then(|h| h.style(&cx.editor_style.syntax))
9824 {
9825 text_style = text_style.highlight(highlight_style);
9826 }
9827 div()
9828 .pl(cx.anchor_x)
9829 .child(EditorElement::new(
9830 &rename_editor,
9831 EditorStyle {
9832 background: cx.theme().system().transparent,
9833 local_player: cx.editor_style.local_player,
9834 text: text_style,
9835 scrollbar_width: cx.editor_style.scrollbar_width,
9836 syntax: cx.editor_style.syntax.clone(),
9837 status: cx.editor_style.status.clone(),
9838 inlay_hints_style: HighlightStyle {
9839 color: Some(cx.theme().status().hint),
9840 font_weight: Some(FontWeight::BOLD),
9841 ..HighlightStyle::default()
9842 },
9843 suggestions_style: HighlightStyle {
9844 color: Some(cx.theme().status().predictive),
9845 ..HighlightStyle::default()
9846 },
9847 ..EditorStyle::default()
9848 },
9849 ))
9850 .into_any_element()
9851 }
9852 }),
9853 disposition: BlockDisposition::Below,
9854 priority: 0,
9855 }],
9856 Some(Autoscroll::fit()),
9857 cx,
9858 )[0];
9859 this.pending_rename = Some(RenameState {
9860 range,
9861 old_name,
9862 editor: rename_editor,
9863 block_id,
9864 });
9865 })?;
9866 }
9867
9868 Ok(())
9869 }))
9870 }
9871
9872 pub fn confirm_rename(
9873 &mut self,
9874 _: &ConfirmRename,
9875 cx: &mut ViewContext<Self>,
9876 ) -> Option<Task<Result<()>>> {
9877 let rename = self.take_rename(false, cx)?;
9878 let workspace = self.workspace()?;
9879 let (start_buffer, start) = self
9880 .buffer
9881 .read(cx)
9882 .text_anchor_for_position(rename.range.start, cx)?;
9883 let (end_buffer, end) = self
9884 .buffer
9885 .read(cx)
9886 .text_anchor_for_position(rename.range.end, cx)?;
9887 if start_buffer != end_buffer {
9888 return None;
9889 }
9890
9891 let buffer = start_buffer;
9892 let range = start..end;
9893 let old_name = rename.old_name;
9894 let new_name = rename.editor.read(cx).text(cx);
9895
9896 let rename = workspace
9897 .read(cx)
9898 .project()
9899 .clone()
9900 .update(cx, |project, cx| {
9901 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
9902 });
9903 let workspace = workspace.downgrade();
9904
9905 Some(cx.spawn(|editor, mut cx| async move {
9906 let project_transaction = rename.await?;
9907 Self::open_project_transaction(
9908 &editor,
9909 workspace,
9910 project_transaction,
9911 format!("Rename: {} → {}", old_name, new_name),
9912 cx.clone(),
9913 )
9914 .await?;
9915
9916 editor.update(&mut cx, |editor, cx| {
9917 editor.refresh_document_highlights(cx);
9918 })?;
9919 Ok(())
9920 }))
9921 }
9922
9923 fn take_rename(
9924 &mut self,
9925 moving_cursor: bool,
9926 cx: &mut ViewContext<Self>,
9927 ) -> Option<RenameState> {
9928 let rename = self.pending_rename.take()?;
9929 if rename.editor.focus_handle(cx).is_focused(cx) {
9930 cx.focus(&self.focus_handle);
9931 }
9932
9933 self.remove_blocks(
9934 [rename.block_id].into_iter().collect(),
9935 Some(Autoscroll::fit()),
9936 cx,
9937 );
9938 self.clear_highlights::<Rename>(cx);
9939 self.show_local_selections = true;
9940
9941 if moving_cursor {
9942 let rename_editor = rename.editor.read(cx);
9943 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
9944
9945 // Update the selection to match the position of the selection inside
9946 // the rename editor.
9947 let snapshot = self.buffer.read(cx).read(cx);
9948 let rename_range = rename.range.to_offset(&snapshot);
9949 let cursor_in_editor = snapshot
9950 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
9951 .min(rename_range.end);
9952 drop(snapshot);
9953
9954 self.change_selections(None, cx, |s| {
9955 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
9956 });
9957 } else {
9958 self.refresh_document_highlights(cx);
9959 }
9960
9961 Some(rename)
9962 }
9963
9964 pub fn pending_rename(&self) -> Option<&RenameState> {
9965 self.pending_rename.as_ref()
9966 }
9967
9968 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9969 let project = match &self.project {
9970 Some(project) => project.clone(),
9971 None => return None,
9972 };
9973
9974 Some(self.perform_format(project, FormatTrigger::Manual, cx))
9975 }
9976
9977 fn perform_format(
9978 &mut self,
9979 project: Model<Project>,
9980 trigger: FormatTrigger,
9981 cx: &mut ViewContext<Self>,
9982 ) -> Task<Result<()>> {
9983 let buffer = self.buffer().clone();
9984 let mut buffers = buffer.read(cx).all_buffers();
9985 if trigger == FormatTrigger::Save {
9986 buffers.retain(|buffer| buffer.read(cx).is_dirty());
9987 }
9988
9989 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
9990 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
9991
9992 cx.spawn(|_, mut cx| async move {
9993 let transaction = futures::select_biased! {
9994 () = timeout => {
9995 log::warn!("timed out waiting for formatting");
9996 None
9997 }
9998 transaction = format.log_err().fuse() => transaction,
9999 };
10000
10001 buffer
10002 .update(&mut cx, |buffer, cx| {
10003 if let Some(transaction) = transaction {
10004 if !buffer.is_singleton() {
10005 buffer.push_transaction(&transaction.0, cx);
10006 }
10007 }
10008
10009 cx.notify();
10010 })
10011 .ok();
10012
10013 Ok(())
10014 })
10015 }
10016
10017 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10018 if let Some(project) = self.project.clone() {
10019 self.buffer.update(cx, |multi_buffer, cx| {
10020 project.update(cx, |project, cx| {
10021 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10022 });
10023 })
10024 }
10025 }
10026
10027 fn cancel_language_server_work(
10028 &mut self,
10029 _: &CancelLanguageServerWork,
10030 cx: &mut ViewContext<Self>,
10031 ) {
10032 if let Some(project) = self.project.clone() {
10033 self.buffer.update(cx, |multi_buffer, cx| {
10034 project.update(cx, |project, cx| {
10035 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10036 });
10037 })
10038 }
10039 }
10040
10041 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10042 cx.show_character_palette();
10043 }
10044
10045 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10046 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10047 let buffer = self.buffer.read(cx).snapshot(cx);
10048 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10049 let is_valid = buffer
10050 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10051 .any(|entry| {
10052 entry.diagnostic.is_primary
10053 && !entry.range.is_empty()
10054 && entry.range.start == primary_range_start
10055 && entry.diagnostic.message == active_diagnostics.primary_message
10056 });
10057
10058 if is_valid != active_diagnostics.is_valid {
10059 active_diagnostics.is_valid = is_valid;
10060 let mut new_styles = HashMap::default();
10061 for (block_id, diagnostic) in &active_diagnostics.blocks {
10062 new_styles.insert(
10063 *block_id,
10064 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10065 );
10066 }
10067 self.display_map.update(cx, |display_map, _cx| {
10068 display_map.replace_blocks(new_styles)
10069 });
10070 }
10071 }
10072 }
10073
10074 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10075 self.dismiss_diagnostics(cx);
10076 let snapshot = self.snapshot(cx);
10077 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10078 let buffer = self.buffer.read(cx).snapshot(cx);
10079
10080 let mut primary_range = None;
10081 let mut primary_message = None;
10082 let mut group_end = Point::zero();
10083 let diagnostic_group = buffer
10084 .diagnostic_group::<MultiBufferPoint>(group_id)
10085 .filter_map(|entry| {
10086 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10087 && (entry.range.start.row == entry.range.end.row
10088 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10089 {
10090 return None;
10091 }
10092 if entry.range.end > group_end {
10093 group_end = entry.range.end;
10094 }
10095 if entry.diagnostic.is_primary {
10096 primary_range = Some(entry.range.clone());
10097 primary_message = Some(entry.diagnostic.message.clone());
10098 }
10099 Some(entry)
10100 })
10101 .collect::<Vec<_>>();
10102 let primary_range = primary_range?;
10103 let primary_message = primary_message?;
10104 let primary_range =
10105 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10106
10107 let blocks = display_map
10108 .insert_blocks(
10109 diagnostic_group.iter().map(|entry| {
10110 let diagnostic = entry.diagnostic.clone();
10111 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10112 BlockProperties {
10113 style: BlockStyle::Fixed,
10114 position: buffer.anchor_after(entry.range.start),
10115 height: message_height,
10116 render: diagnostic_block_renderer(diagnostic, None, true, true),
10117 disposition: BlockDisposition::Below,
10118 priority: 0,
10119 }
10120 }),
10121 cx,
10122 )
10123 .into_iter()
10124 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10125 .collect();
10126
10127 Some(ActiveDiagnosticGroup {
10128 primary_range,
10129 primary_message,
10130 group_id,
10131 blocks,
10132 is_valid: true,
10133 })
10134 });
10135 self.active_diagnostics.is_some()
10136 }
10137
10138 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10139 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10140 self.display_map.update(cx, |display_map, cx| {
10141 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10142 });
10143 cx.notify();
10144 }
10145 }
10146
10147 pub fn set_selections_from_remote(
10148 &mut self,
10149 selections: Vec<Selection<Anchor>>,
10150 pending_selection: Option<Selection<Anchor>>,
10151 cx: &mut ViewContext<Self>,
10152 ) {
10153 let old_cursor_position = self.selections.newest_anchor().head();
10154 self.selections.change_with(cx, |s| {
10155 s.select_anchors(selections);
10156 if let Some(pending_selection) = pending_selection {
10157 s.set_pending(pending_selection, SelectMode::Character);
10158 } else {
10159 s.clear_pending();
10160 }
10161 });
10162 self.selections_did_change(false, &old_cursor_position, true, cx);
10163 }
10164
10165 fn push_to_selection_history(&mut self) {
10166 self.selection_history.push(SelectionHistoryEntry {
10167 selections: self.selections.disjoint_anchors(),
10168 select_next_state: self.select_next_state.clone(),
10169 select_prev_state: self.select_prev_state.clone(),
10170 add_selections_state: self.add_selections_state.clone(),
10171 });
10172 }
10173
10174 pub fn transact(
10175 &mut self,
10176 cx: &mut ViewContext<Self>,
10177 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10178 ) -> Option<TransactionId> {
10179 self.start_transaction_at(Instant::now(), cx);
10180 update(self, cx);
10181 self.end_transaction_at(Instant::now(), cx)
10182 }
10183
10184 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10185 self.end_selection(cx);
10186 if let Some(tx_id) = self
10187 .buffer
10188 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10189 {
10190 self.selection_history
10191 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10192 cx.emit(EditorEvent::TransactionBegun {
10193 transaction_id: tx_id,
10194 })
10195 }
10196 }
10197
10198 fn end_transaction_at(
10199 &mut self,
10200 now: Instant,
10201 cx: &mut ViewContext<Self>,
10202 ) -> Option<TransactionId> {
10203 if let Some(transaction_id) = self
10204 .buffer
10205 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10206 {
10207 if let Some((_, end_selections)) =
10208 self.selection_history.transaction_mut(transaction_id)
10209 {
10210 *end_selections = Some(self.selections.disjoint_anchors());
10211 } else {
10212 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10213 }
10214
10215 cx.emit(EditorEvent::Edited { transaction_id });
10216 Some(transaction_id)
10217 } else {
10218 None
10219 }
10220 }
10221
10222 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10223 let mut fold_ranges = Vec::new();
10224
10225 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10226
10227 let selections = self.selections.all_adjusted(cx);
10228 for selection in selections {
10229 let range = selection.range().sorted();
10230 let buffer_start_row = range.start.row;
10231
10232 for row in (0..=range.end.row).rev() {
10233 if let Some((foldable_range, fold_text)) =
10234 display_map.foldable_range(MultiBufferRow(row))
10235 {
10236 if foldable_range.end.row >= buffer_start_row {
10237 fold_ranges.push((foldable_range, fold_text));
10238 if row <= range.start.row {
10239 break;
10240 }
10241 }
10242 }
10243 }
10244 }
10245
10246 self.fold_ranges(fold_ranges, true, cx);
10247 }
10248
10249 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10250 let buffer_row = fold_at.buffer_row;
10251 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10252
10253 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10254 let autoscroll = self
10255 .selections
10256 .all::<Point>(cx)
10257 .iter()
10258 .any(|selection| fold_range.overlaps(&selection.range()));
10259
10260 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10261 }
10262 }
10263
10264 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10265 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10266 let buffer = &display_map.buffer_snapshot;
10267 let selections = self.selections.all::<Point>(cx);
10268 let ranges = selections
10269 .iter()
10270 .map(|s| {
10271 let range = s.display_range(&display_map).sorted();
10272 let mut start = range.start.to_point(&display_map);
10273 let mut end = range.end.to_point(&display_map);
10274 start.column = 0;
10275 end.column = buffer.line_len(MultiBufferRow(end.row));
10276 start..end
10277 })
10278 .collect::<Vec<_>>();
10279
10280 self.unfold_ranges(ranges, true, true, cx);
10281 }
10282
10283 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10284 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10285
10286 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10287 ..Point::new(
10288 unfold_at.buffer_row.0,
10289 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10290 );
10291
10292 let autoscroll = self
10293 .selections
10294 .all::<Point>(cx)
10295 .iter()
10296 .any(|selection| selection.range().overlaps(&intersection_range));
10297
10298 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10299 }
10300
10301 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10302 let selections = self.selections.all::<Point>(cx);
10303 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10304 let line_mode = self.selections.line_mode;
10305 let ranges = selections.into_iter().map(|s| {
10306 if line_mode {
10307 let start = Point::new(s.start.row, 0);
10308 let end = Point::new(
10309 s.end.row,
10310 display_map
10311 .buffer_snapshot
10312 .line_len(MultiBufferRow(s.end.row)),
10313 );
10314 (start..end, display_map.fold_placeholder.clone())
10315 } else {
10316 (s.start..s.end, display_map.fold_placeholder.clone())
10317 }
10318 });
10319 self.fold_ranges(ranges, true, cx);
10320 }
10321
10322 pub fn fold_ranges<T: ToOffset + Clone>(
10323 &mut self,
10324 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10325 auto_scroll: bool,
10326 cx: &mut ViewContext<Self>,
10327 ) {
10328 let mut fold_ranges = Vec::new();
10329 let mut buffers_affected = HashMap::default();
10330 let multi_buffer = self.buffer().read(cx);
10331 for (fold_range, fold_text) in ranges {
10332 if let Some((_, buffer, _)) =
10333 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10334 {
10335 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10336 };
10337 fold_ranges.push((fold_range, fold_text));
10338 }
10339
10340 let mut ranges = fold_ranges.into_iter().peekable();
10341 if ranges.peek().is_some() {
10342 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10343
10344 if auto_scroll {
10345 self.request_autoscroll(Autoscroll::fit(), cx);
10346 }
10347
10348 for buffer in buffers_affected.into_values() {
10349 self.sync_expanded_diff_hunks(buffer, cx);
10350 }
10351
10352 cx.notify();
10353
10354 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10355 // Clear diagnostics block when folding a range that contains it.
10356 let snapshot = self.snapshot(cx);
10357 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10358 drop(snapshot);
10359 self.active_diagnostics = Some(active_diagnostics);
10360 self.dismiss_diagnostics(cx);
10361 } else {
10362 self.active_diagnostics = Some(active_diagnostics);
10363 }
10364 }
10365
10366 self.scrollbar_marker_state.dirty = true;
10367 }
10368 }
10369
10370 pub fn unfold_ranges<T: ToOffset + Clone>(
10371 &mut self,
10372 ranges: impl IntoIterator<Item = Range<T>>,
10373 inclusive: bool,
10374 auto_scroll: bool,
10375 cx: &mut ViewContext<Self>,
10376 ) {
10377 let mut unfold_ranges = Vec::new();
10378 let mut buffers_affected = HashMap::default();
10379 let multi_buffer = self.buffer().read(cx);
10380 for range in ranges {
10381 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10382 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10383 };
10384 unfold_ranges.push(range);
10385 }
10386
10387 let mut ranges = unfold_ranges.into_iter().peekable();
10388 if ranges.peek().is_some() {
10389 self.display_map
10390 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10391 if auto_scroll {
10392 self.request_autoscroll(Autoscroll::fit(), cx);
10393 }
10394
10395 for buffer in buffers_affected.into_values() {
10396 self.sync_expanded_diff_hunks(buffer, cx);
10397 }
10398
10399 cx.notify();
10400 self.scrollbar_marker_state.dirty = true;
10401 self.active_indent_guides_state.dirty = true;
10402 }
10403 }
10404
10405 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10406 self.display_map.read(cx).fold_placeholder.clone()
10407 }
10408
10409 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10410 if hovered != self.gutter_hovered {
10411 self.gutter_hovered = hovered;
10412 cx.notify();
10413 }
10414 }
10415
10416 pub fn insert_blocks(
10417 &mut self,
10418 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10419 autoscroll: Option<Autoscroll>,
10420 cx: &mut ViewContext<Self>,
10421 ) -> Vec<CustomBlockId> {
10422 let blocks = self
10423 .display_map
10424 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10425 if let Some(autoscroll) = autoscroll {
10426 self.request_autoscroll(autoscroll, cx);
10427 }
10428 cx.notify();
10429 blocks
10430 }
10431
10432 pub fn resize_blocks(
10433 &mut self,
10434 heights: HashMap<CustomBlockId, u32>,
10435 autoscroll: Option<Autoscroll>,
10436 cx: &mut ViewContext<Self>,
10437 ) {
10438 self.display_map
10439 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10440 if let Some(autoscroll) = autoscroll {
10441 self.request_autoscroll(autoscroll, cx);
10442 }
10443 cx.notify();
10444 }
10445
10446 pub fn replace_blocks(
10447 &mut self,
10448 renderers: HashMap<CustomBlockId, RenderBlock>,
10449 autoscroll: Option<Autoscroll>,
10450 cx: &mut ViewContext<Self>,
10451 ) {
10452 self.display_map
10453 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10454 if let Some(autoscroll) = autoscroll {
10455 self.request_autoscroll(autoscroll, cx);
10456 }
10457 cx.notify();
10458 }
10459
10460 pub fn remove_blocks(
10461 &mut self,
10462 block_ids: HashSet<CustomBlockId>,
10463 autoscroll: Option<Autoscroll>,
10464 cx: &mut ViewContext<Self>,
10465 ) {
10466 self.display_map.update(cx, |display_map, cx| {
10467 display_map.remove_blocks(block_ids, cx)
10468 });
10469 if let Some(autoscroll) = autoscroll {
10470 self.request_autoscroll(autoscroll, cx);
10471 }
10472 cx.notify();
10473 }
10474
10475 pub fn row_for_block(
10476 &self,
10477 block_id: CustomBlockId,
10478 cx: &mut ViewContext<Self>,
10479 ) -> Option<DisplayRow> {
10480 self.display_map
10481 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10482 }
10483
10484 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10485 self.focused_block = Some(focused_block);
10486 }
10487
10488 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10489 self.focused_block.take()
10490 }
10491
10492 pub fn insert_creases(
10493 &mut self,
10494 creases: impl IntoIterator<Item = Crease>,
10495 cx: &mut ViewContext<Self>,
10496 ) -> Vec<CreaseId> {
10497 self.display_map
10498 .update(cx, |map, cx| map.insert_creases(creases, cx))
10499 }
10500
10501 pub fn remove_creases(
10502 &mut self,
10503 ids: impl IntoIterator<Item = CreaseId>,
10504 cx: &mut ViewContext<Self>,
10505 ) {
10506 self.display_map
10507 .update(cx, |map, cx| map.remove_creases(ids, cx));
10508 }
10509
10510 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10511 self.display_map
10512 .update(cx, |map, cx| map.snapshot(cx))
10513 .longest_row()
10514 }
10515
10516 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10517 self.display_map
10518 .update(cx, |map, cx| map.snapshot(cx))
10519 .max_point()
10520 }
10521
10522 pub fn text(&self, cx: &AppContext) -> String {
10523 self.buffer.read(cx).read(cx).text()
10524 }
10525
10526 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10527 let text = self.text(cx);
10528 let text = text.trim();
10529
10530 if text.is_empty() {
10531 return None;
10532 }
10533
10534 Some(text.to_string())
10535 }
10536
10537 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10538 self.transact(cx, |this, cx| {
10539 this.buffer
10540 .read(cx)
10541 .as_singleton()
10542 .expect("you can only call set_text on editors for singleton buffers")
10543 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10544 });
10545 }
10546
10547 pub fn display_text(&self, cx: &mut AppContext) -> String {
10548 self.display_map
10549 .update(cx, |map, cx| map.snapshot(cx))
10550 .text()
10551 }
10552
10553 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10554 let mut wrap_guides = smallvec::smallvec![];
10555
10556 if self.show_wrap_guides == Some(false) {
10557 return wrap_guides;
10558 }
10559
10560 let settings = self.buffer.read(cx).settings_at(0, cx);
10561 if settings.show_wrap_guides {
10562 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10563 wrap_guides.push((soft_wrap as usize, true));
10564 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
10565 wrap_guides.push((soft_wrap as usize, true));
10566 }
10567 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10568 }
10569
10570 wrap_guides
10571 }
10572
10573 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10574 let settings = self.buffer.read(cx).settings_at(0, cx);
10575 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
10576 match mode {
10577 language_settings::SoftWrap::None => SoftWrap::None,
10578 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10579 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10580 language_settings::SoftWrap::PreferredLineLength => {
10581 SoftWrap::Column(settings.preferred_line_length)
10582 }
10583 language_settings::SoftWrap::Bounded => {
10584 SoftWrap::Bounded(settings.preferred_line_length)
10585 }
10586 }
10587 }
10588
10589 pub fn set_soft_wrap_mode(
10590 &mut self,
10591 mode: language_settings::SoftWrap,
10592 cx: &mut ViewContext<Self>,
10593 ) {
10594 self.soft_wrap_mode_override = Some(mode);
10595 cx.notify();
10596 }
10597
10598 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10599 let rem_size = cx.rem_size();
10600 self.display_map.update(cx, |map, cx| {
10601 map.set_font(
10602 style.text.font(),
10603 style.text.font_size.to_pixels(rem_size),
10604 cx,
10605 )
10606 });
10607 self.style = Some(style);
10608 }
10609
10610 pub fn style(&self) -> Option<&EditorStyle> {
10611 self.style.as_ref()
10612 }
10613
10614 // Called by the element. This method is not designed to be called outside of the editor
10615 // element's layout code because it does not notify when rewrapping is computed synchronously.
10616 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10617 self.display_map
10618 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10619 }
10620
10621 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10622 if self.soft_wrap_mode_override.is_some() {
10623 self.soft_wrap_mode_override.take();
10624 } else {
10625 let soft_wrap = match self.soft_wrap_mode(cx) {
10626 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10627 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
10628 language_settings::SoftWrap::PreferLine
10629 }
10630 };
10631 self.soft_wrap_mode_override = Some(soft_wrap);
10632 }
10633 cx.notify();
10634 }
10635
10636 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10637 let Some(workspace) = self.workspace() else {
10638 return;
10639 };
10640 let fs = workspace.read(cx).app_state().fs.clone();
10641 let current_show = TabBarSettings::get_global(cx).show;
10642 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10643 setting.show = !current_show;
10644 });
10645 }
10646
10647 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10648 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10649 self.buffer
10650 .read(cx)
10651 .settings_at(0, cx)
10652 .indent_guides
10653 .enabled
10654 });
10655 self.show_indent_guides = Some(!currently_enabled);
10656 cx.notify();
10657 }
10658
10659 fn should_show_indent_guides(&self) -> Option<bool> {
10660 self.show_indent_guides
10661 }
10662
10663 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10664 let mut editor_settings = EditorSettings::get_global(cx).clone();
10665 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10666 EditorSettings::override_global(editor_settings, cx);
10667 }
10668
10669 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
10670 self.use_relative_line_numbers
10671 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
10672 }
10673
10674 pub fn toggle_relative_line_numbers(
10675 &mut self,
10676 _: &ToggleRelativeLineNumbers,
10677 cx: &mut ViewContext<Self>,
10678 ) {
10679 let is_relative = self.should_use_relative_line_numbers(cx);
10680 self.set_relative_line_number(Some(!is_relative), cx)
10681 }
10682
10683 pub fn set_relative_line_number(
10684 &mut self,
10685 is_relative: Option<bool>,
10686 cx: &mut ViewContext<Self>,
10687 ) {
10688 self.use_relative_line_numbers = is_relative;
10689 cx.notify();
10690 }
10691
10692 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10693 self.show_gutter = show_gutter;
10694 cx.notify();
10695 }
10696
10697 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10698 self.show_line_numbers = Some(show_line_numbers);
10699 cx.notify();
10700 }
10701
10702 pub fn set_show_git_diff_gutter(
10703 &mut self,
10704 show_git_diff_gutter: bool,
10705 cx: &mut ViewContext<Self>,
10706 ) {
10707 self.show_git_diff_gutter = Some(show_git_diff_gutter);
10708 cx.notify();
10709 }
10710
10711 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10712 self.show_code_actions = Some(show_code_actions);
10713 cx.notify();
10714 }
10715
10716 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10717 self.show_runnables = Some(show_runnables);
10718 cx.notify();
10719 }
10720
10721 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
10722 if self.display_map.read(cx).masked != masked {
10723 self.display_map.update(cx, |map, _| map.masked = masked);
10724 }
10725 cx.notify()
10726 }
10727
10728 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10729 self.show_wrap_guides = Some(show_wrap_guides);
10730 cx.notify();
10731 }
10732
10733 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10734 self.show_indent_guides = Some(show_indent_guides);
10735 cx.notify();
10736 }
10737
10738 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10739 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10740 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10741 if let Some(dir) = file.abs_path(cx).parent() {
10742 return Some(dir.to_owned());
10743 }
10744 }
10745
10746 if let Some(project_path) = buffer.read(cx).project_path(cx) {
10747 return Some(project_path.path.to_path_buf());
10748 }
10749 }
10750
10751 None
10752 }
10753
10754 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10755 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10756 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10757 cx.reveal_path(&file.abs_path(cx));
10758 }
10759 }
10760 }
10761
10762 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10763 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10764 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10765 if let Some(path) = file.abs_path(cx).to_str() {
10766 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10767 }
10768 }
10769 }
10770 }
10771
10772 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10773 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10774 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10775 if let Some(path) = file.path().to_str() {
10776 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10777 }
10778 }
10779 }
10780 }
10781
10782 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10783 self.show_git_blame_gutter = !self.show_git_blame_gutter;
10784
10785 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10786 self.start_git_blame(true, cx);
10787 }
10788
10789 cx.notify();
10790 }
10791
10792 pub fn toggle_git_blame_inline(
10793 &mut self,
10794 _: &ToggleGitBlameInline,
10795 cx: &mut ViewContext<Self>,
10796 ) {
10797 self.toggle_git_blame_inline_internal(true, cx);
10798 cx.notify();
10799 }
10800
10801 pub fn git_blame_inline_enabled(&self) -> bool {
10802 self.git_blame_inline_enabled
10803 }
10804
10805 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10806 self.show_selection_menu = self
10807 .show_selection_menu
10808 .map(|show_selections_menu| !show_selections_menu)
10809 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10810
10811 cx.notify();
10812 }
10813
10814 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10815 self.show_selection_menu
10816 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10817 }
10818
10819 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10820 if let Some(project) = self.project.as_ref() {
10821 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10822 return;
10823 };
10824
10825 if buffer.read(cx).file().is_none() {
10826 return;
10827 }
10828
10829 let focused = self.focus_handle(cx).contains_focused(cx);
10830
10831 let project = project.clone();
10832 let blame =
10833 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10834 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10835 self.blame = Some(blame);
10836 }
10837 }
10838
10839 fn toggle_git_blame_inline_internal(
10840 &mut self,
10841 user_triggered: bool,
10842 cx: &mut ViewContext<Self>,
10843 ) {
10844 if self.git_blame_inline_enabled {
10845 self.git_blame_inline_enabled = false;
10846 self.show_git_blame_inline = false;
10847 self.show_git_blame_inline_delay_task.take();
10848 } else {
10849 self.git_blame_inline_enabled = true;
10850 self.start_git_blame_inline(user_triggered, cx);
10851 }
10852
10853 cx.notify();
10854 }
10855
10856 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10857 self.start_git_blame(user_triggered, cx);
10858
10859 if ProjectSettings::get_global(cx)
10860 .git
10861 .inline_blame_delay()
10862 .is_some()
10863 {
10864 self.start_inline_blame_timer(cx);
10865 } else {
10866 self.show_git_blame_inline = true
10867 }
10868 }
10869
10870 pub fn blame(&self) -> Option<&Model<GitBlame>> {
10871 self.blame.as_ref()
10872 }
10873
10874 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10875 self.show_git_blame_gutter && self.has_blame_entries(cx)
10876 }
10877
10878 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10879 self.show_git_blame_inline
10880 && self.focus_handle.is_focused(cx)
10881 && !self.newest_selection_head_on_empty_line(cx)
10882 && self.has_blame_entries(cx)
10883 }
10884
10885 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10886 self.blame()
10887 .map_or(false, |blame| blame.read(cx).has_generated_entries())
10888 }
10889
10890 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10891 let cursor_anchor = self.selections.newest_anchor().head();
10892
10893 let snapshot = self.buffer.read(cx).snapshot(cx);
10894 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10895
10896 snapshot.line_len(buffer_row) == 0
10897 }
10898
10899 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10900 let (path, selection, repo) = maybe!({
10901 let project_handle = self.project.as_ref()?.clone();
10902 let project = project_handle.read(cx);
10903
10904 let selection = self.selections.newest::<Point>(cx);
10905 let selection_range = selection.range();
10906
10907 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10908 (buffer, selection_range.start.row..selection_range.end.row)
10909 } else {
10910 let buffer_ranges = self
10911 .buffer()
10912 .read(cx)
10913 .range_to_buffer_ranges(selection_range, cx);
10914
10915 let (buffer, range, _) = if selection.reversed {
10916 buffer_ranges.first()
10917 } else {
10918 buffer_ranges.last()
10919 }?;
10920
10921 let snapshot = buffer.read(cx).snapshot();
10922 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10923 ..text::ToPoint::to_point(&range.end, &snapshot).row;
10924 (buffer.clone(), selection)
10925 };
10926
10927 let path = buffer
10928 .read(cx)
10929 .file()?
10930 .as_local()?
10931 .path()
10932 .to_str()?
10933 .to_string();
10934 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10935 Some((path, selection, repo))
10936 })
10937 .ok_or_else(|| anyhow!("unable to open git repository"))?;
10938
10939 const REMOTE_NAME: &str = "origin";
10940 let origin_url = repo
10941 .remote_url(REMOTE_NAME)
10942 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10943 let sha = repo
10944 .head_sha()
10945 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10946
10947 let (provider, remote) =
10948 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10949 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10950
10951 Ok(provider.build_permalink(
10952 remote,
10953 BuildPermalinkParams {
10954 sha: &sha,
10955 path: &path,
10956 selection: Some(selection),
10957 },
10958 ))
10959 }
10960
10961 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10962 let permalink = self.get_permalink_to_line(cx);
10963
10964 match permalink {
10965 Ok(permalink) => {
10966 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
10967 }
10968 Err(err) => {
10969 let message = format!("Failed to copy permalink: {err}");
10970
10971 Err::<(), anyhow::Error>(err).log_err();
10972
10973 if let Some(workspace) = self.workspace() {
10974 workspace.update(cx, |workspace, cx| {
10975 struct CopyPermalinkToLine;
10976
10977 workspace.show_toast(
10978 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10979 cx,
10980 )
10981 })
10982 }
10983 }
10984 }
10985 }
10986
10987 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
10988 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10989 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10990 if let Some(path) = file.path().to_str() {
10991 let selection = self.selections.newest::<Point>(cx).start.row + 1;
10992 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
10993 }
10994 }
10995 }
10996 }
10997
10998 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10999 let permalink = self.get_permalink_to_line(cx);
11000
11001 match permalink {
11002 Ok(permalink) => {
11003 cx.open_url(permalink.as_ref());
11004 }
11005 Err(err) => {
11006 let message = format!("Failed to open permalink: {err}");
11007
11008 Err::<(), anyhow::Error>(err).log_err();
11009
11010 if let Some(workspace) = self.workspace() {
11011 workspace.update(cx, |workspace, cx| {
11012 struct OpenPermalinkToLine;
11013
11014 workspace.show_toast(
11015 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11016 cx,
11017 )
11018 })
11019 }
11020 }
11021 }
11022 }
11023
11024 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
11025 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
11026 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
11027 pub fn highlight_rows<T: 'static>(
11028 &mut self,
11029 rows: RangeInclusive<Anchor>,
11030 color: Option<Hsla>,
11031 should_autoscroll: bool,
11032 cx: &mut ViewContext<Self>,
11033 ) {
11034 let snapshot = self.buffer().read(cx).snapshot(cx);
11035 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11036 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
11037 highlight
11038 .range
11039 .start()
11040 .cmp(rows.start(), &snapshot)
11041 .then(highlight.range.end().cmp(rows.end(), &snapshot))
11042 });
11043 match (color, existing_highlight_index) {
11044 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
11045 ix,
11046 RowHighlight {
11047 index: post_inc(&mut self.highlight_order),
11048 range: rows,
11049 should_autoscroll,
11050 color,
11051 },
11052 ),
11053 (None, Ok(i)) => {
11054 row_highlights.remove(i);
11055 }
11056 }
11057 }
11058
11059 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11060 pub fn clear_row_highlights<T: 'static>(&mut self) {
11061 self.highlighted_rows.remove(&TypeId::of::<T>());
11062 }
11063
11064 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11065 pub fn highlighted_rows<T: 'static>(
11066 &self,
11067 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
11068 Some(
11069 self.highlighted_rows
11070 .get(&TypeId::of::<T>())?
11071 .iter()
11072 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
11073 )
11074 }
11075
11076 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11077 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11078 /// Allows to ignore certain kinds of highlights.
11079 pub fn highlighted_display_rows(
11080 &mut self,
11081 cx: &mut WindowContext,
11082 ) -> BTreeMap<DisplayRow, Hsla> {
11083 let snapshot = self.snapshot(cx);
11084 let mut used_highlight_orders = HashMap::default();
11085 self.highlighted_rows
11086 .iter()
11087 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11088 .fold(
11089 BTreeMap::<DisplayRow, Hsla>::new(),
11090 |mut unique_rows, highlight| {
11091 let start_row = highlight.range.start().to_display_point(&snapshot).row();
11092 let end_row = highlight.range.end().to_display_point(&snapshot).row();
11093 for row in start_row.0..=end_row.0 {
11094 let used_index =
11095 used_highlight_orders.entry(row).or_insert(highlight.index);
11096 if highlight.index >= *used_index {
11097 *used_index = highlight.index;
11098 match highlight.color {
11099 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
11100 None => unique_rows.remove(&DisplayRow(row)),
11101 };
11102 }
11103 }
11104 unique_rows
11105 },
11106 )
11107 }
11108
11109 pub fn highlighted_display_row_for_autoscroll(
11110 &self,
11111 snapshot: &DisplaySnapshot,
11112 ) -> Option<DisplayRow> {
11113 self.highlighted_rows
11114 .values()
11115 .flat_map(|highlighted_rows| highlighted_rows.iter())
11116 .filter_map(|highlight| {
11117 if highlight.color.is_none() || !highlight.should_autoscroll {
11118 return None;
11119 }
11120 Some(highlight.range.start().to_display_point(snapshot).row())
11121 })
11122 .min()
11123 }
11124
11125 pub fn set_search_within_ranges(
11126 &mut self,
11127 ranges: &[Range<Anchor>],
11128 cx: &mut ViewContext<Self>,
11129 ) {
11130 self.highlight_background::<SearchWithinRange>(
11131 ranges,
11132 |colors| colors.editor_document_highlight_read_background,
11133 cx,
11134 )
11135 }
11136
11137 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11138 self.breadcrumb_header = Some(new_header);
11139 }
11140
11141 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11142 self.clear_background_highlights::<SearchWithinRange>(cx);
11143 }
11144
11145 pub fn highlight_background<T: 'static>(
11146 &mut self,
11147 ranges: &[Range<Anchor>],
11148 color_fetcher: fn(&ThemeColors) -> Hsla,
11149 cx: &mut ViewContext<Self>,
11150 ) {
11151 self.background_highlights
11152 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11153 self.scrollbar_marker_state.dirty = true;
11154 cx.notify();
11155 }
11156
11157 pub fn clear_background_highlights<T: 'static>(
11158 &mut self,
11159 cx: &mut ViewContext<Self>,
11160 ) -> Option<BackgroundHighlight> {
11161 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11162 if !text_highlights.1.is_empty() {
11163 self.scrollbar_marker_state.dirty = true;
11164 cx.notify();
11165 }
11166 Some(text_highlights)
11167 }
11168
11169 pub fn highlight_gutter<T: 'static>(
11170 &mut self,
11171 ranges: &[Range<Anchor>],
11172 color_fetcher: fn(&AppContext) -> Hsla,
11173 cx: &mut ViewContext<Self>,
11174 ) {
11175 self.gutter_highlights
11176 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11177 cx.notify();
11178 }
11179
11180 pub fn clear_gutter_highlights<T: 'static>(
11181 &mut self,
11182 cx: &mut ViewContext<Self>,
11183 ) -> Option<GutterHighlight> {
11184 cx.notify();
11185 self.gutter_highlights.remove(&TypeId::of::<T>())
11186 }
11187
11188 #[cfg(feature = "test-support")]
11189 pub fn all_text_background_highlights(
11190 &mut self,
11191 cx: &mut ViewContext<Self>,
11192 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11193 let snapshot = self.snapshot(cx);
11194 let buffer = &snapshot.buffer_snapshot;
11195 let start = buffer.anchor_before(0);
11196 let end = buffer.anchor_after(buffer.len());
11197 let theme = cx.theme().colors();
11198 self.background_highlights_in_range(start..end, &snapshot, theme)
11199 }
11200
11201 #[cfg(feature = "test-support")]
11202 pub fn search_background_highlights(
11203 &mut self,
11204 cx: &mut ViewContext<Self>,
11205 ) -> Vec<Range<Point>> {
11206 let snapshot = self.buffer().read(cx).snapshot(cx);
11207
11208 let highlights = self
11209 .background_highlights
11210 .get(&TypeId::of::<items::BufferSearchHighlights>());
11211
11212 if let Some((_color, ranges)) = highlights {
11213 ranges
11214 .iter()
11215 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11216 .collect_vec()
11217 } else {
11218 vec![]
11219 }
11220 }
11221
11222 fn document_highlights_for_position<'a>(
11223 &'a self,
11224 position: Anchor,
11225 buffer: &'a MultiBufferSnapshot,
11226 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
11227 let read_highlights = self
11228 .background_highlights
11229 .get(&TypeId::of::<DocumentHighlightRead>())
11230 .map(|h| &h.1);
11231 let write_highlights = self
11232 .background_highlights
11233 .get(&TypeId::of::<DocumentHighlightWrite>())
11234 .map(|h| &h.1);
11235 let left_position = position.bias_left(buffer);
11236 let right_position = position.bias_right(buffer);
11237 read_highlights
11238 .into_iter()
11239 .chain(write_highlights)
11240 .flat_map(move |ranges| {
11241 let start_ix = match ranges.binary_search_by(|probe| {
11242 let cmp = probe.end.cmp(&left_position, buffer);
11243 if cmp.is_ge() {
11244 Ordering::Greater
11245 } else {
11246 Ordering::Less
11247 }
11248 }) {
11249 Ok(i) | Err(i) => i,
11250 };
11251
11252 ranges[start_ix..]
11253 .iter()
11254 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11255 })
11256 }
11257
11258 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11259 self.background_highlights
11260 .get(&TypeId::of::<T>())
11261 .map_or(false, |(_, highlights)| !highlights.is_empty())
11262 }
11263
11264 pub fn background_highlights_in_range(
11265 &self,
11266 search_range: Range<Anchor>,
11267 display_snapshot: &DisplaySnapshot,
11268 theme: &ThemeColors,
11269 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11270 let mut results = Vec::new();
11271 for (color_fetcher, ranges) in self.background_highlights.values() {
11272 let color = color_fetcher(theme);
11273 let start_ix = match ranges.binary_search_by(|probe| {
11274 let cmp = probe
11275 .end
11276 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11277 if cmp.is_gt() {
11278 Ordering::Greater
11279 } else {
11280 Ordering::Less
11281 }
11282 }) {
11283 Ok(i) | Err(i) => i,
11284 };
11285 for range in &ranges[start_ix..] {
11286 if range
11287 .start
11288 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11289 .is_ge()
11290 {
11291 break;
11292 }
11293
11294 let start = range.start.to_display_point(display_snapshot);
11295 let end = range.end.to_display_point(display_snapshot);
11296 results.push((start..end, color))
11297 }
11298 }
11299 results
11300 }
11301
11302 pub fn background_highlight_row_ranges<T: 'static>(
11303 &self,
11304 search_range: Range<Anchor>,
11305 display_snapshot: &DisplaySnapshot,
11306 count: usize,
11307 ) -> Vec<RangeInclusive<DisplayPoint>> {
11308 let mut results = Vec::new();
11309 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11310 return vec![];
11311 };
11312
11313 let start_ix = match ranges.binary_search_by(|probe| {
11314 let cmp = probe
11315 .end
11316 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11317 if cmp.is_gt() {
11318 Ordering::Greater
11319 } else {
11320 Ordering::Less
11321 }
11322 }) {
11323 Ok(i) | Err(i) => i,
11324 };
11325 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11326 if let (Some(start_display), Some(end_display)) = (start, end) {
11327 results.push(
11328 start_display.to_display_point(display_snapshot)
11329 ..=end_display.to_display_point(display_snapshot),
11330 );
11331 }
11332 };
11333 let mut start_row: Option<Point> = None;
11334 let mut end_row: Option<Point> = None;
11335 if ranges.len() > count {
11336 return Vec::new();
11337 }
11338 for range in &ranges[start_ix..] {
11339 if range
11340 .start
11341 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11342 .is_ge()
11343 {
11344 break;
11345 }
11346 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11347 if let Some(current_row) = &end_row {
11348 if end.row == current_row.row {
11349 continue;
11350 }
11351 }
11352 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11353 if start_row.is_none() {
11354 assert_eq!(end_row, None);
11355 start_row = Some(start);
11356 end_row = Some(end);
11357 continue;
11358 }
11359 if let Some(current_end) = end_row.as_mut() {
11360 if start.row > current_end.row + 1 {
11361 push_region(start_row, end_row);
11362 start_row = Some(start);
11363 end_row = Some(end);
11364 } else {
11365 // Merge two hunks.
11366 *current_end = end;
11367 }
11368 } else {
11369 unreachable!();
11370 }
11371 }
11372 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11373 push_region(start_row, end_row);
11374 results
11375 }
11376
11377 pub fn gutter_highlights_in_range(
11378 &self,
11379 search_range: Range<Anchor>,
11380 display_snapshot: &DisplaySnapshot,
11381 cx: &AppContext,
11382 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11383 let mut results = Vec::new();
11384 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11385 let color = color_fetcher(cx);
11386 let start_ix = match ranges.binary_search_by(|probe| {
11387 let cmp = probe
11388 .end
11389 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11390 if cmp.is_gt() {
11391 Ordering::Greater
11392 } else {
11393 Ordering::Less
11394 }
11395 }) {
11396 Ok(i) | Err(i) => i,
11397 };
11398 for range in &ranges[start_ix..] {
11399 if range
11400 .start
11401 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11402 .is_ge()
11403 {
11404 break;
11405 }
11406
11407 let start = range.start.to_display_point(display_snapshot);
11408 let end = range.end.to_display_point(display_snapshot);
11409 results.push((start..end, color))
11410 }
11411 }
11412 results
11413 }
11414
11415 /// Get the text ranges corresponding to the redaction query
11416 pub fn redacted_ranges(
11417 &self,
11418 search_range: Range<Anchor>,
11419 display_snapshot: &DisplaySnapshot,
11420 cx: &WindowContext,
11421 ) -> Vec<Range<DisplayPoint>> {
11422 display_snapshot
11423 .buffer_snapshot
11424 .redacted_ranges(search_range, |file| {
11425 if let Some(file) = file {
11426 file.is_private()
11427 && EditorSettings::get(
11428 Some(SettingsLocation {
11429 worktree_id: file.worktree_id(cx),
11430 path: file.path().as_ref(),
11431 }),
11432 cx,
11433 )
11434 .redact_private_values
11435 } else {
11436 false
11437 }
11438 })
11439 .map(|range| {
11440 range.start.to_display_point(display_snapshot)
11441 ..range.end.to_display_point(display_snapshot)
11442 })
11443 .collect()
11444 }
11445
11446 pub fn highlight_text<T: 'static>(
11447 &mut self,
11448 ranges: Vec<Range<Anchor>>,
11449 style: HighlightStyle,
11450 cx: &mut ViewContext<Self>,
11451 ) {
11452 self.display_map.update(cx, |map, _| {
11453 map.highlight_text(TypeId::of::<T>(), ranges, style)
11454 });
11455 cx.notify();
11456 }
11457
11458 pub(crate) fn highlight_inlays<T: 'static>(
11459 &mut self,
11460 highlights: Vec<InlayHighlight>,
11461 style: HighlightStyle,
11462 cx: &mut ViewContext<Self>,
11463 ) {
11464 self.display_map.update(cx, |map, _| {
11465 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11466 });
11467 cx.notify();
11468 }
11469
11470 pub fn text_highlights<'a, T: 'static>(
11471 &'a self,
11472 cx: &'a AppContext,
11473 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11474 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11475 }
11476
11477 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11478 let cleared = self
11479 .display_map
11480 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11481 if cleared {
11482 cx.notify();
11483 }
11484 }
11485
11486 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11487 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11488 && self.focus_handle.is_focused(cx)
11489 }
11490
11491 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11492 self.show_cursor_when_unfocused = is_enabled;
11493 cx.notify();
11494 }
11495
11496 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11497 cx.notify();
11498 }
11499
11500 fn on_buffer_event(
11501 &mut self,
11502 multibuffer: Model<MultiBuffer>,
11503 event: &multi_buffer::Event,
11504 cx: &mut ViewContext<Self>,
11505 ) {
11506 match event {
11507 multi_buffer::Event::Edited {
11508 singleton_buffer_edited,
11509 } => {
11510 self.scrollbar_marker_state.dirty = true;
11511 self.active_indent_guides_state.dirty = true;
11512 self.refresh_active_diagnostics(cx);
11513 self.refresh_code_actions(cx);
11514 if self.has_active_inline_completion(cx) {
11515 self.update_visible_inline_completion(cx);
11516 }
11517 cx.emit(EditorEvent::BufferEdited);
11518 cx.emit(SearchEvent::MatchesInvalidated);
11519 if *singleton_buffer_edited {
11520 if let Some(project) = &self.project {
11521 let project = project.read(cx);
11522 #[allow(clippy::mutable_key_type)]
11523 let languages_affected = multibuffer
11524 .read(cx)
11525 .all_buffers()
11526 .into_iter()
11527 .filter_map(|buffer| {
11528 let buffer = buffer.read(cx);
11529 let language = buffer.language()?;
11530 if project.is_local_or_ssh()
11531 && project.language_servers_for_buffer(buffer, cx).count() == 0
11532 {
11533 None
11534 } else {
11535 Some(language)
11536 }
11537 })
11538 .cloned()
11539 .collect::<HashSet<_>>();
11540 if !languages_affected.is_empty() {
11541 self.refresh_inlay_hints(
11542 InlayHintRefreshReason::BufferEdited(languages_affected),
11543 cx,
11544 );
11545 }
11546 }
11547 }
11548
11549 let Some(project) = &self.project else { return };
11550 let telemetry = project.read(cx).client().telemetry().clone();
11551 refresh_linked_ranges(self, cx);
11552 telemetry.log_edit_event("editor");
11553 }
11554 multi_buffer::Event::ExcerptsAdded {
11555 buffer,
11556 predecessor,
11557 excerpts,
11558 } => {
11559 self.tasks_update_task = Some(self.refresh_runnables(cx));
11560 cx.emit(EditorEvent::ExcerptsAdded {
11561 buffer: buffer.clone(),
11562 predecessor: *predecessor,
11563 excerpts: excerpts.clone(),
11564 });
11565 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11566 }
11567 multi_buffer::Event::ExcerptsRemoved { ids } => {
11568 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11569 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11570 }
11571 multi_buffer::Event::ExcerptsEdited { ids } => {
11572 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11573 }
11574 multi_buffer::Event::ExcerptsExpanded { ids } => {
11575 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11576 }
11577 multi_buffer::Event::Reparsed(buffer_id) => {
11578 self.tasks_update_task = Some(self.refresh_runnables(cx));
11579
11580 cx.emit(EditorEvent::Reparsed(*buffer_id));
11581 }
11582 multi_buffer::Event::LanguageChanged(buffer_id) => {
11583 linked_editing_ranges::refresh_linked_ranges(self, cx);
11584 cx.emit(EditorEvent::Reparsed(*buffer_id));
11585 cx.notify();
11586 }
11587 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11588 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11589 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11590 cx.emit(EditorEvent::TitleChanged)
11591 }
11592 multi_buffer::Event::DiffBaseChanged => {
11593 self.scrollbar_marker_state.dirty = true;
11594 cx.emit(EditorEvent::DiffBaseChanged);
11595 cx.notify();
11596 }
11597 multi_buffer::Event::DiffUpdated { buffer } => {
11598 self.sync_expanded_diff_hunks(buffer.clone(), cx);
11599 cx.notify();
11600 }
11601 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11602 multi_buffer::Event::DiagnosticsUpdated => {
11603 self.refresh_active_diagnostics(cx);
11604 self.scrollbar_marker_state.dirty = true;
11605 cx.notify();
11606 }
11607 _ => {}
11608 };
11609 }
11610
11611 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11612 cx.notify();
11613 }
11614
11615 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11616 self.tasks_update_task = Some(self.refresh_runnables(cx));
11617 self.refresh_inline_completion(true, false, cx);
11618 self.refresh_inlay_hints(
11619 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11620 self.selections.newest_anchor().head(),
11621 &self.buffer.read(cx).snapshot(cx),
11622 cx,
11623 )),
11624 cx,
11625 );
11626 let editor_settings = EditorSettings::get_global(cx);
11627 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11628 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11629
11630 let project_settings = ProjectSettings::get_global(cx);
11631 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11632
11633 if self.mode == EditorMode::Full {
11634 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11635 if self.git_blame_inline_enabled != inline_blame_enabled {
11636 self.toggle_git_blame_inline_internal(false, cx);
11637 }
11638 }
11639
11640 cx.notify();
11641 }
11642
11643 pub fn set_searchable(&mut self, searchable: bool) {
11644 self.searchable = searchable;
11645 }
11646
11647 pub fn searchable(&self) -> bool {
11648 self.searchable
11649 }
11650
11651 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11652 self.open_excerpts_common(true, cx)
11653 }
11654
11655 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11656 self.open_excerpts_common(false, cx)
11657 }
11658
11659 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11660 let buffer = self.buffer.read(cx);
11661 if buffer.is_singleton() {
11662 cx.propagate();
11663 return;
11664 }
11665
11666 let Some(workspace) = self.workspace() else {
11667 cx.propagate();
11668 return;
11669 };
11670
11671 let mut new_selections_by_buffer = HashMap::default();
11672 for selection in self.selections.all::<usize>(cx) {
11673 for (buffer, mut range, _) in
11674 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11675 {
11676 if selection.reversed {
11677 mem::swap(&mut range.start, &mut range.end);
11678 }
11679 new_selections_by_buffer
11680 .entry(buffer)
11681 .or_insert(Vec::new())
11682 .push(range)
11683 }
11684 }
11685
11686 // We defer the pane interaction because we ourselves are a workspace item
11687 // and activating a new item causes the pane to call a method on us reentrantly,
11688 // which panics if we're on the stack.
11689 cx.window_context().defer(move |cx| {
11690 workspace.update(cx, |workspace, cx| {
11691 let pane = if split {
11692 workspace.adjacent_pane(cx)
11693 } else {
11694 workspace.active_pane().clone()
11695 };
11696
11697 for (buffer, ranges) in new_selections_by_buffer {
11698 let editor =
11699 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
11700 editor.update(cx, |editor, cx| {
11701 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11702 s.select_ranges(ranges);
11703 });
11704 });
11705 }
11706 })
11707 });
11708 }
11709
11710 fn jump(
11711 &mut self,
11712 path: ProjectPath,
11713 position: Point,
11714 anchor: language::Anchor,
11715 offset_from_top: u32,
11716 cx: &mut ViewContext<Self>,
11717 ) {
11718 let workspace = self.workspace();
11719 cx.spawn(|_, mut cx| async move {
11720 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11721 let editor = workspace.update(&mut cx, |workspace, cx| {
11722 // Reset the preview item id before opening the new item
11723 workspace.active_pane().update(cx, |pane, cx| {
11724 pane.set_preview_item_id(None, cx);
11725 });
11726 workspace.open_path_preview(path, None, true, true, cx)
11727 })?;
11728 let editor = editor
11729 .await?
11730 .downcast::<Editor>()
11731 .ok_or_else(|| anyhow!("opened item was not an editor"))?
11732 .downgrade();
11733 editor.update(&mut cx, |editor, cx| {
11734 let buffer = editor
11735 .buffer()
11736 .read(cx)
11737 .as_singleton()
11738 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11739 let buffer = buffer.read(cx);
11740 let cursor = if buffer.can_resolve(&anchor) {
11741 language::ToPoint::to_point(&anchor, buffer)
11742 } else {
11743 buffer.clip_point(position, Bias::Left)
11744 };
11745
11746 let nav_history = editor.nav_history.take();
11747 editor.change_selections(
11748 Some(Autoscroll::top_relative(offset_from_top as usize)),
11749 cx,
11750 |s| {
11751 s.select_ranges([cursor..cursor]);
11752 },
11753 );
11754 editor.nav_history = nav_history;
11755
11756 anyhow::Ok(())
11757 })??;
11758
11759 anyhow::Ok(())
11760 })
11761 .detach_and_log_err(cx);
11762 }
11763
11764 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11765 let snapshot = self.buffer.read(cx).read(cx);
11766 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11767 Some(
11768 ranges
11769 .iter()
11770 .map(move |range| {
11771 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11772 })
11773 .collect(),
11774 )
11775 }
11776
11777 fn selection_replacement_ranges(
11778 &self,
11779 range: Range<OffsetUtf16>,
11780 cx: &AppContext,
11781 ) -> Vec<Range<OffsetUtf16>> {
11782 let selections = self.selections.all::<OffsetUtf16>(cx);
11783 let newest_selection = selections
11784 .iter()
11785 .max_by_key(|selection| selection.id)
11786 .unwrap();
11787 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11788 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11789 let snapshot = self.buffer.read(cx).read(cx);
11790 selections
11791 .into_iter()
11792 .map(|mut selection| {
11793 selection.start.0 =
11794 (selection.start.0 as isize).saturating_add(start_delta) as usize;
11795 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11796 snapshot.clip_offset_utf16(selection.start, Bias::Left)
11797 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11798 })
11799 .collect()
11800 }
11801
11802 fn report_editor_event(
11803 &self,
11804 operation: &'static str,
11805 file_extension: Option<String>,
11806 cx: &AppContext,
11807 ) {
11808 if cfg!(any(test, feature = "test-support")) {
11809 return;
11810 }
11811
11812 let Some(project) = &self.project else { return };
11813
11814 // If None, we are in a file without an extension
11815 let file = self
11816 .buffer
11817 .read(cx)
11818 .as_singleton()
11819 .and_then(|b| b.read(cx).file());
11820 let file_extension = file_extension.or(file
11821 .as_ref()
11822 .and_then(|file| Path::new(file.file_name(cx)).extension())
11823 .and_then(|e| e.to_str())
11824 .map(|a| a.to_string()));
11825
11826 let vim_mode = cx
11827 .global::<SettingsStore>()
11828 .raw_user_settings()
11829 .get("vim_mode")
11830 == Some(&serde_json::Value::Bool(true));
11831
11832 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11833 == language::language_settings::InlineCompletionProvider::Copilot;
11834 let copilot_enabled_for_language = self
11835 .buffer
11836 .read(cx)
11837 .settings_at(0, cx)
11838 .show_inline_completions;
11839
11840 let telemetry = project.read(cx).client().telemetry().clone();
11841 telemetry.report_editor_event(
11842 file_extension,
11843 vim_mode,
11844 operation,
11845 copilot_enabled,
11846 copilot_enabled_for_language,
11847 )
11848 }
11849
11850 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11851 /// with each line being an array of {text, highlight} objects.
11852 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11853 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11854 return;
11855 };
11856
11857 #[derive(Serialize)]
11858 struct Chunk<'a> {
11859 text: String,
11860 highlight: Option<&'a str>,
11861 }
11862
11863 let snapshot = buffer.read(cx).snapshot();
11864 let range = self
11865 .selected_text_range(false, cx)
11866 .and_then(|selection| {
11867 if selection.range.is_empty() {
11868 None
11869 } else {
11870 Some(selection.range)
11871 }
11872 })
11873 .unwrap_or_else(|| 0..snapshot.len());
11874
11875 let chunks = snapshot.chunks(range, true);
11876 let mut lines = Vec::new();
11877 let mut line: VecDeque<Chunk> = VecDeque::new();
11878
11879 let Some(style) = self.style.as_ref() else {
11880 return;
11881 };
11882
11883 for chunk in chunks {
11884 let highlight = chunk
11885 .syntax_highlight_id
11886 .and_then(|id| id.name(&style.syntax));
11887 let mut chunk_lines = chunk.text.split('\n').peekable();
11888 while let Some(text) = chunk_lines.next() {
11889 let mut merged_with_last_token = false;
11890 if let Some(last_token) = line.back_mut() {
11891 if last_token.highlight == highlight {
11892 last_token.text.push_str(text);
11893 merged_with_last_token = true;
11894 }
11895 }
11896
11897 if !merged_with_last_token {
11898 line.push_back(Chunk {
11899 text: text.into(),
11900 highlight,
11901 });
11902 }
11903
11904 if chunk_lines.peek().is_some() {
11905 if line.len() > 1 && line.front().unwrap().text.is_empty() {
11906 line.pop_front();
11907 }
11908 if line.len() > 1 && line.back().unwrap().text.is_empty() {
11909 line.pop_back();
11910 }
11911
11912 lines.push(mem::take(&mut line));
11913 }
11914 }
11915 }
11916
11917 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11918 return;
11919 };
11920 cx.write_to_clipboard(ClipboardItem::new_string(lines));
11921 }
11922
11923 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11924 &self.inlay_hint_cache
11925 }
11926
11927 pub fn replay_insert_event(
11928 &mut self,
11929 text: &str,
11930 relative_utf16_range: Option<Range<isize>>,
11931 cx: &mut ViewContext<Self>,
11932 ) {
11933 if !self.input_enabled {
11934 cx.emit(EditorEvent::InputIgnored { text: text.into() });
11935 return;
11936 }
11937 if let Some(relative_utf16_range) = relative_utf16_range {
11938 let selections = self.selections.all::<OffsetUtf16>(cx);
11939 self.change_selections(None, cx, |s| {
11940 let new_ranges = selections.into_iter().map(|range| {
11941 let start = OffsetUtf16(
11942 range
11943 .head()
11944 .0
11945 .saturating_add_signed(relative_utf16_range.start),
11946 );
11947 let end = OffsetUtf16(
11948 range
11949 .head()
11950 .0
11951 .saturating_add_signed(relative_utf16_range.end),
11952 );
11953 start..end
11954 });
11955 s.select_ranges(new_ranges);
11956 });
11957 }
11958
11959 self.handle_input(text, cx);
11960 }
11961
11962 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11963 let Some(project) = self.project.as_ref() else {
11964 return false;
11965 };
11966 let project = project.read(cx);
11967
11968 let mut supports = false;
11969 self.buffer().read(cx).for_each_buffer(|buffer| {
11970 if !supports {
11971 supports = project
11972 .language_servers_for_buffer(buffer.read(cx), cx)
11973 .any(
11974 |(_, server)| match server.capabilities().inlay_hint_provider {
11975 Some(lsp::OneOf::Left(enabled)) => enabled,
11976 Some(lsp::OneOf::Right(_)) => true,
11977 None => false,
11978 },
11979 )
11980 }
11981 });
11982 supports
11983 }
11984
11985 pub fn focus(&self, cx: &mut WindowContext) {
11986 cx.focus(&self.focus_handle)
11987 }
11988
11989 pub fn is_focused(&self, cx: &WindowContext) -> bool {
11990 self.focus_handle.is_focused(cx)
11991 }
11992
11993 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11994 cx.emit(EditorEvent::Focused);
11995
11996 if let Some(descendant) = self
11997 .last_focused_descendant
11998 .take()
11999 .and_then(|descendant| descendant.upgrade())
12000 {
12001 cx.focus(&descendant);
12002 } else {
12003 if let Some(blame) = self.blame.as_ref() {
12004 blame.update(cx, GitBlame::focus)
12005 }
12006
12007 self.blink_manager.update(cx, BlinkManager::enable);
12008 self.show_cursor_names(cx);
12009 self.buffer.update(cx, |buffer, cx| {
12010 buffer.finalize_last_transaction(cx);
12011 if self.leader_peer_id.is_none() {
12012 buffer.set_active_selections(
12013 &self.selections.disjoint_anchors(),
12014 self.selections.line_mode,
12015 self.cursor_shape,
12016 cx,
12017 );
12018 }
12019 });
12020 }
12021 }
12022
12023 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12024 cx.emit(EditorEvent::FocusedIn)
12025 }
12026
12027 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12028 if event.blurred != self.focus_handle {
12029 self.last_focused_descendant = Some(event.blurred);
12030 }
12031 }
12032
12033 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12034 self.blink_manager.update(cx, BlinkManager::disable);
12035 self.buffer
12036 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12037
12038 if let Some(blame) = self.blame.as_ref() {
12039 blame.update(cx, GitBlame::blur)
12040 }
12041 if !self.hover_state.focused(cx) {
12042 hide_hover(self, cx);
12043 }
12044
12045 self.hide_context_menu(cx);
12046 cx.emit(EditorEvent::Blurred);
12047 cx.notify();
12048 }
12049
12050 pub fn register_action<A: Action>(
12051 &mut self,
12052 listener: impl Fn(&A, &mut WindowContext) + 'static,
12053 ) -> Subscription {
12054 let id = self.next_editor_action_id.post_inc();
12055 let listener = Arc::new(listener);
12056 self.editor_actions.borrow_mut().insert(
12057 id,
12058 Box::new(move |cx| {
12059 let cx = cx.window_context();
12060 let listener = listener.clone();
12061 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12062 let action = action.downcast_ref().unwrap();
12063 if phase == DispatchPhase::Bubble {
12064 listener(action, cx)
12065 }
12066 })
12067 }),
12068 );
12069
12070 let editor_actions = self.editor_actions.clone();
12071 Subscription::new(move || {
12072 editor_actions.borrow_mut().remove(&id);
12073 })
12074 }
12075
12076 pub fn file_header_size(&self) -> u32 {
12077 self.file_header_size
12078 }
12079
12080 pub fn revert(
12081 &mut self,
12082 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12083 cx: &mut ViewContext<Self>,
12084 ) {
12085 self.buffer().update(cx, |multi_buffer, cx| {
12086 for (buffer_id, changes) in revert_changes {
12087 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12088 buffer.update(cx, |buffer, cx| {
12089 buffer.edit(
12090 changes.into_iter().map(|(range, text)| {
12091 (range, text.to_string().map(Arc::<str>::from))
12092 }),
12093 None,
12094 cx,
12095 );
12096 });
12097 }
12098 }
12099 });
12100 self.change_selections(None, cx, |selections| selections.refresh());
12101 }
12102
12103 pub fn to_pixel_point(
12104 &mut self,
12105 source: multi_buffer::Anchor,
12106 editor_snapshot: &EditorSnapshot,
12107 cx: &mut ViewContext<Self>,
12108 ) -> Option<gpui::Point<Pixels>> {
12109 let source_point = source.to_display_point(editor_snapshot);
12110 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12111 }
12112
12113 pub fn display_to_pixel_point(
12114 &mut self,
12115 source: DisplayPoint,
12116 editor_snapshot: &EditorSnapshot,
12117 cx: &mut ViewContext<Self>,
12118 ) -> Option<gpui::Point<Pixels>> {
12119 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12120 let text_layout_details = self.text_layout_details(cx);
12121 let scroll_top = text_layout_details
12122 .scroll_anchor
12123 .scroll_position(editor_snapshot)
12124 .y;
12125
12126 if source.row().as_f32() < scroll_top.floor() {
12127 return None;
12128 }
12129 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12130 let source_y = line_height * (source.row().as_f32() - scroll_top);
12131 Some(gpui::Point::new(source_x, source_y))
12132 }
12133
12134 fn gutter_bounds(&self) -> Option<Bounds<Pixels>> {
12135 let bounds = self.last_bounds?;
12136 Some(element::gutter_bounds(bounds, self.gutter_dimensions))
12137 }
12138
12139 pub fn has_active_completions_menu(&self) -> bool {
12140 self.context_menu.read().as_ref().map_or(false, |menu| {
12141 menu.visible() && matches!(menu, ContextMenu::Completions(_))
12142 })
12143 }
12144
12145 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12146 self.addons
12147 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12148 }
12149
12150 pub fn unregister_addon<T: Addon>(&mut self) {
12151 self.addons.remove(&std::any::TypeId::of::<T>());
12152 }
12153
12154 pub fn addon<T: Addon>(&self) -> Option<&T> {
12155 let type_id = std::any::TypeId::of::<T>();
12156 self.addons
12157 .get(&type_id)
12158 .and_then(|item| item.to_any().downcast_ref::<T>())
12159 }
12160}
12161
12162fn hunks_for_selections(
12163 multi_buffer_snapshot: &MultiBufferSnapshot,
12164 selections: &[Selection<Anchor>],
12165) -> Vec<DiffHunk<MultiBufferRow>> {
12166 let buffer_rows_for_selections = selections.iter().map(|selection| {
12167 let head = selection.head();
12168 let tail = selection.tail();
12169 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12170 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12171 if start > end {
12172 end..start
12173 } else {
12174 start..end
12175 }
12176 });
12177
12178 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12179}
12180
12181pub fn hunks_for_rows(
12182 rows: impl Iterator<Item = Range<MultiBufferRow>>,
12183 multi_buffer_snapshot: &MultiBufferSnapshot,
12184) -> Vec<DiffHunk<MultiBufferRow>> {
12185 let mut hunks = Vec::new();
12186 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12187 HashMap::default();
12188 for selected_multi_buffer_rows in rows {
12189 let query_rows =
12190 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12191 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12192 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12193 // when the caret is just above or just below the deleted hunk.
12194 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12195 let related_to_selection = if allow_adjacent {
12196 hunk.associated_range.overlaps(&query_rows)
12197 || hunk.associated_range.start == query_rows.end
12198 || hunk.associated_range.end == query_rows.start
12199 } else {
12200 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12201 // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12202 hunk.associated_range.overlaps(&selected_multi_buffer_rows)
12203 || selected_multi_buffer_rows.end == hunk.associated_range.start
12204 };
12205 if related_to_selection {
12206 if !processed_buffer_rows
12207 .entry(hunk.buffer_id)
12208 .or_default()
12209 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12210 {
12211 continue;
12212 }
12213 hunks.push(hunk);
12214 }
12215 }
12216 }
12217
12218 hunks
12219}
12220
12221pub trait CollaborationHub {
12222 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12223 fn user_participant_indices<'a>(
12224 &self,
12225 cx: &'a AppContext,
12226 ) -> &'a HashMap<u64, ParticipantIndex>;
12227 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12228}
12229
12230impl CollaborationHub for Model<Project> {
12231 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12232 self.read(cx).collaborators()
12233 }
12234
12235 fn user_participant_indices<'a>(
12236 &self,
12237 cx: &'a AppContext,
12238 ) -> &'a HashMap<u64, ParticipantIndex> {
12239 self.read(cx).user_store().read(cx).participant_indices()
12240 }
12241
12242 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12243 let this = self.read(cx);
12244 let user_ids = this.collaborators().values().map(|c| c.user_id);
12245 this.user_store().read_with(cx, |user_store, cx| {
12246 user_store.participant_names(user_ids, cx)
12247 })
12248 }
12249}
12250
12251pub trait CompletionProvider {
12252 fn completions(
12253 &self,
12254 buffer: &Model<Buffer>,
12255 buffer_position: text::Anchor,
12256 trigger: CompletionContext,
12257 cx: &mut ViewContext<Editor>,
12258 ) -> Task<Result<Vec<Completion>>>;
12259
12260 fn resolve_completions(
12261 &self,
12262 buffer: Model<Buffer>,
12263 completion_indices: Vec<usize>,
12264 completions: Arc<RwLock<Box<[Completion]>>>,
12265 cx: &mut ViewContext<Editor>,
12266 ) -> Task<Result<bool>>;
12267
12268 fn apply_additional_edits_for_completion(
12269 &self,
12270 buffer: Model<Buffer>,
12271 completion: Completion,
12272 push_to_history: bool,
12273 cx: &mut ViewContext<Editor>,
12274 ) -> Task<Result<Option<language::Transaction>>>;
12275
12276 fn is_completion_trigger(
12277 &self,
12278 buffer: &Model<Buffer>,
12279 position: language::Anchor,
12280 text: &str,
12281 trigger_in_words: bool,
12282 cx: &mut ViewContext<Editor>,
12283 ) -> bool;
12284
12285 fn sort_completions(&self) -> bool {
12286 true
12287 }
12288}
12289
12290fn snippet_completions(
12291 project: &Project,
12292 buffer: &Model<Buffer>,
12293 buffer_position: text::Anchor,
12294 cx: &mut AppContext,
12295) -> Vec<Completion> {
12296 let language = buffer.read(cx).language_at(buffer_position);
12297 let language_name = language.as_ref().map(|language| language.lsp_id());
12298 let snippet_store = project.snippets().read(cx);
12299 let snippets = snippet_store.snippets_for(language_name, cx);
12300
12301 if snippets.is_empty() {
12302 return vec![];
12303 }
12304 let snapshot = buffer.read(cx).text_snapshot();
12305 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12306
12307 let mut lines = chunks.lines();
12308 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12309 return vec![];
12310 };
12311
12312 let scope = language.map(|language| language.default_scope());
12313 let classifier = CharClassifier::new(scope).for_completion(true);
12314 let mut last_word = line_at
12315 .chars()
12316 .rev()
12317 .take_while(|c| classifier.is_word(*c))
12318 .collect::<String>();
12319 last_word = last_word.chars().rev().collect();
12320 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12321 let to_lsp = |point: &text::Anchor| {
12322 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12323 point_to_lsp(end)
12324 };
12325 let lsp_end = to_lsp(&buffer_position);
12326 snippets
12327 .into_iter()
12328 .filter_map(|snippet| {
12329 let matching_prefix = snippet
12330 .prefix
12331 .iter()
12332 .find(|prefix| prefix.starts_with(&last_word))?;
12333 let start = as_offset - last_word.len();
12334 let start = snapshot.anchor_before(start);
12335 let range = start..buffer_position;
12336 let lsp_start = to_lsp(&start);
12337 let lsp_range = lsp::Range {
12338 start: lsp_start,
12339 end: lsp_end,
12340 };
12341 Some(Completion {
12342 old_range: range,
12343 new_text: snippet.body.clone(),
12344 label: CodeLabel {
12345 text: matching_prefix.clone(),
12346 runs: vec![],
12347 filter_range: 0..matching_prefix.len(),
12348 },
12349 server_id: LanguageServerId(usize::MAX),
12350 documentation: snippet.description.clone().map(Documentation::SingleLine),
12351 lsp_completion: lsp::CompletionItem {
12352 label: snippet.prefix.first().unwrap().clone(),
12353 kind: Some(CompletionItemKind::SNIPPET),
12354 label_details: snippet.description.as_ref().map(|description| {
12355 lsp::CompletionItemLabelDetails {
12356 detail: Some(description.clone()),
12357 description: None,
12358 }
12359 }),
12360 insert_text_format: Some(InsertTextFormat::SNIPPET),
12361 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12362 lsp::InsertReplaceEdit {
12363 new_text: snippet.body.clone(),
12364 insert: lsp_range,
12365 replace: lsp_range,
12366 },
12367 )),
12368 filter_text: Some(snippet.body.clone()),
12369 sort_text: Some(char::MAX.to_string()),
12370 ..Default::default()
12371 },
12372 confirm: None,
12373 })
12374 })
12375 .collect()
12376}
12377
12378impl CompletionProvider for Model<Project> {
12379 fn completions(
12380 &self,
12381 buffer: &Model<Buffer>,
12382 buffer_position: text::Anchor,
12383 options: CompletionContext,
12384 cx: &mut ViewContext<Editor>,
12385 ) -> Task<Result<Vec<Completion>>> {
12386 self.update(cx, |project, cx| {
12387 let snippets = snippet_completions(project, buffer, buffer_position, cx);
12388 let project_completions = project.completions(buffer, buffer_position, options, cx);
12389 cx.background_executor().spawn(async move {
12390 let mut completions = project_completions.await?;
12391 //let snippets = snippets.into_iter().;
12392 completions.extend(snippets);
12393 Ok(completions)
12394 })
12395 })
12396 }
12397
12398 fn resolve_completions(
12399 &self,
12400 buffer: Model<Buffer>,
12401 completion_indices: Vec<usize>,
12402 completions: Arc<RwLock<Box<[Completion]>>>,
12403 cx: &mut ViewContext<Editor>,
12404 ) -> Task<Result<bool>> {
12405 self.update(cx, |project, cx| {
12406 project.resolve_completions(buffer, completion_indices, completions, cx)
12407 })
12408 }
12409
12410 fn apply_additional_edits_for_completion(
12411 &self,
12412 buffer: Model<Buffer>,
12413 completion: Completion,
12414 push_to_history: bool,
12415 cx: &mut ViewContext<Editor>,
12416 ) -> Task<Result<Option<language::Transaction>>> {
12417 self.update(cx, |project, cx| {
12418 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12419 })
12420 }
12421
12422 fn is_completion_trigger(
12423 &self,
12424 buffer: &Model<Buffer>,
12425 position: language::Anchor,
12426 text: &str,
12427 trigger_in_words: bool,
12428 cx: &mut ViewContext<Editor>,
12429 ) -> bool {
12430 if !EditorSettings::get_global(cx).show_completions_on_input {
12431 return false;
12432 }
12433
12434 let mut chars = text.chars();
12435 let char = if let Some(char) = chars.next() {
12436 char
12437 } else {
12438 return false;
12439 };
12440 if chars.next().is_some() {
12441 return false;
12442 }
12443
12444 let buffer = buffer.read(cx);
12445 let classifier = buffer
12446 .snapshot()
12447 .char_classifier_at(position)
12448 .for_completion(true);
12449 if trigger_in_words && classifier.is_word(char) {
12450 return true;
12451 }
12452
12453 buffer
12454 .completion_triggers()
12455 .iter()
12456 .any(|string| string == text)
12457 }
12458}
12459
12460fn inlay_hint_settings(
12461 location: Anchor,
12462 snapshot: &MultiBufferSnapshot,
12463 cx: &mut ViewContext<'_, Editor>,
12464) -> InlayHintSettings {
12465 let file = snapshot.file_at(location);
12466 let language = snapshot.language_at(location);
12467 let settings = all_language_settings(file, cx);
12468 settings
12469 .language(language.map(|l| l.name()).as_ref())
12470 .inlay_hints
12471}
12472
12473fn consume_contiguous_rows(
12474 contiguous_row_selections: &mut Vec<Selection<Point>>,
12475 selection: &Selection<Point>,
12476 display_map: &DisplaySnapshot,
12477 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12478) -> (MultiBufferRow, MultiBufferRow) {
12479 contiguous_row_selections.push(selection.clone());
12480 let start_row = MultiBufferRow(selection.start.row);
12481 let mut end_row = ending_row(selection, display_map);
12482
12483 while let Some(next_selection) = selections.peek() {
12484 if next_selection.start.row <= end_row.0 {
12485 end_row = ending_row(next_selection, display_map);
12486 contiguous_row_selections.push(selections.next().unwrap().clone());
12487 } else {
12488 break;
12489 }
12490 }
12491 (start_row, end_row)
12492}
12493
12494fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12495 if next_selection.end.column > 0 || next_selection.is_empty() {
12496 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12497 } else {
12498 MultiBufferRow(next_selection.end.row)
12499 }
12500}
12501
12502impl EditorSnapshot {
12503 pub fn remote_selections_in_range<'a>(
12504 &'a self,
12505 range: &'a Range<Anchor>,
12506 collaboration_hub: &dyn CollaborationHub,
12507 cx: &'a AppContext,
12508 ) -> impl 'a + Iterator<Item = RemoteSelection> {
12509 let participant_names = collaboration_hub.user_names(cx);
12510 let participant_indices = collaboration_hub.user_participant_indices(cx);
12511 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12512 let collaborators_by_replica_id = collaborators_by_peer_id
12513 .iter()
12514 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12515 .collect::<HashMap<_, _>>();
12516 self.buffer_snapshot
12517 .selections_in_range(range, false)
12518 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12519 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12520 let participant_index = participant_indices.get(&collaborator.user_id).copied();
12521 let user_name = participant_names.get(&collaborator.user_id).cloned();
12522 Some(RemoteSelection {
12523 replica_id,
12524 selection,
12525 cursor_shape,
12526 line_mode,
12527 participant_index,
12528 peer_id: collaborator.peer_id,
12529 user_name,
12530 })
12531 })
12532 }
12533
12534 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12535 self.display_snapshot.buffer_snapshot.language_at(position)
12536 }
12537
12538 pub fn is_focused(&self) -> bool {
12539 self.is_focused
12540 }
12541
12542 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12543 self.placeholder_text.as_ref()
12544 }
12545
12546 pub fn scroll_position(&self) -> gpui::Point<f32> {
12547 self.scroll_anchor.scroll_position(&self.display_snapshot)
12548 }
12549
12550 fn gutter_dimensions(
12551 &self,
12552 font_id: FontId,
12553 font_size: Pixels,
12554 em_width: Pixels,
12555 max_line_number_width: Pixels,
12556 cx: &AppContext,
12557 ) -> GutterDimensions {
12558 if !self.show_gutter {
12559 return GutterDimensions::default();
12560 }
12561 let descent = cx.text_system().descent(font_id, font_size);
12562
12563 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12564 matches!(
12565 ProjectSettings::get_global(cx).git.git_gutter,
12566 GitGutterSetting::TrackedFiles
12567 )
12568 });
12569 let gutter_settings = EditorSettings::get_global(cx).gutter;
12570 let show_line_numbers = self
12571 .show_line_numbers
12572 .unwrap_or(gutter_settings.line_numbers);
12573 let line_gutter_width = if show_line_numbers {
12574 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12575 let min_width_for_number_on_gutter = em_width * 4.0;
12576 max_line_number_width.max(min_width_for_number_on_gutter)
12577 } else {
12578 0.0.into()
12579 };
12580
12581 let show_code_actions = self
12582 .show_code_actions
12583 .unwrap_or(gutter_settings.code_actions);
12584
12585 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12586
12587 let git_blame_entries_width = self
12588 .render_git_blame_gutter
12589 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12590
12591 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12592 left_padding += if show_code_actions || show_runnables {
12593 em_width * 3.0
12594 } else if show_git_gutter && show_line_numbers {
12595 em_width * 2.0
12596 } else if show_git_gutter || show_line_numbers {
12597 em_width
12598 } else {
12599 px(0.)
12600 };
12601
12602 let right_padding = if gutter_settings.folds && show_line_numbers {
12603 em_width * 4.0
12604 } else if gutter_settings.folds {
12605 em_width * 3.0
12606 } else if show_line_numbers {
12607 em_width
12608 } else {
12609 px(0.)
12610 };
12611
12612 GutterDimensions {
12613 left_padding,
12614 right_padding,
12615 width: line_gutter_width + left_padding + right_padding,
12616 margin: -descent,
12617 git_blame_entries_width,
12618 }
12619 }
12620
12621 pub fn render_fold_toggle(
12622 &self,
12623 buffer_row: MultiBufferRow,
12624 row_contains_cursor: bool,
12625 editor: View<Editor>,
12626 cx: &mut WindowContext,
12627 ) -> Option<AnyElement> {
12628 let folded = self.is_line_folded(buffer_row);
12629
12630 if let Some(crease) = self
12631 .crease_snapshot
12632 .query_row(buffer_row, &self.buffer_snapshot)
12633 {
12634 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12635 if folded {
12636 editor.update(cx, |editor, cx| {
12637 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12638 });
12639 } else {
12640 editor.update(cx, |editor, cx| {
12641 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12642 });
12643 }
12644 });
12645
12646 Some((crease.render_toggle)(
12647 buffer_row,
12648 folded,
12649 toggle_callback,
12650 cx,
12651 ))
12652 } else if folded
12653 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12654 {
12655 Some(
12656 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12657 .selected(folded)
12658 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12659 if folded {
12660 this.unfold_at(&UnfoldAt { buffer_row }, cx);
12661 } else {
12662 this.fold_at(&FoldAt { buffer_row }, cx);
12663 }
12664 }))
12665 .into_any_element(),
12666 )
12667 } else {
12668 None
12669 }
12670 }
12671
12672 pub fn render_crease_trailer(
12673 &self,
12674 buffer_row: MultiBufferRow,
12675 cx: &mut WindowContext,
12676 ) -> Option<AnyElement> {
12677 let folded = self.is_line_folded(buffer_row);
12678 let crease = self
12679 .crease_snapshot
12680 .query_row(buffer_row, &self.buffer_snapshot)?;
12681 Some((crease.render_trailer)(buffer_row, folded, cx))
12682 }
12683}
12684
12685impl Deref for EditorSnapshot {
12686 type Target = DisplaySnapshot;
12687
12688 fn deref(&self) -> &Self::Target {
12689 &self.display_snapshot
12690 }
12691}
12692
12693#[derive(Clone, Debug, PartialEq, Eq)]
12694pub enum EditorEvent {
12695 InputIgnored {
12696 text: Arc<str>,
12697 },
12698 InputHandled {
12699 utf16_range_to_replace: Option<Range<isize>>,
12700 text: Arc<str>,
12701 },
12702 ExcerptsAdded {
12703 buffer: Model<Buffer>,
12704 predecessor: ExcerptId,
12705 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12706 },
12707 ExcerptsRemoved {
12708 ids: Vec<ExcerptId>,
12709 },
12710 ExcerptsEdited {
12711 ids: Vec<ExcerptId>,
12712 },
12713 ExcerptsExpanded {
12714 ids: Vec<ExcerptId>,
12715 },
12716 BufferEdited,
12717 Edited {
12718 transaction_id: clock::Lamport,
12719 },
12720 Reparsed(BufferId),
12721 Focused,
12722 FocusedIn,
12723 Blurred,
12724 DirtyChanged,
12725 Saved,
12726 TitleChanged,
12727 DiffBaseChanged,
12728 SelectionsChanged {
12729 local: bool,
12730 },
12731 ScrollPositionChanged {
12732 local: bool,
12733 autoscroll: bool,
12734 },
12735 Closed,
12736 TransactionUndone {
12737 transaction_id: clock::Lamport,
12738 },
12739 TransactionBegun {
12740 transaction_id: clock::Lamport,
12741 },
12742}
12743
12744impl EventEmitter<EditorEvent> for Editor {}
12745
12746impl FocusableView for Editor {
12747 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12748 self.focus_handle.clone()
12749 }
12750}
12751
12752impl Render for Editor {
12753 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12754 let settings = ThemeSettings::get_global(cx);
12755
12756 let text_style = match self.mode {
12757 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12758 color: cx.theme().colors().editor_foreground,
12759 font_family: settings.ui_font.family.clone(),
12760 font_features: settings.ui_font.features.clone(),
12761 font_fallbacks: settings.ui_font.fallbacks.clone(),
12762 font_size: rems(0.875).into(),
12763 font_weight: settings.ui_font.weight,
12764 line_height: relative(settings.buffer_line_height.value()),
12765 ..Default::default()
12766 },
12767 EditorMode::Full => TextStyle {
12768 color: cx.theme().colors().editor_foreground,
12769 font_family: settings.buffer_font.family.clone(),
12770 font_features: settings.buffer_font.features.clone(),
12771 font_fallbacks: settings.buffer_font.fallbacks.clone(),
12772 font_size: settings.buffer_font_size(cx).into(),
12773 font_weight: settings.buffer_font.weight,
12774 line_height: relative(settings.buffer_line_height.value()),
12775 ..Default::default()
12776 },
12777 };
12778
12779 let background = match self.mode {
12780 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12781 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12782 EditorMode::Full => cx.theme().colors().editor_background,
12783 };
12784
12785 EditorElement::new(
12786 cx.view(),
12787 EditorStyle {
12788 background,
12789 local_player: cx.theme().players().local(),
12790 text: text_style,
12791 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12792 syntax: cx.theme().syntax().clone(),
12793 status: cx.theme().status().clone(),
12794 inlay_hints_style: HighlightStyle {
12795 color: Some(cx.theme().status().hint),
12796 ..HighlightStyle::default()
12797 },
12798 suggestions_style: HighlightStyle {
12799 color: Some(cx.theme().status().predictive),
12800 ..HighlightStyle::default()
12801 },
12802 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
12803 },
12804 )
12805 }
12806}
12807
12808impl ViewInputHandler for Editor {
12809 fn text_for_range(
12810 &mut self,
12811 range_utf16: Range<usize>,
12812 cx: &mut ViewContext<Self>,
12813 ) -> Option<String> {
12814 Some(
12815 self.buffer
12816 .read(cx)
12817 .read(cx)
12818 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12819 .collect(),
12820 )
12821 }
12822
12823 fn selected_text_range(
12824 &mut self,
12825 ignore_disabled_input: bool,
12826 cx: &mut ViewContext<Self>,
12827 ) -> Option<UTF16Selection> {
12828 // Prevent the IME menu from appearing when holding down an alphabetic key
12829 // while input is disabled.
12830 if !ignore_disabled_input && !self.input_enabled {
12831 return None;
12832 }
12833
12834 let selection = self.selections.newest::<OffsetUtf16>(cx);
12835 let range = selection.range();
12836
12837 Some(UTF16Selection {
12838 range: range.start.0..range.end.0,
12839 reversed: selection.reversed,
12840 })
12841 }
12842
12843 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12844 let snapshot = self.buffer.read(cx).read(cx);
12845 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
12846 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12847 }
12848
12849 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12850 self.clear_highlights::<InputComposition>(cx);
12851 self.ime_transaction.take();
12852 }
12853
12854 fn replace_text_in_range(
12855 &mut self,
12856 range_utf16: Option<Range<usize>>,
12857 text: &str,
12858 cx: &mut ViewContext<Self>,
12859 ) {
12860 if !self.input_enabled {
12861 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12862 return;
12863 }
12864
12865 self.transact(cx, |this, cx| {
12866 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12867 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12868 Some(this.selection_replacement_ranges(range_utf16, cx))
12869 } else {
12870 this.marked_text_ranges(cx)
12871 };
12872
12873 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12874 let newest_selection_id = this.selections.newest_anchor().id;
12875 this.selections
12876 .all::<OffsetUtf16>(cx)
12877 .iter()
12878 .zip(ranges_to_replace.iter())
12879 .find_map(|(selection, range)| {
12880 if selection.id == newest_selection_id {
12881 Some(
12882 (range.start.0 as isize - selection.head().0 as isize)
12883 ..(range.end.0 as isize - selection.head().0 as isize),
12884 )
12885 } else {
12886 None
12887 }
12888 })
12889 });
12890
12891 cx.emit(EditorEvent::InputHandled {
12892 utf16_range_to_replace: range_to_replace,
12893 text: text.into(),
12894 });
12895
12896 if let Some(new_selected_ranges) = new_selected_ranges {
12897 this.change_selections(None, cx, |selections| {
12898 selections.select_ranges(new_selected_ranges)
12899 });
12900 this.backspace(&Default::default(), cx);
12901 }
12902
12903 this.handle_input(text, cx);
12904 });
12905
12906 if let Some(transaction) = self.ime_transaction {
12907 self.buffer.update(cx, |buffer, cx| {
12908 buffer.group_until_transaction(transaction, cx);
12909 });
12910 }
12911
12912 self.unmark_text(cx);
12913 }
12914
12915 fn replace_and_mark_text_in_range(
12916 &mut self,
12917 range_utf16: Option<Range<usize>>,
12918 text: &str,
12919 new_selected_range_utf16: Option<Range<usize>>,
12920 cx: &mut ViewContext<Self>,
12921 ) {
12922 if !self.input_enabled {
12923 return;
12924 }
12925
12926 let transaction = self.transact(cx, |this, cx| {
12927 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12928 let snapshot = this.buffer.read(cx).read(cx);
12929 if let Some(relative_range_utf16) = range_utf16.as_ref() {
12930 for marked_range in &mut marked_ranges {
12931 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12932 marked_range.start.0 += relative_range_utf16.start;
12933 marked_range.start =
12934 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12935 marked_range.end =
12936 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12937 }
12938 }
12939 Some(marked_ranges)
12940 } else if let Some(range_utf16) = range_utf16 {
12941 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12942 Some(this.selection_replacement_ranges(range_utf16, cx))
12943 } else {
12944 None
12945 };
12946
12947 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12948 let newest_selection_id = this.selections.newest_anchor().id;
12949 this.selections
12950 .all::<OffsetUtf16>(cx)
12951 .iter()
12952 .zip(ranges_to_replace.iter())
12953 .find_map(|(selection, range)| {
12954 if selection.id == newest_selection_id {
12955 Some(
12956 (range.start.0 as isize - selection.head().0 as isize)
12957 ..(range.end.0 as isize - selection.head().0 as isize),
12958 )
12959 } else {
12960 None
12961 }
12962 })
12963 });
12964
12965 cx.emit(EditorEvent::InputHandled {
12966 utf16_range_to_replace: range_to_replace,
12967 text: text.into(),
12968 });
12969
12970 if let Some(ranges) = ranges_to_replace {
12971 this.change_selections(None, cx, |s| s.select_ranges(ranges));
12972 }
12973
12974 let marked_ranges = {
12975 let snapshot = this.buffer.read(cx).read(cx);
12976 this.selections
12977 .disjoint_anchors()
12978 .iter()
12979 .map(|selection| {
12980 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12981 })
12982 .collect::<Vec<_>>()
12983 };
12984
12985 if text.is_empty() {
12986 this.unmark_text(cx);
12987 } else {
12988 this.highlight_text::<InputComposition>(
12989 marked_ranges.clone(),
12990 HighlightStyle {
12991 underline: Some(UnderlineStyle {
12992 thickness: px(1.),
12993 color: None,
12994 wavy: false,
12995 }),
12996 ..Default::default()
12997 },
12998 cx,
12999 );
13000 }
13001
13002 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13003 let use_autoclose = this.use_autoclose;
13004 let use_auto_surround = this.use_auto_surround;
13005 this.set_use_autoclose(false);
13006 this.set_use_auto_surround(false);
13007 this.handle_input(text, cx);
13008 this.set_use_autoclose(use_autoclose);
13009 this.set_use_auto_surround(use_auto_surround);
13010
13011 if let Some(new_selected_range) = new_selected_range_utf16 {
13012 let snapshot = this.buffer.read(cx).read(cx);
13013 let new_selected_ranges = marked_ranges
13014 .into_iter()
13015 .map(|marked_range| {
13016 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13017 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13018 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13019 snapshot.clip_offset_utf16(new_start, Bias::Left)
13020 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13021 })
13022 .collect::<Vec<_>>();
13023
13024 drop(snapshot);
13025 this.change_selections(None, cx, |selections| {
13026 selections.select_ranges(new_selected_ranges)
13027 });
13028 }
13029 });
13030
13031 self.ime_transaction = self.ime_transaction.or(transaction);
13032 if let Some(transaction) = self.ime_transaction {
13033 self.buffer.update(cx, |buffer, cx| {
13034 buffer.group_until_transaction(transaction, cx);
13035 });
13036 }
13037
13038 if self.text_highlights::<InputComposition>(cx).is_none() {
13039 self.ime_transaction.take();
13040 }
13041 }
13042
13043 fn bounds_for_range(
13044 &mut self,
13045 range_utf16: Range<usize>,
13046 element_bounds: gpui::Bounds<Pixels>,
13047 cx: &mut ViewContext<Self>,
13048 ) -> Option<gpui::Bounds<Pixels>> {
13049 let text_layout_details = self.text_layout_details(cx);
13050 let style = &text_layout_details.editor_style;
13051 let font_id = cx.text_system().resolve_font(&style.text.font());
13052 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13053 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13054
13055 let em_width = cx
13056 .text_system()
13057 .typographic_bounds(font_id, font_size, 'm')
13058 .unwrap()
13059 .size
13060 .width;
13061
13062 let snapshot = self.snapshot(cx);
13063 let scroll_position = snapshot.scroll_position();
13064 let scroll_left = scroll_position.x * em_width;
13065
13066 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13067 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13068 + self.gutter_dimensions.width;
13069 let y = line_height * (start.row().as_f32() - scroll_position.y);
13070
13071 Some(Bounds {
13072 origin: element_bounds.origin + point(x, y),
13073 size: size(em_width, line_height),
13074 })
13075 }
13076}
13077
13078trait SelectionExt {
13079 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13080 fn spanned_rows(
13081 &self,
13082 include_end_if_at_line_start: bool,
13083 map: &DisplaySnapshot,
13084 ) -> Range<MultiBufferRow>;
13085}
13086
13087impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
13088 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
13089 let start = self
13090 .start
13091 .to_point(&map.buffer_snapshot)
13092 .to_display_point(map);
13093 let end = self
13094 .end
13095 .to_point(&map.buffer_snapshot)
13096 .to_display_point(map);
13097 if self.reversed {
13098 end..start
13099 } else {
13100 start..end
13101 }
13102 }
13103
13104 fn spanned_rows(
13105 &self,
13106 include_end_if_at_line_start: bool,
13107 map: &DisplaySnapshot,
13108 ) -> Range<MultiBufferRow> {
13109 let start = self.start.to_point(&map.buffer_snapshot);
13110 let mut end = self.end.to_point(&map.buffer_snapshot);
13111 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
13112 end.row -= 1;
13113 }
13114
13115 let buffer_start = map.prev_line_boundary(start).0;
13116 let buffer_end = map.next_line_boundary(end).0;
13117 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
13118 }
13119}
13120
13121impl<T: InvalidationRegion> InvalidationStack<T> {
13122 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
13123 where
13124 S: Clone + ToOffset,
13125 {
13126 while let Some(region) = self.last() {
13127 let all_selections_inside_invalidation_ranges =
13128 if selections.len() == region.ranges().len() {
13129 selections
13130 .iter()
13131 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
13132 .all(|(selection, invalidation_range)| {
13133 let head = selection.head().to_offset(buffer);
13134 invalidation_range.start <= head && invalidation_range.end >= head
13135 })
13136 } else {
13137 false
13138 };
13139
13140 if all_selections_inside_invalidation_ranges {
13141 break;
13142 } else {
13143 self.pop();
13144 }
13145 }
13146 }
13147}
13148
13149impl<T> Default for InvalidationStack<T> {
13150 fn default() -> Self {
13151 Self(Default::default())
13152 }
13153}
13154
13155impl<T> Deref for InvalidationStack<T> {
13156 type Target = Vec<T>;
13157
13158 fn deref(&self) -> &Self::Target {
13159 &self.0
13160 }
13161}
13162
13163impl<T> DerefMut for InvalidationStack<T> {
13164 fn deref_mut(&mut self) -> &mut Self::Target {
13165 &mut self.0
13166 }
13167}
13168
13169impl InvalidationRegion for SnippetState {
13170 fn ranges(&self) -> &[Range<Anchor>] {
13171 &self.ranges[self.active_index]
13172 }
13173}
13174
13175pub fn diagnostic_block_renderer(
13176 diagnostic: Diagnostic,
13177 max_message_rows: Option<u8>,
13178 allow_closing: bool,
13179 _is_valid: bool,
13180) -> RenderBlock {
13181 let (text_without_backticks, code_ranges) =
13182 highlight_diagnostic_message(&diagnostic, max_message_rows);
13183
13184 Box::new(move |cx: &mut BlockContext| {
13185 let group_id: SharedString = cx.block_id.to_string().into();
13186
13187 let mut text_style = cx.text_style().clone();
13188 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13189 let theme_settings = ThemeSettings::get_global(cx);
13190 text_style.font_family = theme_settings.buffer_font.family.clone();
13191 text_style.font_style = theme_settings.buffer_font.style;
13192 text_style.font_features = theme_settings.buffer_font.features.clone();
13193 text_style.font_weight = theme_settings.buffer_font.weight;
13194
13195 let multi_line_diagnostic = diagnostic.message.contains('\n');
13196
13197 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13198 if multi_line_diagnostic {
13199 v_flex()
13200 } else {
13201 h_flex()
13202 }
13203 .when(allow_closing, |div| {
13204 div.children(diagnostic.is_primary.then(|| {
13205 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13206 .icon_color(Color::Muted)
13207 .size(ButtonSize::Compact)
13208 .style(ButtonStyle::Transparent)
13209 .visible_on_hover(group_id.clone())
13210 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13211 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13212 }))
13213 })
13214 .child(
13215 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13216 .icon_color(Color::Muted)
13217 .size(ButtonSize::Compact)
13218 .style(ButtonStyle::Transparent)
13219 .visible_on_hover(group_id.clone())
13220 .on_click({
13221 let message = diagnostic.message.clone();
13222 move |_click, cx| {
13223 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13224 }
13225 })
13226 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13227 )
13228 };
13229
13230 let icon_size = buttons(&diagnostic, cx.block_id)
13231 .into_any_element()
13232 .layout_as_root(AvailableSpace::min_size(), cx);
13233
13234 h_flex()
13235 .id(cx.block_id)
13236 .group(group_id.clone())
13237 .relative()
13238 .size_full()
13239 .pl(cx.gutter_dimensions.width)
13240 .w(cx.max_width + cx.gutter_dimensions.width)
13241 .child(
13242 div()
13243 .flex()
13244 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13245 .flex_shrink(),
13246 )
13247 .child(buttons(&diagnostic, cx.block_id))
13248 .child(div().flex().flex_shrink_0().child(
13249 StyledText::new(text_without_backticks.clone()).with_highlights(
13250 &text_style,
13251 code_ranges.iter().map(|range| {
13252 (
13253 range.clone(),
13254 HighlightStyle {
13255 font_weight: Some(FontWeight::BOLD),
13256 ..Default::default()
13257 },
13258 )
13259 }),
13260 ),
13261 ))
13262 .into_any_element()
13263 })
13264}
13265
13266pub fn highlight_diagnostic_message(
13267 diagnostic: &Diagnostic,
13268 mut max_message_rows: Option<u8>,
13269) -> (SharedString, Vec<Range<usize>>) {
13270 let mut text_without_backticks = String::new();
13271 let mut code_ranges = Vec::new();
13272
13273 if let Some(source) = &diagnostic.source {
13274 text_without_backticks.push_str(source);
13275 code_ranges.push(0..source.len());
13276 text_without_backticks.push_str(": ");
13277 }
13278
13279 let mut prev_offset = 0;
13280 let mut in_code_block = false;
13281 let has_row_limit = max_message_rows.is_some();
13282 let mut newline_indices = diagnostic
13283 .message
13284 .match_indices('\n')
13285 .filter(|_| has_row_limit)
13286 .map(|(ix, _)| ix)
13287 .fuse()
13288 .peekable();
13289
13290 for (quote_ix, _) in diagnostic
13291 .message
13292 .match_indices('`')
13293 .chain([(diagnostic.message.len(), "")])
13294 {
13295 let mut first_newline_ix = None;
13296 let mut last_newline_ix = None;
13297 while let Some(newline_ix) = newline_indices.peek() {
13298 if *newline_ix < quote_ix {
13299 if first_newline_ix.is_none() {
13300 first_newline_ix = Some(*newline_ix);
13301 }
13302 last_newline_ix = Some(*newline_ix);
13303
13304 if let Some(rows_left) = &mut max_message_rows {
13305 if *rows_left == 0 {
13306 break;
13307 } else {
13308 *rows_left -= 1;
13309 }
13310 }
13311 let _ = newline_indices.next();
13312 } else {
13313 break;
13314 }
13315 }
13316 let prev_len = text_without_backticks.len();
13317 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
13318 text_without_backticks.push_str(new_text);
13319 if in_code_block {
13320 code_ranges.push(prev_len..text_without_backticks.len());
13321 }
13322 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13323 in_code_block = !in_code_block;
13324 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13325 text_without_backticks.push_str("...");
13326 break;
13327 }
13328 }
13329
13330 (text_without_backticks.into(), code_ranges)
13331}
13332
13333fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13334 match severity {
13335 DiagnosticSeverity::ERROR => colors.error,
13336 DiagnosticSeverity::WARNING => colors.warning,
13337 DiagnosticSeverity::INFORMATION => colors.info,
13338 DiagnosticSeverity::HINT => colors.info,
13339 _ => colors.ignored,
13340 }
13341}
13342
13343pub fn styled_runs_for_code_label<'a>(
13344 label: &'a CodeLabel,
13345 syntax_theme: &'a theme::SyntaxTheme,
13346) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13347 let fade_out = HighlightStyle {
13348 fade_out: Some(0.35),
13349 ..Default::default()
13350 };
13351
13352 let mut prev_end = label.filter_range.end;
13353 label
13354 .runs
13355 .iter()
13356 .enumerate()
13357 .flat_map(move |(ix, (range, highlight_id))| {
13358 let style = if let Some(style) = highlight_id.style(syntax_theme) {
13359 style
13360 } else {
13361 return Default::default();
13362 };
13363 let mut muted_style = style;
13364 muted_style.highlight(fade_out);
13365
13366 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13367 if range.start >= label.filter_range.end {
13368 if range.start > prev_end {
13369 runs.push((prev_end..range.start, fade_out));
13370 }
13371 runs.push((range.clone(), muted_style));
13372 } else if range.end <= label.filter_range.end {
13373 runs.push((range.clone(), style));
13374 } else {
13375 runs.push((range.start..label.filter_range.end, style));
13376 runs.push((label.filter_range.end..range.end, muted_style));
13377 }
13378 prev_end = cmp::max(prev_end, range.end);
13379
13380 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13381 runs.push((prev_end..label.text.len(), fade_out));
13382 }
13383
13384 runs
13385 })
13386}
13387
13388pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13389 let mut prev_index = 0;
13390 let mut prev_codepoint: Option<char> = None;
13391 text.char_indices()
13392 .chain([(text.len(), '\0')])
13393 .filter_map(move |(index, codepoint)| {
13394 let prev_codepoint = prev_codepoint.replace(codepoint)?;
13395 let is_boundary = index == text.len()
13396 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13397 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13398 if is_boundary {
13399 let chunk = &text[prev_index..index];
13400 prev_index = index;
13401 Some(chunk)
13402 } else {
13403 None
13404 }
13405 })
13406}
13407
13408pub trait RangeToAnchorExt: Sized {
13409 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13410
13411 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13412 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13413 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
13414 }
13415}
13416
13417impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13418 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13419 let start_offset = self.start.to_offset(snapshot);
13420 let end_offset = self.end.to_offset(snapshot);
13421 if start_offset == end_offset {
13422 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13423 } else {
13424 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13425 }
13426 }
13427}
13428
13429pub trait RowExt {
13430 fn as_f32(&self) -> f32;
13431
13432 fn next_row(&self) -> Self;
13433
13434 fn previous_row(&self) -> Self;
13435
13436 fn minus(&self, other: Self) -> u32;
13437}
13438
13439impl RowExt for DisplayRow {
13440 fn as_f32(&self) -> f32 {
13441 self.0 as f32
13442 }
13443
13444 fn next_row(&self) -> Self {
13445 Self(self.0 + 1)
13446 }
13447
13448 fn previous_row(&self) -> Self {
13449 Self(self.0.saturating_sub(1))
13450 }
13451
13452 fn minus(&self, other: Self) -> u32 {
13453 self.0 - other.0
13454 }
13455}
13456
13457impl RowExt for MultiBufferRow {
13458 fn as_f32(&self) -> f32 {
13459 self.0 as f32
13460 }
13461
13462 fn next_row(&self) -> Self {
13463 Self(self.0 + 1)
13464 }
13465
13466 fn previous_row(&self) -> Self {
13467 Self(self.0.saturating_sub(1))
13468 }
13469
13470 fn minus(&self, other: Self) -> u32 {
13471 self.0 - other.0
13472 }
13473}
13474
13475trait RowRangeExt {
13476 type Row;
13477
13478 fn len(&self) -> usize;
13479
13480 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13481}
13482
13483impl RowRangeExt for Range<MultiBufferRow> {
13484 type Row = MultiBufferRow;
13485
13486 fn len(&self) -> usize {
13487 (self.end.0 - self.start.0) as usize
13488 }
13489
13490 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13491 (self.start.0..self.end.0).map(MultiBufferRow)
13492 }
13493}
13494
13495impl RowRangeExt for Range<DisplayRow> {
13496 type Row = DisplayRow;
13497
13498 fn len(&self) -> usize {
13499 (self.end.0 - self.start.0) as usize
13500 }
13501
13502 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13503 (self.start.0..self.end.0).map(DisplayRow)
13504 }
13505}
13506
13507fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13508 if hunk.diff_base_byte_range.is_empty() {
13509 DiffHunkStatus::Added
13510 } else if hunk.associated_range.is_empty() {
13511 DiffHunkStatus::Removed
13512 } else {
13513 DiffHunkStatus::Modified
13514 }
13515}
13516
13517/// If select range has more than one line, we
13518/// just point the cursor to range.start.
13519fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
13520 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
13521 range
13522 } else {
13523 range.start..range.start
13524 }
13525}