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