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::{CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine};
63pub use editor_settings_controls::*;
64use element::LineWithInvisibles;
65pub use element::{
66 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
67};
68use futures::FutureExt;
69use fuzzy::{StringMatch, StringMatchCandidate};
70use git::blame::GitBlame;
71use git::diff_hunk_to_display;
72use gpui::{
73 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
74 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
75 ClipboardItem, Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle,
76 FocusOutEvent, FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText,
77 KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
78 SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
79 UTF16Selection, UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler,
80 VisualContext, WeakFocusHandle, WeakView, WindowContext,
81};
82use highlight_matching_bracket::refresh_matching_bracket_highlights;
83use hover_popover::{hide_hover, HoverState};
84use hunk_diff::ExpandedHunks;
85pub(crate) use hunk_diff::HoveredHunk;
86use indent_guides::ActiveIndentGuidesState;
87use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
88pub use inline_completion_provider::*;
89pub use items::MAX_TAB_TITLE_LEN;
90use itertools::Itertools;
91use language::{
92 char_kind,
93 language_settings::{self, all_language_settings, InlayHintSettings},
94 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
95 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
96 Point, Selection, SelectionGoal, TransactionId,
97};
98use language::{point_to_lsp, BufferRow, Runnable, RunnableRange};
99use linked_editing_ranges::refresh_linked_ranges;
100use task::{ResolvedTask, TaskTemplate, TaskVariables};
101
102use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
103pub use lsp::CompletionContext;
104use lsp::{
105 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
106 LanguageServerId,
107};
108use mouse_context_menu::MouseContextMenu;
109use movement::TextLayoutDetails;
110pub use multi_buffer::{
111 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
112 ToPoint,
113};
114use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
115use ordered_float::OrderedFloat;
116use parking_lot::{Mutex, RwLock};
117use project::project_settings::{GitGutterSetting, ProjectSettings};
118use project::{
119 CodeAction, Completion, CompletionIntent, FormatTrigger, Item, Location, Project, ProjectPath,
120 ProjectTransaction, TaskSourceKind, WorktreeId,
121};
122use rand::prelude::*;
123use rpc::{proto::*, ErrorExt};
124use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
125use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
126use serde::{Deserialize, Serialize};
127use settings::{update_settings_file, Settings, SettingsStore};
128use smallvec::SmallVec;
129use snippet::Snippet;
130use std::{
131 any::TypeId,
132 borrow::Cow,
133 cell::RefCell,
134 cmp::{self, Ordering, Reverse},
135 mem,
136 num::NonZeroU32,
137 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
138 path::{Path, PathBuf},
139 rc::Rc,
140 sync::Arc,
141 time::{Duration, Instant},
142};
143pub use sum_tree::Bias;
144use sum_tree::TreeMap;
145use text::{BufferId, OffsetUtf16, Rope};
146use theme::{
147 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
148 ThemeColors, ThemeSettings,
149};
150use ui::{
151 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
152 ListItem, Popover, Tooltip,
153};
154use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
155use workspace::item::{ItemHandle, PreviewTabsSettings};
156use workspace::notifications::{DetachAndPromptErr, NotificationId};
157use workspace::{
158 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
159};
160use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
161
162use crate::hover_links::find_url;
163use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
164
165pub const FILE_HEADER_HEIGHT: u32 = 1;
166pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
167pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
168pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
169const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
170const MAX_LINE_LEN: usize = 1024;
171const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
172const MAX_SELECTION_HISTORY_LEN: usize = 1024;
173pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
174#[doc(hidden)]
175pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
176#[doc(hidden)]
177pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
178
179pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
180pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
181
182pub fn render_parsed_markdown(
183 element_id: impl Into<ElementId>,
184 parsed: &language::ParsedMarkdown,
185 editor_style: &EditorStyle,
186 workspace: Option<WeakView<Workspace>>,
187 cx: &mut WindowContext,
188) -> InteractiveText {
189 let code_span_background_color = cx
190 .theme()
191 .colors()
192 .editor_document_highlight_read_background;
193
194 let highlights = gpui::combine_highlights(
195 parsed.highlights.iter().filter_map(|(range, highlight)| {
196 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
197 Some((range.clone(), highlight))
198 }),
199 parsed
200 .regions
201 .iter()
202 .zip(&parsed.region_ranges)
203 .filter_map(|(region, range)| {
204 if region.code {
205 Some((
206 range.clone(),
207 HighlightStyle {
208 background_color: Some(code_span_background_color),
209 ..Default::default()
210 },
211 ))
212 } else {
213 None
214 }
215 }),
216 );
217
218 let mut links = Vec::new();
219 let mut link_ranges = Vec::new();
220 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
221 if let Some(link) = region.link.clone() {
222 links.push(link);
223 link_ranges.push(range.clone());
224 }
225 }
226
227 InteractiveText::new(
228 element_id,
229 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
230 )
231 .on_click(link_ranges, move |clicked_range_ix, cx| {
232 match &links[clicked_range_ix] {
233 markdown::Link::Web { url } => cx.open_url(url),
234 markdown::Link::Path { path } => {
235 if let Some(workspace) = &workspace {
236 _ = workspace.update(cx, |workspace, cx| {
237 workspace.open_abs_path(path.clone(), false, cx).detach();
238 });
239 }
240 }
241 }
242 })
243}
244
245#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
246pub(crate) enum InlayId {
247 Suggestion(usize),
248 Hint(usize),
249}
250
251impl InlayId {
252 fn id(&self) -> usize {
253 match self {
254 Self::Suggestion(id) => *id,
255 Self::Hint(id) => *id,
256 }
257 }
258}
259
260enum DiffRowHighlight {}
261enum DocumentHighlightRead {}
262enum DocumentHighlightWrite {}
263enum InputComposition {}
264
265#[derive(Copy, Clone, PartialEq, Eq)]
266pub enum Direction {
267 Prev,
268 Next,
269}
270
271#[derive(Debug, Copy, Clone, PartialEq, Eq)]
272pub enum Navigated {
273 Yes,
274 No,
275}
276
277impl Navigated {
278 pub fn from_bool(yes: bool) -> Navigated {
279 if yes {
280 Navigated::Yes
281 } else {
282 Navigated::No
283 }
284 }
285}
286
287pub fn init_settings(cx: &mut AppContext) {
288 EditorSettings::register(cx);
289}
290
291pub fn init(cx: &mut AppContext) {
292 init_settings(cx);
293
294 workspace::register_project_item::<Editor>(cx);
295 workspace::FollowableViewRegistry::register::<Editor>(cx);
296 workspace::register_serializable_item::<Editor>(cx);
297
298 cx.observe_new_views(
299 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
300 workspace.register_action(Editor::new_file);
301 workspace.register_action(Editor::new_file_vertical);
302 workspace.register_action(Editor::new_file_horizontal);
303 },
304 )
305 .detach();
306
307 cx.on_action(move |_: &workspace::NewFile, cx| {
308 let app_state = workspace::AppState::global(cx);
309 if let Some(app_state) = app_state.upgrade() {
310 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
311 Editor::new_file(workspace, &Default::default(), cx)
312 })
313 .detach();
314 }
315 });
316 cx.on_action(move |_: &workspace::NewWindow, cx| {
317 let app_state = workspace::AppState::global(cx);
318 if let Some(app_state) = app_state.upgrade() {
319 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
320 Editor::new_file(workspace, &Default::default(), cx)
321 })
322 .detach();
323 }
324 });
325}
326
327pub struct SearchWithinRange;
328
329trait InvalidationRegion {
330 fn ranges(&self) -> &[Range<Anchor>];
331}
332
333#[derive(Clone, Debug, PartialEq)]
334pub enum SelectPhase {
335 Begin {
336 position: DisplayPoint,
337 add: bool,
338 click_count: usize,
339 },
340 BeginColumnar {
341 position: DisplayPoint,
342 reset: bool,
343 goal_column: u32,
344 },
345 Extend {
346 position: DisplayPoint,
347 click_count: usize,
348 },
349 Update {
350 position: DisplayPoint,
351 goal_column: u32,
352 scroll_delta: gpui::Point<f32>,
353 },
354 End,
355}
356
357#[derive(Clone, Debug)]
358pub enum SelectMode {
359 Character,
360 Word(Range<Anchor>),
361 Line(Range<Anchor>),
362 All,
363}
364
365#[derive(Copy, Clone, PartialEq, Eq, Debug)]
366pub enum EditorMode {
367 SingleLine { auto_width: bool },
368 AutoHeight { max_lines: usize },
369 Full,
370}
371
372#[derive(Clone, Debug)]
373pub enum SoftWrap {
374 None,
375 PreferLine,
376 EditorWidth,
377 Column(u32),
378 Bounded(u32),
379}
380
381#[derive(Clone)]
382pub struct EditorStyle {
383 pub background: Hsla,
384 pub local_player: PlayerColor,
385 pub text: TextStyle,
386 pub scrollbar_width: Pixels,
387 pub syntax: Arc<SyntaxTheme>,
388 pub status: StatusColors,
389 pub inlay_hints_style: HighlightStyle,
390 pub suggestions_style: HighlightStyle,
391 pub unnecessary_code_fade: f32,
392}
393
394impl Default for EditorStyle {
395 fn default() -> Self {
396 Self {
397 background: Hsla::default(),
398 local_player: PlayerColor::default(),
399 text: TextStyle::default(),
400 scrollbar_width: Pixels::default(),
401 syntax: Default::default(),
402 // HACK: Status colors don't have a real default.
403 // We should look into removing the status colors from the editor
404 // style and retrieve them directly from the theme.
405 status: StatusColors::dark(),
406 inlay_hints_style: HighlightStyle::default(),
407 suggestions_style: HighlightStyle::default(),
408 unnecessary_code_fade: Default::default(),
409 }
410 }
411}
412
413type CompletionId = usize;
414
415#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
416struct EditorActionId(usize);
417
418impl EditorActionId {
419 pub fn post_inc(&mut self) -> Self {
420 let answer = self.0;
421
422 *self = Self(answer + 1);
423
424 Self(answer)
425 }
426}
427
428// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
429// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
430
431type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
432type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
433
434#[derive(Default)]
435struct ScrollbarMarkerState {
436 scrollbar_size: Size<Pixels>,
437 dirty: bool,
438 markers: Arc<[PaintQuad]>,
439 pending_refresh: Option<Task<Result<()>>>,
440}
441
442impl ScrollbarMarkerState {
443 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
444 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
445 }
446}
447
448#[derive(Clone, Debug)]
449struct RunnableTasks {
450 templates: Vec<(TaskSourceKind, TaskTemplate)>,
451 offset: MultiBufferOffset,
452 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
453 column: u32,
454 // Values of all named captures, including those starting with '_'
455 extra_variables: HashMap<String, String>,
456 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
457 context_range: Range<BufferOffset>,
458}
459
460#[derive(Clone)]
461struct ResolvedTasks {
462 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
463 position: Anchor,
464}
465#[derive(Copy, Clone, Debug)]
466struct MultiBufferOffset(usize);
467#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
468struct BufferOffset(usize);
469
470// Addons allow storing per-editor state in other crates (e.g. Vim)
471pub trait Addon: 'static {
472 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
473 fn should_show_inline_completions(&self, _: &AppContext) -> bool {
474 true
475 }
476
477 fn to_any(&self) -> &dyn std::any::Any;
478}
479
480/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
481///
482/// See the [module level documentation](self) for more information.
483pub struct Editor {
484 focus_handle: FocusHandle,
485 last_focused_descendant: Option<WeakFocusHandle>,
486 /// The text buffer being edited
487 buffer: Model<MultiBuffer>,
488 /// Map of how text in the buffer should be displayed.
489 /// Handles soft wraps, folds, fake inlay text insertions, etc.
490 pub display_map: Model<DisplayMap>,
491 pub selections: SelectionsCollection,
492 pub scroll_manager: ScrollManager,
493 /// When inline assist editors are linked, they all render cursors because
494 /// typing enters text into each of them, even the ones that aren't focused.
495 pub(crate) show_cursor_when_unfocused: bool,
496 columnar_selection_tail: Option<Anchor>,
497 add_selections_state: Option<AddSelectionsState>,
498 select_next_state: Option<SelectNextState>,
499 select_prev_state: Option<SelectNextState>,
500 selection_history: SelectionHistory,
501 autoclose_regions: Vec<AutocloseRegion>,
502 snippet_stack: InvalidationStack<SnippetState>,
503 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
504 ime_transaction: Option<TransactionId>,
505 active_diagnostics: Option<ActiveDiagnosticGroup>,
506 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
507 project: Option<Model<Project>>,
508 completion_provider: Option<Box<dyn CompletionProvider>>,
509 collaboration_hub: Option<Box<dyn CollaborationHub>>,
510 blink_manager: Model<BlinkManager>,
511 show_cursor_names: bool,
512 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
513 pub show_local_selections: bool,
514 mode: EditorMode,
515 show_breadcrumbs: bool,
516 show_gutter: bool,
517 show_line_numbers: Option<bool>,
518 use_relative_line_numbers: Option<bool>,
519 show_git_diff_gutter: Option<bool>,
520 show_code_actions: Option<bool>,
521 show_runnables: Option<bool>,
522 show_wrap_guides: Option<bool>,
523 show_indent_guides: Option<bool>,
524 placeholder_text: Option<Arc<str>>,
525 highlight_order: usize,
526 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
527 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
528 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
529 scrollbar_marker_state: ScrollbarMarkerState,
530 active_indent_guides_state: ActiveIndentGuidesState,
531 nav_history: Option<ItemNavHistory>,
532 context_menu: RwLock<Option<ContextMenu>>,
533 mouse_context_menu: Option<MouseContextMenu>,
534 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
535 signature_help_state: SignatureHelpState,
536 auto_signature_help: Option<bool>,
537 find_all_references_task_sources: Vec<Anchor>,
538 next_completion_id: CompletionId,
539 completion_documentation_pre_resolve_debounce: DebouncedDelay,
540 available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
541 code_actions_task: Option<Task<()>>,
542 document_highlights_task: Option<Task<()>>,
543 linked_editing_range_task: Option<Task<Option<()>>>,
544 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
545 pending_rename: Option<RenameState>,
546 searchable: bool,
547 cursor_shape: CursorShape,
548 current_line_highlight: Option<CurrentLineHighlight>,
549 collapse_matches: bool,
550 autoindent_mode: Option<AutoindentMode>,
551 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
552 input_enabled: bool,
553 use_modal_editing: bool,
554 read_only: bool,
555 leader_peer_id: Option<PeerId>,
556 remote_id: Option<ViewId>,
557 hover_state: HoverState,
558 gutter_hovered: bool,
559 hovered_link_state: Option<HoveredLinkState>,
560 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
561 active_inline_completion: Option<(Inlay, Option<Range<Anchor>>)>,
562 show_inline_completions_override: Option<bool>,
563 inlay_hint_cache: InlayHintCache,
564 expanded_hunks: ExpandedHunks,
565 next_inlay_id: usize,
566 _subscriptions: Vec<Subscription>,
567 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
568 gutter_dimensions: GutterDimensions,
569 style: Option<EditorStyle>,
570 next_editor_action_id: EditorActionId,
571 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
572 use_autoclose: bool,
573 use_auto_surround: bool,
574 auto_replace_emoji_shortcode: bool,
575 show_git_blame_gutter: bool,
576 show_git_blame_inline: bool,
577 show_git_blame_inline_delay_task: Option<Task<()>>,
578 git_blame_inline_enabled: bool,
579 serialize_dirty_buffers: bool,
580 show_selection_menu: Option<bool>,
581 blame: Option<Model<GitBlame>>,
582 blame_subscription: Option<Subscription>,
583 custom_context_menu: Option<
584 Box<
585 dyn 'static
586 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
587 >,
588 >,
589 last_bounds: Option<Bounds<Pixels>>,
590 expect_bounds_change: Option<Bounds<Pixels>>,
591 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
592 tasks_update_task: Option<Task<()>>,
593 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
594 file_header_size: u32,
595 breadcrumb_header: Option<String>,
596 focused_block: Option<FocusedBlock>,
597 next_scroll_position: NextScrollCursorCenterTopBottom,
598 addons: HashMap<TypeId, Box<dyn Addon>>,
599 _scroll_cursor_center_top_bottom_task: Task<()>,
600}
601
602#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
603enum NextScrollCursorCenterTopBottom {
604 #[default]
605 Center,
606 Top,
607 Bottom,
608}
609
610impl NextScrollCursorCenterTopBottom {
611 fn next(&self) -> Self {
612 match self {
613 Self::Center => Self::Top,
614 Self::Top => Self::Bottom,
615 Self::Bottom => Self::Center,
616 }
617 }
618}
619
620#[derive(Clone)]
621pub struct EditorSnapshot {
622 pub mode: EditorMode,
623 show_gutter: bool,
624 show_line_numbers: Option<bool>,
625 show_git_diff_gutter: Option<bool>,
626 show_code_actions: Option<bool>,
627 show_runnables: Option<bool>,
628 render_git_blame_gutter: bool,
629 pub display_snapshot: DisplaySnapshot,
630 pub placeholder_text: Option<Arc<str>>,
631 is_focused: bool,
632 scroll_anchor: ScrollAnchor,
633 ongoing_scroll: OngoingScroll,
634 current_line_highlight: CurrentLineHighlight,
635 gutter_hovered: bool,
636}
637
638const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
639
640#[derive(Default, Debug, Clone, Copy)]
641pub struct GutterDimensions {
642 pub left_padding: Pixels,
643 pub right_padding: Pixels,
644 pub width: Pixels,
645 pub margin: Pixels,
646 pub git_blame_entries_width: Option<Pixels>,
647}
648
649impl GutterDimensions {
650 /// The full width of the space taken up by the gutter.
651 pub fn full_width(&self) -> Pixels {
652 self.margin + self.width
653 }
654
655 /// The width of the space reserved for the fold indicators,
656 /// use alongside 'justify_end' and `gutter_width` to
657 /// right align content with the line numbers
658 pub fn fold_area_width(&self) -> Pixels {
659 self.margin + self.right_padding
660 }
661}
662
663#[derive(Debug)]
664pub struct RemoteSelection {
665 pub replica_id: ReplicaId,
666 pub selection: Selection<Anchor>,
667 pub cursor_shape: CursorShape,
668 pub peer_id: PeerId,
669 pub line_mode: bool,
670 pub participant_index: Option<ParticipantIndex>,
671 pub user_name: Option<SharedString>,
672}
673
674#[derive(Clone, Debug)]
675struct SelectionHistoryEntry {
676 selections: Arc<[Selection<Anchor>]>,
677 select_next_state: Option<SelectNextState>,
678 select_prev_state: Option<SelectNextState>,
679 add_selections_state: Option<AddSelectionsState>,
680}
681
682enum SelectionHistoryMode {
683 Normal,
684 Undoing,
685 Redoing,
686}
687
688#[derive(Clone, PartialEq, Eq, Hash)]
689struct HoveredCursor {
690 replica_id: u16,
691 selection_id: usize,
692}
693
694impl Default for SelectionHistoryMode {
695 fn default() -> Self {
696 Self::Normal
697 }
698}
699
700#[derive(Default)]
701struct SelectionHistory {
702 #[allow(clippy::type_complexity)]
703 selections_by_transaction:
704 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
705 mode: SelectionHistoryMode,
706 undo_stack: VecDeque<SelectionHistoryEntry>,
707 redo_stack: VecDeque<SelectionHistoryEntry>,
708}
709
710impl SelectionHistory {
711 fn insert_transaction(
712 &mut self,
713 transaction_id: TransactionId,
714 selections: Arc<[Selection<Anchor>]>,
715 ) {
716 self.selections_by_transaction
717 .insert(transaction_id, (selections, None));
718 }
719
720 #[allow(clippy::type_complexity)]
721 fn transaction(
722 &self,
723 transaction_id: TransactionId,
724 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
725 self.selections_by_transaction.get(&transaction_id)
726 }
727
728 #[allow(clippy::type_complexity)]
729 fn transaction_mut(
730 &mut self,
731 transaction_id: TransactionId,
732 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
733 self.selections_by_transaction.get_mut(&transaction_id)
734 }
735
736 fn push(&mut self, entry: SelectionHistoryEntry) {
737 if !entry.selections.is_empty() {
738 match self.mode {
739 SelectionHistoryMode::Normal => {
740 self.push_undo(entry);
741 self.redo_stack.clear();
742 }
743 SelectionHistoryMode::Undoing => self.push_redo(entry),
744 SelectionHistoryMode::Redoing => self.push_undo(entry),
745 }
746 }
747 }
748
749 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
750 if self
751 .undo_stack
752 .back()
753 .map_or(true, |e| e.selections != entry.selections)
754 {
755 self.undo_stack.push_back(entry);
756 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
757 self.undo_stack.pop_front();
758 }
759 }
760 }
761
762 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
763 if self
764 .redo_stack
765 .back()
766 .map_or(true, |e| e.selections != entry.selections)
767 {
768 self.redo_stack.push_back(entry);
769 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
770 self.redo_stack.pop_front();
771 }
772 }
773 }
774}
775
776struct RowHighlight {
777 index: usize,
778 range: RangeInclusive<Anchor>,
779 color: Option<Hsla>,
780 should_autoscroll: bool,
781}
782
783#[derive(Clone, Debug)]
784struct AddSelectionsState {
785 above: bool,
786 stack: Vec<usize>,
787}
788
789#[derive(Clone)]
790struct SelectNextState {
791 query: AhoCorasick,
792 wordwise: bool,
793 done: bool,
794}
795
796impl std::fmt::Debug for SelectNextState {
797 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
798 f.debug_struct(std::any::type_name::<Self>())
799 .field("wordwise", &self.wordwise)
800 .field("done", &self.done)
801 .finish()
802 }
803}
804
805#[derive(Debug)]
806struct AutocloseRegion {
807 selection_id: usize,
808 range: Range<Anchor>,
809 pair: BracketPair,
810}
811
812#[derive(Debug)]
813struct SnippetState {
814 ranges: Vec<Vec<Range<Anchor>>>,
815 active_index: usize,
816}
817
818#[doc(hidden)]
819pub struct RenameState {
820 pub range: Range<Anchor>,
821 pub old_name: Arc<str>,
822 pub editor: View<Editor>,
823 block_id: CustomBlockId,
824}
825
826struct InvalidationStack<T>(Vec<T>);
827
828struct RegisteredInlineCompletionProvider {
829 provider: Arc<dyn InlineCompletionProviderHandle>,
830 _subscription: Subscription,
831}
832
833enum ContextMenu {
834 Completions(CompletionsMenu),
835 CodeActions(CodeActionsMenu),
836}
837
838impl ContextMenu {
839 fn select_first(
840 &mut self,
841 project: Option<&Model<Project>>,
842 cx: &mut ViewContext<Editor>,
843 ) -> bool {
844 if self.visible() {
845 match self {
846 ContextMenu::Completions(menu) => menu.select_first(project, cx),
847 ContextMenu::CodeActions(menu) => menu.select_first(cx),
848 }
849 true
850 } else {
851 false
852 }
853 }
854
855 fn select_prev(
856 &mut self,
857 project: Option<&Model<Project>>,
858 cx: &mut ViewContext<Editor>,
859 ) -> bool {
860 if self.visible() {
861 match self {
862 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
863 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
864 }
865 true
866 } else {
867 false
868 }
869 }
870
871 fn select_next(
872 &mut self,
873 project: Option<&Model<Project>>,
874 cx: &mut ViewContext<Editor>,
875 ) -> bool {
876 if self.visible() {
877 match self {
878 ContextMenu::Completions(menu) => menu.select_next(project, cx),
879 ContextMenu::CodeActions(menu) => menu.select_next(cx),
880 }
881 true
882 } else {
883 false
884 }
885 }
886
887 fn select_last(
888 &mut self,
889 project: Option<&Model<Project>>,
890 cx: &mut ViewContext<Editor>,
891 ) -> bool {
892 if self.visible() {
893 match self {
894 ContextMenu::Completions(menu) => menu.select_last(project, cx),
895 ContextMenu::CodeActions(menu) => menu.select_last(cx),
896 }
897 true
898 } else {
899 false
900 }
901 }
902
903 fn visible(&self) -> bool {
904 match self {
905 ContextMenu::Completions(menu) => menu.visible(),
906 ContextMenu::CodeActions(menu) => menu.visible(),
907 }
908 }
909
910 fn render(
911 &self,
912 cursor_position: DisplayPoint,
913 style: &EditorStyle,
914 max_height: Pixels,
915 workspace: Option<WeakView<Workspace>>,
916 cx: &mut ViewContext<Editor>,
917 ) -> (ContextMenuOrigin, AnyElement) {
918 match self {
919 ContextMenu::Completions(menu) => (
920 ContextMenuOrigin::EditorPoint(cursor_position),
921 menu.render(style, max_height, workspace, cx),
922 ),
923 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
924 }
925 }
926}
927
928enum ContextMenuOrigin {
929 EditorPoint(DisplayPoint),
930 GutterIndicator(DisplayRow),
931}
932
933#[derive(Clone)]
934struct CompletionsMenu {
935 id: CompletionId,
936 sort_completions: bool,
937 initial_position: Anchor,
938 buffer: Model<Buffer>,
939 completions: Arc<RwLock<Box<[Completion]>>>,
940 match_candidates: Arc<[StringMatchCandidate]>,
941 matches: Arc<[StringMatch]>,
942 selected_item: usize,
943 scroll_handle: UniformListScrollHandle,
944 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
945}
946
947impl CompletionsMenu {
948 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
949 self.selected_item = 0;
950 self.scroll_handle.scroll_to_item(self.selected_item);
951 self.attempt_resolve_selected_completion_documentation(project, cx);
952 cx.notify();
953 }
954
955 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
956 if self.selected_item > 0 {
957 self.selected_item -= 1;
958 } else {
959 self.selected_item = self.matches.len() - 1;
960 }
961 self.scroll_handle.scroll_to_item(self.selected_item);
962 self.attempt_resolve_selected_completion_documentation(project, cx);
963 cx.notify();
964 }
965
966 fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
967 if self.selected_item + 1 < self.matches.len() {
968 self.selected_item += 1;
969 } else {
970 self.selected_item = 0;
971 }
972 self.scroll_handle.scroll_to_item(self.selected_item);
973 self.attempt_resolve_selected_completion_documentation(project, cx);
974 cx.notify();
975 }
976
977 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
978 self.selected_item = self.matches.len() - 1;
979 self.scroll_handle.scroll_to_item(self.selected_item);
980 self.attempt_resolve_selected_completion_documentation(project, cx);
981 cx.notify();
982 }
983
984 fn pre_resolve_completion_documentation(
985 buffer: Model<Buffer>,
986 completions: Arc<RwLock<Box<[Completion]>>>,
987 matches: Arc<[StringMatch]>,
988 editor: &Editor,
989 cx: &mut ViewContext<Editor>,
990 ) -> Task<()> {
991 let settings = EditorSettings::get_global(cx);
992 if !settings.show_completion_documentation {
993 return Task::ready(());
994 }
995
996 let Some(provider) = editor.completion_provider.as_ref() else {
997 return Task::ready(());
998 };
999
1000 let resolve_task = provider.resolve_completions(
1001 buffer,
1002 matches.iter().map(|m| m.candidate_id).collect(),
1003 completions.clone(),
1004 cx,
1005 );
1006
1007 return cx.spawn(move |this, mut cx| async move {
1008 if let Some(true) = resolve_task.await.log_err() {
1009 this.update(&mut cx, |_, cx| cx.notify()).ok();
1010 }
1011 });
1012 }
1013
1014 fn attempt_resolve_selected_completion_documentation(
1015 &mut self,
1016 project: Option<&Model<Project>>,
1017 cx: &mut ViewContext<Editor>,
1018 ) {
1019 let settings = EditorSettings::get_global(cx);
1020 if !settings.show_completion_documentation {
1021 return;
1022 }
1023
1024 let completion_index = self.matches[self.selected_item].candidate_id;
1025 let Some(project) = project else {
1026 return;
1027 };
1028
1029 let resolve_task = project.update(cx, |project, cx| {
1030 project.resolve_completions(
1031 self.buffer.clone(),
1032 vec![completion_index],
1033 self.completions.clone(),
1034 cx,
1035 )
1036 });
1037
1038 let delay_ms =
1039 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1040 let delay = Duration::from_millis(delay_ms);
1041
1042 self.selected_completion_documentation_resolve_debounce
1043 .lock()
1044 .fire_new(delay, cx, |_, cx| {
1045 cx.spawn(move |this, mut cx| async move {
1046 if let Some(true) = resolve_task.await.log_err() {
1047 this.update(&mut cx, |_, cx| cx.notify()).ok();
1048 }
1049 })
1050 });
1051 }
1052
1053 fn visible(&self) -> bool {
1054 !self.matches.is_empty()
1055 }
1056
1057 fn render(
1058 &self,
1059 style: &EditorStyle,
1060 max_height: Pixels,
1061 workspace: Option<WeakView<Workspace>>,
1062 cx: &mut ViewContext<Editor>,
1063 ) -> AnyElement {
1064 let settings = EditorSettings::get_global(cx);
1065 let show_completion_documentation = settings.show_completion_documentation;
1066
1067 let widest_completion_ix = self
1068 .matches
1069 .iter()
1070 .enumerate()
1071 .max_by_key(|(_, mat)| {
1072 let completions = self.completions.read();
1073 let completion = &completions[mat.candidate_id];
1074 let documentation = &completion.documentation;
1075
1076 let mut len = completion.label.text.chars().count();
1077 if let Some(Documentation::SingleLine(text)) = documentation {
1078 if show_completion_documentation {
1079 len += text.chars().count();
1080 }
1081 }
1082
1083 len
1084 })
1085 .map(|(ix, _)| ix);
1086
1087 let completions = self.completions.clone();
1088 let matches = self.matches.clone();
1089 let selected_item = self.selected_item;
1090 let style = style.clone();
1091
1092 let multiline_docs = if show_completion_documentation {
1093 let mat = &self.matches[selected_item];
1094 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1095 Some(Documentation::MultiLinePlainText(text)) => {
1096 Some(div().child(SharedString::from(text.clone())))
1097 }
1098 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1099 Some(div().child(render_parsed_markdown(
1100 "completions_markdown",
1101 parsed,
1102 &style,
1103 workspace,
1104 cx,
1105 )))
1106 }
1107 _ => None,
1108 };
1109 multiline_docs.map(|div| {
1110 div.id("multiline_docs")
1111 .max_h(max_height)
1112 .flex_1()
1113 .px_1p5()
1114 .py_1()
1115 .min_w(px(260.))
1116 .max_w(px(640.))
1117 .w(px(500.))
1118 .overflow_y_scroll()
1119 .occlude()
1120 })
1121 } else {
1122 None
1123 };
1124
1125 let list = uniform_list(
1126 cx.view().clone(),
1127 "completions",
1128 matches.len(),
1129 move |_editor, range, cx| {
1130 let start_ix = range.start;
1131 let completions_guard = completions.read();
1132
1133 matches[range]
1134 .iter()
1135 .enumerate()
1136 .map(|(ix, mat)| {
1137 let item_ix = start_ix + ix;
1138 let candidate_id = mat.candidate_id;
1139 let completion = &completions_guard[candidate_id];
1140
1141 let documentation = if show_completion_documentation {
1142 &completion.documentation
1143 } else {
1144 &None
1145 };
1146
1147 let highlights = gpui::combine_highlights(
1148 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1149 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1150 |(range, mut highlight)| {
1151 // Ignore font weight for syntax highlighting, as we'll use it
1152 // for fuzzy matches.
1153 highlight.font_weight = None;
1154
1155 if completion.lsp_completion.deprecated.unwrap_or(false) {
1156 highlight.strikethrough = Some(StrikethroughStyle {
1157 thickness: 1.0.into(),
1158 ..Default::default()
1159 });
1160 highlight.color = Some(cx.theme().colors().text_muted);
1161 }
1162
1163 (range, highlight)
1164 },
1165 ),
1166 );
1167 let completion_label = StyledText::new(completion.label.text.clone())
1168 .with_highlights(&style.text, highlights);
1169 let documentation_label =
1170 if let Some(Documentation::SingleLine(text)) = documentation {
1171 if text.trim().is_empty() {
1172 None
1173 } else {
1174 Some(
1175 Label::new(text.clone())
1176 .ml_4()
1177 .size(LabelSize::Small)
1178 .color(Color::Muted),
1179 )
1180 }
1181 } else {
1182 None
1183 };
1184
1185 div().min_w(px(220.)).max_w(px(540.)).child(
1186 ListItem::new(mat.candidate_id)
1187 .inset(true)
1188 .selected(item_ix == selected_item)
1189 .on_click(cx.listener(move |editor, _event, cx| {
1190 cx.stop_propagation();
1191 if let Some(task) = editor.confirm_completion(
1192 &ConfirmCompletion {
1193 item_ix: Some(item_ix),
1194 },
1195 cx,
1196 ) {
1197 task.detach_and_log_err(cx)
1198 }
1199 }))
1200 .child(h_flex().overflow_hidden().child(completion_label))
1201 .end_slot::<Label>(documentation_label),
1202 )
1203 })
1204 .collect()
1205 },
1206 )
1207 .occlude()
1208 .max_h(max_height)
1209 .track_scroll(self.scroll_handle.clone())
1210 .with_width_from_item(widest_completion_ix)
1211 .with_sizing_behavior(ListSizingBehavior::Infer);
1212
1213 Popover::new()
1214 .child(list)
1215 .when_some(multiline_docs, |popover, multiline_docs| {
1216 popover.aside(multiline_docs)
1217 })
1218 .into_any_element()
1219 }
1220
1221 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1222 let mut matches = if let Some(query) = query {
1223 fuzzy::match_strings(
1224 &self.match_candidates,
1225 query,
1226 query.chars().any(|c| c.is_uppercase()),
1227 100,
1228 &Default::default(),
1229 executor,
1230 )
1231 .await
1232 } else {
1233 self.match_candidates
1234 .iter()
1235 .enumerate()
1236 .map(|(candidate_id, candidate)| StringMatch {
1237 candidate_id,
1238 score: Default::default(),
1239 positions: Default::default(),
1240 string: candidate.string.clone(),
1241 })
1242 .collect()
1243 };
1244
1245 // Remove all candidates where the query's start does not match the start of any word in the candidate
1246 if let Some(query) = query {
1247 if let Some(query_start) = query.chars().next() {
1248 matches.retain(|string_match| {
1249 split_words(&string_match.string).any(|word| {
1250 // Check that the first codepoint of the word as lowercase matches the first
1251 // codepoint of the query as lowercase
1252 word.chars()
1253 .flat_map(|codepoint| codepoint.to_lowercase())
1254 .zip(query_start.to_lowercase())
1255 .all(|(word_cp, query_cp)| word_cp == query_cp)
1256 })
1257 });
1258 }
1259 }
1260
1261 let completions = self.completions.read();
1262 if self.sort_completions {
1263 matches.sort_unstable_by_key(|mat| {
1264 // We do want to strike a balance here between what the language server tells us
1265 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1266 // `Creat` and there is a local variable called `CreateComponent`).
1267 // So what we do is: we bucket all matches into two buckets
1268 // - Strong matches
1269 // - Weak matches
1270 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1271 // and the Weak matches are the rest.
1272 //
1273 // For the strong matches, we sort by the language-servers score first and for the weak
1274 // matches, we prefer our fuzzy finder first.
1275 //
1276 // The thinking behind that: it's useless to take the sort_text the language-server gives
1277 // us into account when it's obviously a bad match.
1278
1279 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1280 enum MatchScore<'a> {
1281 Strong {
1282 sort_text: Option<&'a str>,
1283 score: Reverse<OrderedFloat<f64>>,
1284 sort_key: (usize, &'a str),
1285 },
1286 Weak {
1287 score: Reverse<OrderedFloat<f64>>,
1288 sort_text: Option<&'a str>,
1289 sort_key: (usize, &'a str),
1290 },
1291 }
1292
1293 let completion = &completions[mat.candidate_id];
1294 let sort_key = completion.sort_key();
1295 let sort_text = completion.lsp_completion.sort_text.as_deref();
1296 let score = Reverse(OrderedFloat(mat.score));
1297
1298 if mat.score >= 0.2 {
1299 MatchScore::Strong {
1300 sort_text,
1301 score,
1302 sort_key,
1303 }
1304 } else {
1305 MatchScore::Weak {
1306 score,
1307 sort_text,
1308 sort_key,
1309 }
1310 }
1311 });
1312 }
1313
1314 for mat in &mut matches {
1315 let completion = &completions[mat.candidate_id];
1316 mat.string.clone_from(&completion.label.text);
1317 for position in &mut mat.positions {
1318 *position += completion.label.filter_range.start;
1319 }
1320 }
1321 drop(completions);
1322
1323 self.matches = matches.into();
1324 self.selected_item = 0;
1325 }
1326}
1327
1328#[derive(Clone)]
1329struct CodeActionContents {
1330 tasks: Option<Arc<ResolvedTasks>>,
1331 actions: Option<Arc<[CodeAction]>>,
1332}
1333
1334impl CodeActionContents {
1335 fn len(&self) -> usize {
1336 match (&self.tasks, &self.actions) {
1337 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1338 (Some(tasks), None) => tasks.templates.len(),
1339 (None, Some(actions)) => actions.len(),
1340 (None, None) => 0,
1341 }
1342 }
1343
1344 fn is_empty(&self) -> bool {
1345 match (&self.tasks, &self.actions) {
1346 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1347 (Some(tasks), None) => tasks.templates.is_empty(),
1348 (None, Some(actions)) => actions.is_empty(),
1349 (None, None) => true,
1350 }
1351 }
1352
1353 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1354 self.tasks
1355 .iter()
1356 .flat_map(|tasks| {
1357 tasks
1358 .templates
1359 .iter()
1360 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1361 })
1362 .chain(self.actions.iter().flat_map(|actions| {
1363 actions
1364 .iter()
1365 .map(|action| CodeActionsItem::CodeAction(action.clone()))
1366 }))
1367 }
1368 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1369 match (&self.tasks, &self.actions) {
1370 (Some(tasks), Some(actions)) => {
1371 if index < tasks.templates.len() {
1372 tasks
1373 .templates
1374 .get(index)
1375 .cloned()
1376 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1377 } else {
1378 actions
1379 .get(index - tasks.templates.len())
1380 .cloned()
1381 .map(CodeActionsItem::CodeAction)
1382 }
1383 }
1384 (Some(tasks), None) => tasks
1385 .templates
1386 .get(index)
1387 .cloned()
1388 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1389 (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
1390 (None, None) => None,
1391 }
1392 }
1393}
1394
1395#[allow(clippy::large_enum_variant)]
1396#[derive(Clone)]
1397enum CodeActionsItem {
1398 Task(TaskSourceKind, ResolvedTask),
1399 CodeAction(CodeAction),
1400}
1401
1402impl CodeActionsItem {
1403 fn as_task(&self) -> Option<&ResolvedTask> {
1404 let Self::Task(_, task) = self else {
1405 return None;
1406 };
1407 Some(task)
1408 }
1409 fn as_code_action(&self) -> Option<&CodeAction> {
1410 let Self::CodeAction(action) = self else {
1411 return None;
1412 };
1413 Some(action)
1414 }
1415 fn label(&self) -> String {
1416 match self {
1417 Self::CodeAction(action) => action.lsp_action.title.clone(),
1418 Self::Task(_, task) => task.resolved_label.clone(),
1419 }
1420 }
1421}
1422
1423struct CodeActionsMenu {
1424 actions: CodeActionContents,
1425 buffer: Model<Buffer>,
1426 selected_item: usize,
1427 scroll_handle: UniformListScrollHandle,
1428 deployed_from_indicator: Option<DisplayRow>,
1429}
1430
1431impl CodeActionsMenu {
1432 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1433 self.selected_item = 0;
1434 self.scroll_handle.scroll_to_item(self.selected_item);
1435 cx.notify()
1436 }
1437
1438 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1439 if self.selected_item > 0 {
1440 self.selected_item -= 1;
1441 } else {
1442 self.selected_item = self.actions.len() - 1;
1443 }
1444 self.scroll_handle.scroll_to_item(self.selected_item);
1445 cx.notify();
1446 }
1447
1448 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1449 if self.selected_item + 1 < self.actions.len() {
1450 self.selected_item += 1;
1451 } else {
1452 self.selected_item = 0;
1453 }
1454 self.scroll_handle.scroll_to_item(self.selected_item);
1455 cx.notify();
1456 }
1457
1458 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1459 self.selected_item = self.actions.len() - 1;
1460 self.scroll_handle.scroll_to_item(self.selected_item);
1461 cx.notify()
1462 }
1463
1464 fn visible(&self) -> bool {
1465 !self.actions.is_empty()
1466 }
1467
1468 fn render(
1469 &self,
1470 cursor_position: DisplayPoint,
1471 _style: &EditorStyle,
1472 max_height: Pixels,
1473 cx: &mut ViewContext<Editor>,
1474 ) -> (ContextMenuOrigin, AnyElement) {
1475 let actions = self.actions.clone();
1476 let selected_item = self.selected_item;
1477 let element = uniform_list(
1478 cx.view().clone(),
1479 "code_actions_menu",
1480 self.actions.len(),
1481 move |_this, range, cx| {
1482 actions
1483 .iter()
1484 .skip(range.start)
1485 .take(range.end - range.start)
1486 .enumerate()
1487 .map(|(ix, action)| {
1488 let item_ix = range.start + ix;
1489 let selected = selected_item == item_ix;
1490 let colors = cx.theme().colors();
1491 div()
1492 .px_2()
1493 .text_color(colors.text)
1494 .when(selected, |style| {
1495 style
1496 .bg(colors.element_active)
1497 .text_color(colors.text_accent)
1498 })
1499 .hover(|style| {
1500 style
1501 .bg(colors.element_hover)
1502 .text_color(colors.text_accent)
1503 })
1504 .whitespace_nowrap()
1505 .when_some(action.as_code_action(), |this, action| {
1506 this.on_mouse_down(
1507 MouseButton::Left,
1508 cx.listener(move |editor, _, cx| {
1509 cx.stop_propagation();
1510 if let Some(task) = editor.confirm_code_action(
1511 &ConfirmCodeAction {
1512 item_ix: Some(item_ix),
1513 },
1514 cx,
1515 ) {
1516 task.detach_and_log_err(cx)
1517 }
1518 }),
1519 )
1520 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1521 .child(SharedString::from(action.lsp_action.title.clone()))
1522 })
1523 .when_some(action.as_task(), |this, task| {
1524 this.on_mouse_down(
1525 MouseButton::Left,
1526 cx.listener(move |editor, _, cx| {
1527 cx.stop_propagation();
1528 if let Some(task) = editor.confirm_code_action(
1529 &ConfirmCodeAction {
1530 item_ix: Some(item_ix),
1531 },
1532 cx,
1533 ) {
1534 task.detach_and_log_err(cx)
1535 }
1536 }),
1537 )
1538 .child(SharedString::from(task.resolved_label.clone()))
1539 })
1540 })
1541 .collect()
1542 },
1543 )
1544 .elevation_1(cx)
1545 .px_2()
1546 .py_1()
1547 .max_h(max_height)
1548 .occlude()
1549 .track_scroll(self.scroll_handle.clone())
1550 .with_width_from_item(
1551 self.actions
1552 .iter()
1553 .enumerate()
1554 .max_by_key(|(_, action)| match action {
1555 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1556 CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
1557 })
1558 .map(|(ix, _)| ix),
1559 )
1560 .with_sizing_behavior(ListSizingBehavior::Infer)
1561 .into_any_element();
1562
1563 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1564 ContextMenuOrigin::GutterIndicator(row)
1565 } else {
1566 ContextMenuOrigin::EditorPoint(cursor_position)
1567 };
1568
1569 (cursor_position, element)
1570 }
1571}
1572
1573#[derive(Debug)]
1574struct ActiveDiagnosticGroup {
1575 primary_range: Range<Anchor>,
1576 primary_message: String,
1577 group_id: usize,
1578 blocks: HashMap<CustomBlockId, Diagnostic>,
1579 is_valid: bool,
1580}
1581
1582#[derive(Serialize, Deserialize, Clone, Debug)]
1583pub struct ClipboardSelection {
1584 pub len: usize,
1585 pub is_entire_line: bool,
1586 pub first_line_indent: u32,
1587}
1588
1589#[derive(Debug)]
1590pub(crate) struct NavigationData {
1591 cursor_anchor: Anchor,
1592 cursor_position: Point,
1593 scroll_anchor: ScrollAnchor,
1594 scroll_top_row: u32,
1595}
1596
1597#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1598enum GotoDefinitionKind {
1599 Symbol,
1600 Declaration,
1601 Type,
1602 Implementation,
1603}
1604
1605#[derive(Debug, Clone)]
1606enum InlayHintRefreshReason {
1607 Toggle(bool),
1608 SettingsChange(InlayHintSettings),
1609 NewLinesShown,
1610 BufferEdited(HashSet<Arc<Language>>),
1611 RefreshRequested,
1612 ExcerptsRemoved(Vec<ExcerptId>),
1613}
1614
1615impl InlayHintRefreshReason {
1616 fn description(&self) -> &'static str {
1617 match self {
1618 Self::Toggle(_) => "toggle",
1619 Self::SettingsChange(_) => "settings change",
1620 Self::NewLinesShown => "new lines shown",
1621 Self::BufferEdited(_) => "buffer edited",
1622 Self::RefreshRequested => "refresh requested",
1623 Self::ExcerptsRemoved(_) => "excerpts removed",
1624 }
1625 }
1626}
1627
1628pub(crate) struct FocusedBlock {
1629 id: BlockId,
1630 focus_handle: WeakFocusHandle,
1631}
1632
1633impl Editor {
1634 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1635 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1636 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1637 Self::new(
1638 EditorMode::SingleLine { auto_width: false },
1639 buffer,
1640 None,
1641 false,
1642 cx,
1643 )
1644 }
1645
1646 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1647 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1648 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1649 Self::new(EditorMode::Full, buffer, None, false, cx)
1650 }
1651
1652 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1653 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1654 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1655 Self::new(
1656 EditorMode::SingleLine { auto_width: true },
1657 buffer,
1658 None,
1659 false,
1660 cx,
1661 )
1662 }
1663
1664 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1665 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1666 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1667 Self::new(
1668 EditorMode::AutoHeight { max_lines },
1669 buffer,
1670 None,
1671 false,
1672 cx,
1673 )
1674 }
1675
1676 pub fn for_buffer(
1677 buffer: Model<Buffer>,
1678 project: Option<Model<Project>>,
1679 cx: &mut ViewContext<Self>,
1680 ) -> Self {
1681 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1682 Self::new(EditorMode::Full, buffer, project, false, cx)
1683 }
1684
1685 pub fn for_multibuffer(
1686 buffer: Model<MultiBuffer>,
1687 project: Option<Model<Project>>,
1688 show_excerpt_controls: bool,
1689 cx: &mut ViewContext<Self>,
1690 ) -> Self {
1691 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1692 }
1693
1694 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1695 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1696 let mut clone = Self::new(
1697 self.mode,
1698 self.buffer.clone(),
1699 self.project.clone(),
1700 show_excerpt_controls,
1701 cx,
1702 );
1703 self.display_map.update(cx, |display_map, cx| {
1704 let snapshot = display_map.snapshot(cx);
1705 clone.display_map.update(cx, |display_map, cx| {
1706 display_map.set_state(&snapshot, cx);
1707 });
1708 });
1709 clone.selections.clone_state(&self.selections);
1710 clone.scroll_manager.clone_state(&self.scroll_manager);
1711 clone.searchable = self.searchable;
1712 clone
1713 }
1714
1715 pub fn new(
1716 mode: EditorMode,
1717 buffer: Model<MultiBuffer>,
1718 project: Option<Model<Project>>,
1719 show_excerpt_controls: bool,
1720 cx: &mut ViewContext<Self>,
1721 ) -> Self {
1722 let style = cx.text_style();
1723 let font_size = style.font_size.to_pixels(cx.rem_size());
1724 let editor = cx.view().downgrade();
1725 let fold_placeholder = FoldPlaceholder {
1726 constrain_width: true,
1727 render: Arc::new(move |fold_id, fold_range, cx| {
1728 let editor = editor.clone();
1729 div()
1730 .id(fold_id)
1731 .bg(cx.theme().colors().ghost_element_background)
1732 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1733 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1734 .rounded_sm()
1735 .size_full()
1736 .cursor_pointer()
1737 .child("⋯")
1738 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1739 .on_click(move |_, cx| {
1740 editor
1741 .update(cx, |editor, cx| {
1742 editor.unfold_ranges(
1743 [fold_range.start..fold_range.end],
1744 true,
1745 false,
1746 cx,
1747 );
1748 cx.stop_propagation();
1749 })
1750 .ok();
1751 })
1752 .into_any()
1753 }),
1754 merge_adjacent: true,
1755 };
1756 let file_header_size = if show_excerpt_controls { 3 } else { 2 };
1757 let display_map = cx.new_model(|cx| {
1758 DisplayMap::new(
1759 buffer.clone(),
1760 style.font(),
1761 font_size,
1762 None,
1763 show_excerpt_controls,
1764 file_header_size,
1765 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1766 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1767 fold_placeholder,
1768 cx,
1769 )
1770 });
1771
1772 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1773
1774 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1775
1776 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1777 .then(|| language_settings::SoftWrap::PreferLine);
1778
1779 let mut project_subscriptions = Vec::new();
1780 if mode == EditorMode::Full {
1781 if let Some(project) = project.as_ref() {
1782 if buffer.read(cx).is_singleton() {
1783 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1784 cx.emit(EditorEvent::TitleChanged);
1785 }));
1786 }
1787 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1788 if let project::Event::RefreshInlayHints = event {
1789 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1790 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1791 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1792 let focus_handle = editor.focus_handle(cx);
1793 if focus_handle.is_focused(cx) {
1794 let snapshot = buffer.read(cx).snapshot();
1795 for (range, snippet) in snippet_edits {
1796 let editor_range =
1797 language::range_from_lsp(*range).to_offset(&snapshot);
1798 editor
1799 .insert_snippet(&[editor_range], snippet.clone(), cx)
1800 .ok();
1801 }
1802 }
1803 }
1804 }
1805 }));
1806 let task_inventory = project.read(cx).task_inventory().clone();
1807 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1808 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1809 }));
1810 }
1811 }
1812
1813 let inlay_hint_settings = inlay_hint_settings(
1814 selections.newest_anchor().head(),
1815 &buffer.read(cx).snapshot(cx),
1816 cx,
1817 );
1818 let focus_handle = cx.focus_handle();
1819 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1820 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1821 .detach();
1822 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1823 .detach();
1824 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1825
1826 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1827 Some(false)
1828 } else {
1829 None
1830 };
1831
1832 let mut this = Self {
1833 focus_handle,
1834 show_cursor_when_unfocused: false,
1835 last_focused_descendant: None,
1836 buffer: buffer.clone(),
1837 display_map: display_map.clone(),
1838 selections,
1839 scroll_manager: ScrollManager::new(cx),
1840 columnar_selection_tail: None,
1841 add_selections_state: None,
1842 select_next_state: None,
1843 select_prev_state: None,
1844 selection_history: Default::default(),
1845 autoclose_regions: Default::default(),
1846 snippet_stack: Default::default(),
1847 select_larger_syntax_node_stack: Vec::new(),
1848 ime_transaction: Default::default(),
1849 active_diagnostics: None,
1850 soft_wrap_mode_override,
1851 completion_provider: project.clone().map(|project| Box::new(project) as _),
1852 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1853 project,
1854 blink_manager: blink_manager.clone(),
1855 show_local_selections: true,
1856 mode,
1857 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1858 show_gutter: mode == EditorMode::Full,
1859 show_line_numbers: None,
1860 use_relative_line_numbers: None,
1861 show_git_diff_gutter: None,
1862 show_code_actions: None,
1863 show_runnables: None,
1864 show_wrap_guides: None,
1865 show_indent_guides,
1866 placeholder_text: None,
1867 highlight_order: 0,
1868 highlighted_rows: HashMap::default(),
1869 background_highlights: Default::default(),
1870 gutter_highlights: TreeMap::default(),
1871 scrollbar_marker_state: ScrollbarMarkerState::default(),
1872 active_indent_guides_state: ActiveIndentGuidesState::default(),
1873 nav_history: None,
1874 context_menu: RwLock::new(None),
1875 mouse_context_menu: None,
1876 completion_tasks: Default::default(),
1877 signature_help_state: SignatureHelpState::default(),
1878 auto_signature_help: None,
1879 find_all_references_task_sources: Vec::new(),
1880 next_completion_id: 0,
1881 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1882 next_inlay_id: 0,
1883 available_code_actions: Default::default(),
1884 code_actions_task: Default::default(),
1885 document_highlights_task: Default::default(),
1886 linked_editing_range_task: Default::default(),
1887 pending_rename: Default::default(),
1888 searchable: true,
1889 cursor_shape: Default::default(),
1890 current_line_highlight: None,
1891 autoindent_mode: Some(AutoindentMode::EachLine),
1892 collapse_matches: false,
1893 workspace: None,
1894 input_enabled: true,
1895 use_modal_editing: mode == EditorMode::Full,
1896 read_only: false,
1897 use_autoclose: true,
1898 use_auto_surround: true,
1899 auto_replace_emoji_shortcode: false,
1900 leader_peer_id: None,
1901 remote_id: None,
1902 hover_state: Default::default(),
1903 hovered_link_state: Default::default(),
1904 inline_completion_provider: None,
1905 active_inline_completion: None,
1906 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1907 expanded_hunks: ExpandedHunks::default(),
1908 gutter_hovered: false,
1909 pixel_position_of_newest_cursor: None,
1910 last_bounds: None,
1911 expect_bounds_change: None,
1912 gutter_dimensions: GutterDimensions::default(),
1913 style: None,
1914 show_cursor_names: false,
1915 hovered_cursors: Default::default(),
1916 next_editor_action_id: EditorActionId::default(),
1917 editor_actions: Rc::default(),
1918 show_inline_completions_override: None,
1919 custom_context_menu: None,
1920 show_git_blame_gutter: false,
1921 show_git_blame_inline: false,
1922 show_selection_menu: None,
1923 show_git_blame_inline_delay_task: None,
1924 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1925 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1926 .session
1927 .restore_unsaved_buffers,
1928 blame: None,
1929 blame_subscription: None,
1930 file_header_size,
1931 tasks: Default::default(),
1932 _subscriptions: vec![
1933 cx.observe(&buffer, Self::on_buffer_changed),
1934 cx.subscribe(&buffer, Self::on_buffer_event),
1935 cx.observe(&display_map, Self::on_display_map_changed),
1936 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1937 cx.observe_global::<SettingsStore>(Self::settings_changed),
1938 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1939 cx.observe_window_activation(|editor, cx| {
1940 let active = cx.is_window_active();
1941 editor.blink_manager.update(cx, |blink_manager, cx| {
1942 if active {
1943 blink_manager.enable(cx);
1944 } else {
1945 blink_manager.disable(cx);
1946 }
1947 });
1948 }),
1949 ],
1950 tasks_update_task: None,
1951 linked_edit_ranges: Default::default(),
1952 previous_search_ranges: None,
1953 breadcrumb_header: None,
1954 focused_block: None,
1955 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1956 addons: HashMap::default(),
1957 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1958 };
1959 this.tasks_update_task = Some(this.refresh_runnables(cx));
1960 this._subscriptions.extend(project_subscriptions);
1961
1962 this.end_selection(cx);
1963 this.scroll_manager.show_scrollbar(cx);
1964
1965 if mode == EditorMode::Full {
1966 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1967 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1968
1969 if this.git_blame_inline_enabled {
1970 this.git_blame_inline_enabled = true;
1971 this.start_git_blame_inline(false, cx);
1972 }
1973 }
1974
1975 this.report_editor_event("open", None, cx);
1976 this
1977 }
1978
1979 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
1980 self.mouse_context_menu
1981 .as_ref()
1982 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1983 }
1984
1985 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
1986 let mut key_context = KeyContext::new_with_defaults();
1987 key_context.add("Editor");
1988 let mode = match self.mode {
1989 EditorMode::SingleLine { .. } => "single_line",
1990 EditorMode::AutoHeight { .. } => "auto_height",
1991 EditorMode::Full => "full",
1992 };
1993
1994 if EditorSettings::jupyter_enabled(cx) {
1995 key_context.add("jupyter");
1996 }
1997
1998 key_context.set("mode", mode);
1999 if self.pending_rename.is_some() {
2000 key_context.add("renaming");
2001 }
2002 if self.context_menu_visible() {
2003 match self.context_menu.read().as_ref() {
2004 Some(ContextMenu::Completions(_)) => {
2005 key_context.add("menu");
2006 key_context.add("showing_completions")
2007 }
2008 Some(ContextMenu::CodeActions(_)) => {
2009 key_context.add("menu");
2010 key_context.add("showing_code_actions")
2011 }
2012 None => {}
2013 }
2014 }
2015
2016 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2017 if !self.focus_handle(cx).contains_focused(cx)
2018 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2019 {
2020 for addon in self.addons.values() {
2021 addon.extend_key_context(&mut key_context, cx)
2022 }
2023 }
2024
2025 if let Some(extension) = self
2026 .buffer
2027 .read(cx)
2028 .as_singleton()
2029 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2030 {
2031 key_context.set("extension", extension.to_string());
2032 }
2033
2034 if self.has_active_inline_completion(cx) {
2035 key_context.add("copilot_suggestion");
2036 key_context.add("inline_completion");
2037 }
2038
2039 key_context
2040 }
2041
2042 pub fn new_file(
2043 workspace: &mut Workspace,
2044 _: &workspace::NewFile,
2045 cx: &mut ViewContext<Workspace>,
2046 ) {
2047 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2048 "Failed to create buffer",
2049 cx,
2050 |e, _| match e.error_code() {
2051 ErrorCode::RemoteUpgradeRequired => Some(format!(
2052 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2053 e.error_tag("required").unwrap_or("the latest version")
2054 )),
2055 _ => None,
2056 },
2057 );
2058 }
2059
2060 pub fn new_in_workspace(
2061 workspace: &mut Workspace,
2062 cx: &mut ViewContext<Workspace>,
2063 ) -> Task<Result<View<Editor>>> {
2064 let project = workspace.project().clone();
2065 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2066
2067 cx.spawn(|workspace, mut cx| async move {
2068 let buffer = create.await?;
2069 workspace.update(&mut cx, |workspace, cx| {
2070 let editor =
2071 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2072 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2073 editor
2074 })
2075 })
2076 }
2077
2078 fn new_file_vertical(
2079 workspace: &mut Workspace,
2080 _: &workspace::NewFileSplitVertical,
2081 cx: &mut ViewContext<Workspace>,
2082 ) {
2083 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2084 }
2085
2086 fn new_file_horizontal(
2087 workspace: &mut Workspace,
2088 _: &workspace::NewFileSplitHorizontal,
2089 cx: &mut ViewContext<Workspace>,
2090 ) {
2091 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2092 }
2093
2094 fn new_file_in_direction(
2095 workspace: &mut Workspace,
2096 direction: SplitDirection,
2097 cx: &mut ViewContext<Workspace>,
2098 ) {
2099 let project = workspace.project().clone();
2100 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2101
2102 cx.spawn(|workspace, mut cx| async move {
2103 let buffer = create.await?;
2104 workspace.update(&mut cx, move |workspace, cx| {
2105 workspace.split_item(
2106 direction,
2107 Box::new(
2108 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2109 ),
2110 cx,
2111 )
2112 })?;
2113 anyhow::Ok(())
2114 })
2115 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2116 ErrorCode::RemoteUpgradeRequired => Some(format!(
2117 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2118 e.error_tag("required").unwrap_or("the latest version")
2119 )),
2120 _ => None,
2121 });
2122 }
2123
2124 pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
2125 self.buffer.read(cx).replica_id()
2126 }
2127
2128 pub fn leader_peer_id(&self) -> Option<PeerId> {
2129 self.leader_peer_id
2130 }
2131
2132 pub fn buffer(&self) -> &Model<MultiBuffer> {
2133 &self.buffer
2134 }
2135
2136 pub fn workspace(&self) -> Option<View<Workspace>> {
2137 self.workspace.as_ref()?.0.upgrade()
2138 }
2139
2140 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2141 self.buffer().read(cx).title(cx)
2142 }
2143
2144 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2145 EditorSnapshot {
2146 mode: self.mode,
2147 show_gutter: self.show_gutter,
2148 show_line_numbers: self.show_line_numbers,
2149 show_git_diff_gutter: self.show_git_diff_gutter,
2150 show_code_actions: self.show_code_actions,
2151 show_runnables: self.show_runnables,
2152 render_git_blame_gutter: self.render_git_blame_gutter(cx),
2153 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2154 scroll_anchor: self.scroll_manager.anchor(),
2155 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2156 placeholder_text: self.placeholder_text.clone(),
2157 is_focused: self.focus_handle.is_focused(cx),
2158 current_line_highlight: self
2159 .current_line_highlight
2160 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2161 gutter_hovered: self.gutter_hovered,
2162 }
2163 }
2164
2165 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2166 self.buffer.read(cx).language_at(point, cx)
2167 }
2168
2169 pub fn file_at<T: ToOffset>(
2170 &self,
2171 point: T,
2172 cx: &AppContext,
2173 ) -> Option<Arc<dyn language::File>> {
2174 self.buffer.read(cx).read(cx).file_at(point).cloned()
2175 }
2176
2177 pub fn active_excerpt(
2178 &self,
2179 cx: &AppContext,
2180 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2181 self.buffer
2182 .read(cx)
2183 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2184 }
2185
2186 pub fn mode(&self) -> EditorMode {
2187 self.mode
2188 }
2189
2190 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2191 self.collaboration_hub.as_deref()
2192 }
2193
2194 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2195 self.collaboration_hub = Some(hub);
2196 }
2197
2198 pub fn set_custom_context_menu(
2199 &mut self,
2200 f: impl 'static
2201 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2202 ) {
2203 self.custom_context_menu = Some(Box::new(f))
2204 }
2205
2206 pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
2207 self.completion_provider = Some(provider);
2208 }
2209
2210 pub fn set_inline_completion_provider<T>(
2211 &mut self,
2212 provider: Option<Model<T>>,
2213 cx: &mut ViewContext<Self>,
2214 ) where
2215 T: InlineCompletionProvider,
2216 {
2217 self.inline_completion_provider =
2218 provider.map(|provider| RegisteredInlineCompletionProvider {
2219 _subscription: cx.observe(&provider, |this, _, cx| {
2220 if this.focus_handle.is_focused(cx) {
2221 this.update_visible_inline_completion(cx);
2222 }
2223 }),
2224 provider: Arc::new(provider),
2225 });
2226 self.refresh_inline_completion(false, false, cx);
2227 }
2228
2229 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2230 self.placeholder_text.as_deref()
2231 }
2232
2233 pub fn set_placeholder_text(
2234 &mut self,
2235 placeholder_text: impl Into<Arc<str>>,
2236 cx: &mut ViewContext<Self>,
2237 ) {
2238 let placeholder_text = Some(placeholder_text.into());
2239 if self.placeholder_text != placeholder_text {
2240 self.placeholder_text = placeholder_text;
2241 cx.notify();
2242 }
2243 }
2244
2245 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2246 self.cursor_shape = cursor_shape;
2247
2248 // Disrupt blink for immediate user feedback that the cursor shape has changed
2249 self.blink_manager.update(cx, BlinkManager::show_cursor);
2250
2251 cx.notify();
2252 }
2253
2254 pub fn set_current_line_highlight(
2255 &mut self,
2256 current_line_highlight: Option<CurrentLineHighlight>,
2257 ) {
2258 self.current_line_highlight = current_line_highlight;
2259 }
2260
2261 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2262 self.collapse_matches = collapse_matches;
2263 }
2264
2265 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2266 if self.collapse_matches {
2267 return range.start..range.start;
2268 }
2269 range.clone()
2270 }
2271
2272 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2273 if self.display_map.read(cx).clip_at_line_ends != clip {
2274 self.display_map
2275 .update(cx, |map, _| map.clip_at_line_ends = clip);
2276 }
2277 }
2278
2279 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2280 self.input_enabled = input_enabled;
2281 }
2282
2283 pub fn set_autoindent(&mut self, autoindent: bool) {
2284 if autoindent {
2285 self.autoindent_mode = Some(AutoindentMode::EachLine);
2286 } else {
2287 self.autoindent_mode = None;
2288 }
2289 }
2290
2291 pub fn read_only(&self, cx: &AppContext) -> bool {
2292 self.read_only || self.buffer.read(cx).read_only()
2293 }
2294
2295 pub fn set_read_only(&mut self, read_only: bool) {
2296 self.read_only = read_only;
2297 }
2298
2299 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2300 self.use_autoclose = autoclose;
2301 }
2302
2303 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2304 self.use_auto_surround = auto_surround;
2305 }
2306
2307 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2308 self.auto_replace_emoji_shortcode = auto_replace;
2309 }
2310
2311 pub fn toggle_inline_completions(
2312 &mut self,
2313 _: &ToggleInlineCompletions,
2314 cx: &mut ViewContext<Self>,
2315 ) {
2316 if self.show_inline_completions_override.is_some() {
2317 self.set_show_inline_completions(None, cx);
2318 } else {
2319 let cursor = self.selections.newest_anchor().head();
2320 if let Some((buffer, cursor_buffer_position)) =
2321 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2322 {
2323 let show_inline_completions =
2324 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2325 self.set_show_inline_completions(Some(show_inline_completions), cx);
2326 }
2327 }
2328 }
2329
2330 pub fn set_show_inline_completions(
2331 &mut self,
2332 show_inline_completions: Option<bool>,
2333 cx: &mut ViewContext<Self>,
2334 ) {
2335 self.show_inline_completions_override = show_inline_completions;
2336 self.refresh_inline_completion(false, true, cx);
2337 }
2338
2339 fn should_show_inline_completions(
2340 &self,
2341 buffer: &Model<Buffer>,
2342 buffer_position: language::Anchor,
2343 cx: &AppContext,
2344 ) -> bool {
2345 if let Some(provider) = self.inline_completion_provider() {
2346 for addon in self.addons.values() {
2347 if !addon.should_show_inline_completions(cx) {
2348 return false;
2349 }
2350 }
2351 if let Some(show_inline_completions) = self.show_inline_completions_override {
2352 show_inline_completions
2353 } else {
2354 self.mode == EditorMode::Full && provider.is_enabled(&buffer, buffer_position, cx)
2355 }
2356 } else {
2357 false
2358 }
2359 }
2360
2361 pub fn set_use_modal_editing(&mut self, to: bool) {
2362 self.use_modal_editing = to;
2363 }
2364
2365 pub fn use_modal_editing(&self) -> bool {
2366 self.use_modal_editing
2367 }
2368
2369 fn selections_did_change(
2370 &mut self,
2371 local: bool,
2372 old_cursor_position: &Anchor,
2373 show_completions: bool,
2374 cx: &mut ViewContext<Self>,
2375 ) {
2376 cx.invalidate_character_coordinates();
2377
2378 // Copy selections to primary selection buffer
2379 #[cfg(target_os = "linux")]
2380 if local {
2381 let selections = self.selections.all::<usize>(cx);
2382 let buffer_handle = self.buffer.read(cx).read(cx);
2383
2384 let mut text = String::new();
2385 for (index, selection) in selections.iter().enumerate() {
2386 let text_for_selection = buffer_handle
2387 .text_for_range(selection.start..selection.end)
2388 .collect::<String>();
2389
2390 text.push_str(&text_for_selection);
2391 if index != selections.len() - 1 {
2392 text.push('\n');
2393 }
2394 }
2395
2396 if !text.is_empty() {
2397 cx.write_to_primary(ClipboardItem::new_string(text));
2398 }
2399 }
2400
2401 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2402 self.buffer.update(cx, |buffer, cx| {
2403 buffer.set_active_selections(
2404 &self.selections.disjoint_anchors(),
2405 self.selections.line_mode,
2406 self.cursor_shape,
2407 cx,
2408 )
2409 });
2410 }
2411 let display_map = self
2412 .display_map
2413 .update(cx, |display_map, cx| display_map.snapshot(cx));
2414 let buffer = &display_map.buffer_snapshot;
2415 self.add_selections_state = None;
2416 self.select_next_state = None;
2417 self.select_prev_state = None;
2418 self.select_larger_syntax_node_stack.clear();
2419 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2420 self.snippet_stack
2421 .invalidate(&self.selections.disjoint_anchors(), buffer);
2422 self.take_rename(false, cx);
2423
2424 let new_cursor_position = self.selections.newest_anchor().head();
2425
2426 self.push_to_nav_history(
2427 *old_cursor_position,
2428 Some(new_cursor_position.to_point(buffer)),
2429 cx,
2430 );
2431
2432 if local {
2433 let new_cursor_position = self.selections.newest_anchor().head();
2434 let mut context_menu = self.context_menu.write();
2435 let completion_menu = match context_menu.as_ref() {
2436 Some(ContextMenu::Completions(menu)) => Some(menu),
2437
2438 _ => {
2439 *context_menu = None;
2440 None
2441 }
2442 };
2443
2444 if let Some(completion_menu) = completion_menu {
2445 let cursor_position = new_cursor_position.to_offset(buffer);
2446 let (word_range, kind) = buffer.surrounding_word(completion_menu.initial_position);
2447 if kind == Some(CharKind::Word)
2448 && word_range.to_inclusive().contains(&cursor_position)
2449 {
2450 let mut completion_menu = completion_menu.clone();
2451 drop(context_menu);
2452
2453 let query = Self::completion_query(buffer, cursor_position);
2454 cx.spawn(move |this, mut cx| async move {
2455 completion_menu
2456 .filter(query.as_deref(), cx.background_executor().clone())
2457 .await;
2458
2459 this.update(&mut cx, |this, cx| {
2460 let mut context_menu = this.context_menu.write();
2461 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2462 return;
2463 };
2464
2465 if menu.id > completion_menu.id {
2466 return;
2467 }
2468
2469 *context_menu = Some(ContextMenu::Completions(completion_menu));
2470 drop(context_menu);
2471 cx.notify();
2472 })
2473 })
2474 .detach();
2475
2476 if show_completions {
2477 self.show_completions(&ShowCompletions { trigger: None }, cx);
2478 }
2479 } else {
2480 drop(context_menu);
2481 self.hide_context_menu(cx);
2482 }
2483 } else {
2484 drop(context_menu);
2485 }
2486
2487 hide_hover(self, cx);
2488
2489 if old_cursor_position.to_display_point(&display_map).row()
2490 != new_cursor_position.to_display_point(&display_map).row()
2491 {
2492 self.available_code_actions.take();
2493 }
2494 self.refresh_code_actions(cx);
2495 self.refresh_document_highlights(cx);
2496 refresh_matching_bracket_highlights(self, cx);
2497 self.discard_inline_completion(false, cx);
2498 linked_editing_ranges::refresh_linked_ranges(self, cx);
2499 if self.git_blame_inline_enabled {
2500 self.start_inline_blame_timer(cx);
2501 }
2502 }
2503
2504 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2505 cx.emit(EditorEvent::SelectionsChanged { local });
2506
2507 if self.selections.disjoint_anchors().len() == 1 {
2508 cx.emit(SearchEvent::ActiveMatchChanged)
2509 }
2510 cx.notify();
2511 }
2512
2513 pub fn change_selections<R>(
2514 &mut self,
2515 autoscroll: Option<Autoscroll>,
2516 cx: &mut ViewContext<Self>,
2517 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2518 ) -> R {
2519 self.change_selections_inner(autoscroll, true, cx, change)
2520 }
2521
2522 pub fn change_selections_inner<R>(
2523 &mut self,
2524 autoscroll: Option<Autoscroll>,
2525 request_completions: bool,
2526 cx: &mut ViewContext<Self>,
2527 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2528 ) -> R {
2529 let old_cursor_position = self.selections.newest_anchor().head();
2530 self.push_to_selection_history();
2531
2532 let (changed, result) = self.selections.change_with(cx, change);
2533
2534 if changed {
2535 if let Some(autoscroll) = autoscroll {
2536 self.request_autoscroll(autoscroll, cx);
2537 }
2538 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2539
2540 if self.should_open_signature_help_automatically(
2541 &old_cursor_position,
2542 self.signature_help_state.backspace_pressed(),
2543 cx,
2544 ) {
2545 self.show_signature_help(&ShowSignatureHelp, cx);
2546 }
2547 self.signature_help_state.set_backspace_pressed(false);
2548 }
2549
2550 result
2551 }
2552
2553 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2554 where
2555 I: IntoIterator<Item = (Range<S>, T)>,
2556 S: ToOffset,
2557 T: Into<Arc<str>>,
2558 {
2559 if self.read_only(cx) {
2560 return;
2561 }
2562
2563 self.buffer
2564 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2565 }
2566
2567 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2568 where
2569 I: IntoIterator<Item = (Range<S>, T)>,
2570 S: ToOffset,
2571 T: Into<Arc<str>>,
2572 {
2573 if self.read_only(cx) {
2574 return;
2575 }
2576
2577 self.buffer.update(cx, |buffer, cx| {
2578 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2579 });
2580 }
2581
2582 pub fn edit_with_block_indent<I, S, T>(
2583 &mut self,
2584 edits: I,
2585 original_indent_columns: Vec<u32>,
2586 cx: &mut ViewContext<Self>,
2587 ) where
2588 I: IntoIterator<Item = (Range<S>, T)>,
2589 S: ToOffset,
2590 T: Into<Arc<str>>,
2591 {
2592 if self.read_only(cx) {
2593 return;
2594 }
2595
2596 self.buffer.update(cx, |buffer, cx| {
2597 buffer.edit(
2598 edits,
2599 Some(AutoindentMode::Block {
2600 original_indent_columns,
2601 }),
2602 cx,
2603 )
2604 });
2605 }
2606
2607 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2608 self.hide_context_menu(cx);
2609
2610 match phase {
2611 SelectPhase::Begin {
2612 position,
2613 add,
2614 click_count,
2615 } => self.begin_selection(position, add, click_count, cx),
2616 SelectPhase::BeginColumnar {
2617 position,
2618 goal_column,
2619 reset,
2620 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2621 SelectPhase::Extend {
2622 position,
2623 click_count,
2624 } => self.extend_selection(position, click_count, cx),
2625 SelectPhase::Update {
2626 position,
2627 goal_column,
2628 scroll_delta,
2629 } => self.update_selection(position, goal_column, scroll_delta, cx),
2630 SelectPhase::End => self.end_selection(cx),
2631 }
2632 }
2633
2634 fn extend_selection(
2635 &mut self,
2636 position: DisplayPoint,
2637 click_count: usize,
2638 cx: &mut ViewContext<Self>,
2639 ) {
2640 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2641 let tail = self.selections.newest::<usize>(cx).tail();
2642 self.begin_selection(position, false, click_count, cx);
2643
2644 let position = position.to_offset(&display_map, Bias::Left);
2645 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2646
2647 let mut pending_selection = self
2648 .selections
2649 .pending_anchor()
2650 .expect("extend_selection not called with pending selection");
2651 if position >= tail {
2652 pending_selection.start = tail_anchor;
2653 } else {
2654 pending_selection.end = tail_anchor;
2655 pending_selection.reversed = true;
2656 }
2657
2658 let mut pending_mode = self.selections.pending_mode().unwrap();
2659 match &mut pending_mode {
2660 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2661 _ => {}
2662 }
2663
2664 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2665 s.set_pending(pending_selection, pending_mode)
2666 });
2667 }
2668
2669 fn begin_selection(
2670 &mut self,
2671 position: DisplayPoint,
2672 add: bool,
2673 click_count: usize,
2674 cx: &mut ViewContext<Self>,
2675 ) {
2676 if !self.focus_handle.is_focused(cx) {
2677 self.last_focused_descendant = None;
2678 cx.focus(&self.focus_handle);
2679 }
2680
2681 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2682 let buffer = &display_map.buffer_snapshot;
2683 let newest_selection = self.selections.newest_anchor().clone();
2684 let position = display_map.clip_point(position, Bias::Left);
2685
2686 let start;
2687 let end;
2688 let mode;
2689 let auto_scroll;
2690 match click_count {
2691 1 => {
2692 start = buffer.anchor_before(position.to_point(&display_map));
2693 end = start;
2694 mode = SelectMode::Character;
2695 auto_scroll = true;
2696 }
2697 2 => {
2698 let range = movement::surrounding_word(&display_map, position);
2699 start = buffer.anchor_before(range.start.to_point(&display_map));
2700 end = buffer.anchor_before(range.end.to_point(&display_map));
2701 mode = SelectMode::Word(start..end);
2702 auto_scroll = true;
2703 }
2704 3 => {
2705 let position = display_map
2706 .clip_point(position, Bias::Left)
2707 .to_point(&display_map);
2708 let line_start = display_map.prev_line_boundary(position).0;
2709 let next_line_start = buffer.clip_point(
2710 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2711 Bias::Left,
2712 );
2713 start = buffer.anchor_before(line_start);
2714 end = buffer.anchor_before(next_line_start);
2715 mode = SelectMode::Line(start..end);
2716 auto_scroll = true;
2717 }
2718 _ => {
2719 start = buffer.anchor_before(0);
2720 end = buffer.anchor_before(buffer.len());
2721 mode = SelectMode::All;
2722 auto_scroll = false;
2723 }
2724 }
2725
2726 let point_to_delete: Option<usize> = {
2727 let selected_points: Vec<Selection<Point>> =
2728 self.selections.disjoint_in_range(start..end, cx);
2729
2730 if !add || click_count > 1 {
2731 None
2732 } else if selected_points.len() > 0 {
2733 Some(selected_points[0].id)
2734 } else {
2735 let clicked_point_already_selected =
2736 self.selections.disjoint.iter().find(|selection| {
2737 selection.start.to_point(buffer) == start.to_point(buffer)
2738 || selection.end.to_point(buffer) == end.to_point(buffer)
2739 });
2740
2741 if let Some(selection) = clicked_point_already_selected {
2742 Some(selection.id)
2743 } else {
2744 None
2745 }
2746 }
2747 };
2748
2749 let selections_count = self.selections.count();
2750
2751 self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
2752 if let Some(point_to_delete) = point_to_delete {
2753 s.delete(point_to_delete);
2754
2755 if selections_count == 1 {
2756 s.set_pending_anchor_range(start..end, mode);
2757 }
2758 } else {
2759 if !add {
2760 s.clear_disjoint();
2761 } else if click_count > 1 {
2762 s.delete(newest_selection.id)
2763 }
2764
2765 s.set_pending_anchor_range(start..end, mode);
2766 }
2767 });
2768 }
2769
2770 fn begin_columnar_selection(
2771 &mut self,
2772 position: DisplayPoint,
2773 goal_column: u32,
2774 reset: bool,
2775 cx: &mut ViewContext<Self>,
2776 ) {
2777 if !self.focus_handle.is_focused(cx) {
2778 self.last_focused_descendant = None;
2779 cx.focus(&self.focus_handle);
2780 }
2781
2782 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2783
2784 if reset {
2785 let pointer_position = display_map
2786 .buffer_snapshot
2787 .anchor_before(position.to_point(&display_map));
2788
2789 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2790 s.clear_disjoint();
2791 s.set_pending_anchor_range(
2792 pointer_position..pointer_position,
2793 SelectMode::Character,
2794 );
2795 });
2796 }
2797
2798 let tail = self.selections.newest::<Point>(cx).tail();
2799 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2800
2801 if !reset {
2802 self.select_columns(
2803 tail.to_display_point(&display_map),
2804 position,
2805 goal_column,
2806 &display_map,
2807 cx,
2808 );
2809 }
2810 }
2811
2812 fn update_selection(
2813 &mut self,
2814 position: DisplayPoint,
2815 goal_column: u32,
2816 scroll_delta: gpui::Point<f32>,
2817 cx: &mut ViewContext<Self>,
2818 ) {
2819 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2820
2821 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2822 let tail = tail.to_display_point(&display_map);
2823 self.select_columns(tail, position, goal_column, &display_map, cx);
2824 } else if let Some(mut pending) = self.selections.pending_anchor() {
2825 let buffer = self.buffer.read(cx).snapshot(cx);
2826 let head;
2827 let tail;
2828 let mode = self.selections.pending_mode().unwrap();
2829 match &mode {
2830 SelectMode::Character => {
2831 head = position.to_point(&display_map);
2832 tail = pending.tail().to_point(&buffer);
2833 }
2834 SelectMode::Word(original_range) => {
2835 let original_display_range = original_range.start.to_display_point(&display_map)
2836 ..original_range.end.to_display_point(&display_map);
2837 let original_buffer_range = original_display_range.start.to_point(&display_map)
2838 ..original_display_range.end.to_point(&display_map);
2839 if movement::is_inside_word(&display_map, position)
2840 || original_display_range.contains(&position)
2841 {
2842 let word_range = movement::surrounding_word(&display_map, position);
2843 if word_range.start < original_display_range.start {
2844 head = word_range.start.to_point(&display_map);
2845 } else {
2846 head = word_range.end.to_point(&display_map);
2847 }
2848 } else {
2849 head = position.to_point(&display_map);
2850 }
2851
2852 if head <= original_buffer_range.start {
2853 tail = original_buffer_range.end;
2854 } else {
2855 tail = original_buffer_range.start;
2856 }
2857 }
2858 SelectMode::Line(original_range) => {
2859 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2860
2861 let position = display_map
2862 .clip_point(position, Bias::Left)
2863 .to_point(&display_map);
2864 let line_start = display_map.prev_line_boundary(position).0;
2865 let next_line_start = buffer.clip_point(
2866 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2867 Bias::Left,
2868 );
2869
2870 if line_start < original_range.start {
2871 head = line_start
2872 } else {
2873 head = next_line_start
2874 }
2875
2876 if head <= original_range.start {
2877 tail = original_range.end;
2878 } else {
2879 tail = original_range.start;
2880 }
2881 }
2882 SelectMode::All => {
2883 return;
2884 }
2885 };
2886
2887 if head < tail {
2888 pending.start = buffer.anchor_before(head);
2889 pending.end = buffer.anchor_before(tail);
2890 pending.reversed = true;
2891 } else {
2892 pending.start = buffer.anchor_before(tail);
2893 pending.end = buffer.anchor_before(head);
2894 pending.reversed = false;
2895 }
2896
2897 self.change_selections(None, cx, |s| {
2898 s.set_pending(pending, mode);
2899 });
2900 } else {
2901 log::error!("update_selection dispatched with no pending selection");
2902 return;
2903 }
2904
2905 self.apply_scroll_delta(scroll_delta, cx);
2906 cx.notify();
2907 }
2908
2909 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2910 self.columnar_selection_tail.take();
2911 if self.selections.pending_anchor().is_some() {
2912 let selections = self.selections.all::<usize>(cx);
2913 self.change_selections(None, cx, |s| {
2914 s.select(selections);
2915 s.clear_pending();
2916 });
2917 }
2918 }
2919
2920 fn select_columns(
2921 &mut self,
2922 tail: DisplayPoint,
2923 head: DisplayPoint,
2924 goal_column: u32,
2925 display_map: &DisplaySnapshot,
2926 cx: &mut ViewContext<Self>,
2927 ) {
2928 let start_row = cmp::min(tail.row(), head.row());
2929 let end_row = cmp::max(tail.row(), head.row());
2930 let start_column = cmp::min(tail.column(), goal_column);
2931 let end_column = cmp::max(tail.column(), goal_column);
2932 let reversed = start_column < tail.column();
2933
2934 let selection_ranges = (start_row.0..=end_row.0)
2935 .map(DisplayRow)
2936 .filter_map(|row| {
2937 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2938 let start = display_map
2939 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2940 .to_point(display_map);
2941 let end = display_map
2942 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2943 .to_point(display_map);
2944 if reversed {
2945 Some(end..start)
2946 } else {
2947 Some(start..end)
2948 }
2949 } else {
2950 None
2951 }
2952 })
2953 .collect::<Vec<_>>();
2954
2955 self.change_selections(None, cx, |s| {
2956 s.select_ranges(selection_ranges);
2957 });
2958 cx.notify();
2959 }
2960
2961 pub fn has_pending_nonempty_selection(&self) -> bool {
2962 let pending_nonempty_selection = match self.selections.pending_anchor() {
2963 Some(Selection { start, end, .. }) => start != end,
2964 None => false,
2965 };
2966
2967 pending_nonempty_selection
2968 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2969 }
2970
2971 pub fn has_pending_selection(&self) -> bool {
2972 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2973 }
2974
2975 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2976 if self.clear_clicked_diff_hunks(cx) {
2977 cx.notify();
2978 return;
2979 }
2980 if self.dismiss_menus_and_popups(true, cx) {
2981 return;
2982 }
2983
2984 if self.mode == EditorMode::Full {
2985 if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
2986 return;
2987 }
2988 }
2989
2990 cx.propagate();
2991 }
2992
2993 pub fn dismiss_menus_and_popups(
2994 &mut self,
2995 should_report_inline_completion_event: bool,
2996 cx: &mut ViewContext<Self>,
2997 ) -> bool {
2998 if self.take_rename(false, cx).is_some() {
2999 return true;
3000 }
3001
3002 if hide_hover(self, cx) {
3003 return true;
3004 }
3005
3006 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3007 return true;
3008 }
3009
3010 if self.hide_context_menu(cx).is_some() {
3011 return true;
3012 }
3013
3014 if self.mouse_context_menu.take().is_some() {
3015 return true;
3016 }
3017
3018 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3019 return true;
3020 }
3021
3022 if self.snippet_stack.pop().is_some() {
3023 return true;
3024 }
3025
3026 if self.mode == EditorMode::Full {
3027 if self.active_diagnostics.is_some() {
3028 self.dismiss_diagnostics(cx);
3029 return true;
3030 }
3031 }
3032
3033 false
3034 }
3035
3036 fn linked_editing_ranges_for(
3037 &self,
3038 selection: Range<text::Anchor>,
3039 cx: &AppContext,
3040 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3041 if self.linked_edit_ranges.is_empty() {
3042 return None;
3043 }
3044 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3045 selection.end.buffer_id.and_then(|end_buffer_id| {
3046 if selection.start.buffer_id != Some(end_buffer_id) {
3047 return None;
3048 }
3049 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3050 let snapshot = buffer.read(cx).snapshot();
3051 self.linked_edit_ranges
3052 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3053 .map(|ranges| (ranges, snapshot, buffer))
3054 })?;
3055 use text::ToOffset as TO;
3056 // find offset from the start of current range to current cursor position
3057 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3058
3059 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3060 let start_difference = start_offset - start_byte_offset;
3061 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3062 let end_difference = end_offset - start_byte_offset;
3063 // Current range has associated linked ranges.
3064 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3065 for range in linked_ranges.iter() {
3066 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3067 let end_offset = start_offset + end_difference;
3068 let start_offset = start_offset + start_difference;
3069 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3070 continue;
3071 }
3072 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3073 if s.start.buffer_id != selection.start.buffer_id
3074 || s.end.buffer_id != selection.end.buffer_id
3075 {
3076 return false;
3077 }
3078 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3079 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3080 }) {
3081 continue;
3082 }
3083 let start = buffer_snapshot.anchor_after(start_offset);
3084 let end = buffer_snapshot.anchor_after(end_offset);
3085 linked_edits
3086 .entry(buffer.clone())
3087 .or_default()
3088 .push(start..end);
3089 }
3090 Some(linked_edits)
3091 }
3092
3093 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3094 let text: Arc<str> = text.into();
3095
3096 if self.read_only(cx) {
3097 return;
3098 }
3099
3100 let selections = self.selections.all_adjusted(cx);
3101 let mut bracket_inserted = false;
3102 let mut edits = Vec::new();
3103 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3104 let mut new_selections = Vec::with_capacity(selections.len());
3105 let mut new_autoclose_regions = Vec::new();
3106 let snapshot = self.buffer.read(cx).read(cx);
3107
3108 for (selection, autoclose_region) in
3109 self.selections_with_autoclose_regions(selections, &snapshot)
3110 {
3111 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3112 // Determine if the inserted text matches the opening or closing
3113 // bracket of any of this language's bracket pairs.
3114 let mut bracket_pair = None;
3115 let mut is_bracket_pair_start = false;
3116 let mut is_bracket_pair_end = false;
3117 if !text.is_empty() {
3118 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3119 // and they are removing the character that triggered IME popup.
3120 for (pair, enabled) in scope.brackets() {
3121 if !pair.close && !pair.surround {
3122 continue;
3123 }
3124
3125 if enabled && pair.start.ends_with(text.as_ref()) {
3126 bracket_pair = Some(pair.clone());
3127 is_bracket_pair_start = true;
3128 break;
3129 }
3130 if pair.end.as_str() == text.as_ref() {
3131 bracket_pair = Some(pair.clone());
3132 is_bracket_pair_end = true;
3133 break;
3134 }
3135 }
3136 }
3137
3138 if let Some(bracket_pair) = bracket_pair {
3139 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3140 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3141 let auto_surround =
3142 self.use_auto_surround && snapshot_settings.use_auto_surround;
3143 if selection.is_empty() {
3144 if is_bracket_pair_start {
3145 let prefix_len = bracket_pair.start.len() - text.len();
3146
3147 // If the inserted text is a suffix of an opening bracket and the
3148 // selection is preceded by the rest of the opening bracket, then
3149 // insert the closing bracket.
3150 let following_text_allows_autoclose = snapshot
3151 .chars_at(selection.start)
3152 .next()
3153 .map_or(true, |c| scope.should_autoclose_before(c));
3154 let preceding_text_matches_prefix = prefix_len == 0
3155 || (selection.start.column >= (prefix_len as u32)
3156 && snapshot.contains_str_at(
3157 Point::new(
3158 selection.start.row,
3159 selection.start.column - (prefix_len as u32),
3160 ),
3161 &bracket_pair.start[..prefix_len],
3162 ));
3163
3164 if autoclose
3165 && bracket_pair.close
3166 && following_text_allows_autoclose
3167 && preceding_text_matches_prefix
3168 {
3169 let anchor = snapshot.anchor_before(selection.end);
3170 new_selections.push((selection.map(|_| anchor), text.len()));
3171 new_autoclose_regions.push((
3172 anchor,
3173 text.len(),
3174 selection.id,
3175 bracket_pair.clone(),
3176 ));
3177 edits.push((
3178 selection.range(),
3179 format!("{}{}", text, bracket_pair.end).into(),
3180 ));
3181 bracket_inserted = true;
3182 continue;
3183 }
3184 }
3185
3186 if let Some(region) = autoclose_region {
3187 // If the selection is followed by an auto-inserted closing bracket,
3188 // then don't insert that closing bracket again; just move the selection
3189 // past the closing bracket.
3190 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3191 && text.as_ref() == region.pair.end.as_str();
3192 if should_skip {
3193 let anchor = snapshot.anchor_after(selection.end);
3194 new_selections
3195 .push((selection.map(|_| anchor), region.pair.end.len()));
3196 continue;
3197 }
3198 }
3199
3200 let always_treat_brackets_as_autoclosed = snapshot
3201 .settings_at(selection.start, cx)
3202 .always_treat_brackets_as_autoclosed;
3203 if always_treat_brackets_as_autoclosed
3204 && is_bracket_pair_end
3205 && snapshot.contains_str_at(selection.end, text.as_ref())
3206 {
3207 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3208 // and the inserted text is a closing bracket and the selection is followed
3209 // by the closing bracket then move the selection past the closing bracket.
3210 let anchor = snapshot.anchor_after(selection.end);
3211 new_selections.push((selection.map(|_| anchor), text.len()));
3212 continue;
3213 }
3214 }
3215 // If an opening bracket is 1 character long and is typed while
3216 // text is selected, then surround that text with the bracket pair.
3217 else if auto_surround
3218 && bracket_pair.surround
3219 && is_bracket_pair_start
3220 && bracket_pair.start.chars().count() == 1
3221 {
3222 edits.push((selection.start..selection.start, text.clone()));
3223 edits.push((
3224 selection.end..selection.end,
3225 bracket_pair.end.as_str().into(),
3226 ));
3227 bracket_inserted = true;
3228 new_selections.push((
3229 Selection {
3230 id: selection.id,
3231 start: snapshot.anchor_after(selection.start),
3232 end: snapshot.anchor_before(selection.end),
3233 reversed: selection.reversed,
3234 goal: selection.goal,
3235 },
3236 0,
3237 ));
3238 continue;
3239 }
3240 }
3241 }
3242
3243 if self.auto_replace_emoji_shortcode
3244 && selection.is_empty()
3245 && text.as_ref().ends_with(':')
3246 {
3247 if let Some(possible_emoji_short_code) =
3248 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3249 {
3250 if !possible_emoji_short_code.is_empty() {
3251 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3252 let emoji_shortcode_start = Point::new(
3253 selection.start.row,
3254 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3255 );
3256
3257 // Remove shortcode from buffer
3258 edits.push((
3259 emoji_shortcode_start..selection.start,
3260 "".to_string().into(),
3261 ));
3262 new_selections.push((
3263 Selection {
3264 id: selection.id,
3265 start: snapshot.anchor_after(emoji_shortcode_start),
3266 end: snapshot.anchor_before(selection.start),
3267 reversed: selection.reversed,
3268 goal: selection.goal,
3269 },
3270 0,
3271 ));
3272
3273 // Insert emoji
3274 let selection_start_anchor = snapshot.anchor_after(selection.start);
3275 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3276 edits.push((selection.start..selection.end, emoji.to_string().into()));
3277
3278 continue;
3279 }
3280 }
3281 }
3282 }
3283
3284 // If not handling any auto-close operation, then just replace the selected
3285 // text with the given input and move the selection to the end of the
3286 // newly inserted text.
3287 let anchor = snapshot.anchor_after(selection.end);
3288 if !self.linked_edit_ranges.is_empty() {
3289 let start_anchor = snapshot.anchor_before(selection.start);
3290
3291 let is_word_char = text.chars().next().map_or(true, |char| {
3292 let scope = snapshot.language_scope_at(start_anchor.to_offset(&snapshot));
3293 let kind = char_kind(&scope, char);
3294
3295 kind == CharKind::Word
3296 });
3297
3298 if is_word_char {
3299 if let Some(ranges) = self
3300 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3301 {
3302 for (buffer, edits) in ranges {
3303 linked_edits
3304 .entry(buffer.clone())
3305 .or_default()
3306 .extend(edits.into_iter().map(|range| (range, text.clone())));
3307 }
3308 }
3309 }
3310 }
3311
3312 new_selections.push((selection.map(|_| anchor), 0));
3313 edits.push((selection.start..selection.end, text.clone()));
3314 }
3315
3316 drop(snapshot);
3317
3318 self.transact(cx, |this, cx| {
3319 this.buffer.update(cx, |buffer, cx| {
3320 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3321 });
3322 for (buffer, edits) in linked_edits {
3323 buffer.update(cx, |buffer, cx| {
3324 let snapshot = buffer.snapshot();
3325 let edits = edits
3326 .into_iter()
3327 .map(|(range, text)| {
3328 use text::ToPoint as TP;
3329 let end_point = TP::to_point(&range.end, &snapshot);
3330 let start_point = TP::to_point(&range.start, &snapshot);
3331 (start_point..end_point, text)
3332 })
3333 .sorted_by_key(|(range, _)| range.start)
3334 .collect::<Vec<_>>();
3335 buffer.edit(edits, None, cx);
3336 })
3337 }
3338 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3339 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3340 let snapshot = this.buffer.read(cx).read(cx);
3341 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3342 .zip(new_selection_deltas)
3343 .map(|(selection, delta)| Selection {
3344 id: selection.id,
3345 start: selection.start + delta,
3346 end: selection.end + delta,
3347 reversed: selection.reversed,
3348 goal: SelectionGoal::None,
3349 })
3350 .collect::<Vec<_>>();
3351
3352 let mut i = 0;
3353 for (position, delta, selection_id, pair) in new_autoclose_regions {
3354 let position = position.to_offset(&snapshot) + delta;
3355 let start = snapshot.anchor_before(position);
3356 let end = snapshot.anchor_after(position);
3357 while let Some(existing_state) = this.autoclose_regions.get(i) {
3358 match existing_state.range.start.cmp(&start, &snapshot) {
3359 Ordering::Less => i += 1,
3360 Ordering::Greater => break,
3361 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3362 Ordering::Less => i += 1,
3363 Ordering::Equal => break,
3364 Ordering::Greater => break,
3365 },
3366 }
3367 }
3368 this.autoclose_regions.insert(
3369 i,
3370 AutocloseRegion {
3371 selection_id,
3372 range: start..end,
3373 pair,
3374 },
3375 );
3376 }
3377
3378 drop(snapshot);
3379 let had_active_inline_completion = this.has_active_inline_completion(cx);
3380 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3381 s.select(new_selections)
3382 });
3383
3384 if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
3385 if let Some(on_type_format_task) =
3386 this.trigger_on_type_formatting(text.to_string(), cx)
3387 {
3388 on_type_format_task.detach_and_log_err(cx);
3389 }
3390 }
3391
3392 let editor_settings = EditorSettings::get_global(cx);
3393 if bracket_inserted
3394 && (editor_settings.auto_signature_help
3395 || editor_settings.show_signature_help_after_edits)
3396 {
3397 this.show_signature_help(&ShowSignatureHelp, cx);
3398 }
3399
3400 let trigger_in_words = !had_active_inline_completion;
3401 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3402 linked_editing_ranges::refresh_linked_ranges(this, cx);
3403 this.refresh_inline_completion(true, false, cx);
3404 });
3405 }
3406
3407 fn find_possible_emoji_shortcode_at_position(
3408 snapshot: &MultiBufferSnapshot,
3409 position: Point,
3410 ) -> Option<String> {
3411 let mut chars = Vec::new();
3412 let mut found_colon = false;
3413 for char in snapshot.reversed_chars_at(position).take(100) {
3414 // Found a possible emoji shortcode in the middle of the buffer
3415 if found_colon {
3416 if char.is_whitespace() {
3417 chars.reverse();
3418 return Some(chars.iter().collect());
3419 }
3420 // If the previous character is not a whitespace, we are in the middle of a word
3421 // and we only want to complete the shortcode if the word is made up of other emojis
3422 let mut containing_word = String::new();
3423 for ch in snapshot
3424 .reversed_chars_at(position)
3425 .skip(chars.len() + 1)
3426 .take(100)
3427 {
3428 if ch.is_whitespace() {
3429 break;
3430 }
3431 containing_word.push(ch);
3432 }
3433 let containing_word = containing_word.chars().rev().collect::<String>();
3434 if util::word_consists_of_emojis(containing_word.as_str()) {
3435 chars.reverse();
3436 return Some(chars.iter().collect());
3437 }
3438 }
3439
3440 if char.is_whitespace() || !char.is_ascii() {
3441 return None;
3442 }
3443 if char == ':' {
3444 found_colon = true;
3445 } else {
3446 chars.push(char);
3447 }
3448 }
3449 // Found a possible emoji shortcode at the beginning of the buffer
3450 chars.reverse();
3451 Some(chars.iter().collect())
3452 }
3453
3454 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3455 self.transact(cx, |this, cx| {
3456 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3457 let selections = this.selections.all::<usize>(cx);
3458 let multi_buffer = this.buffer.read(cx);
3459 let buffer = multi_buffer.snapshot(cx);
3460 selections
3461 .iter()
3462 .map(|selection| {
3463 let start_point = selection.start.to_point(&buffer);
3464 let mut indent =
3465 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3466 indent.len = cmp::min(indent.len, start_point.column);
3467 let start = selection.start;
3468 let end = selection.end;
3469 let selection_is_empty = start == end;
3470 let language_scope = buffer.language_scope_at(start);
3471 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3472 &language_scope
3473 {
3474 let leading_whitespace_len = buffer
3475 .reversed_chars_at(start)
3476 .take_while(|c| c.is_whitespace() && *c != '\n')
3477 .map(|c| c.len_utf8())
3478 .sum::<usize>();
3479
3480 let trailing_whitespace_len = buffer
3481 .chars_at(end)
3482 .take_while(|c| c.is_whitespace() && *c != '\n')
3483 .map(|c| c.len_utf8())
3484 .sum::<usize>();
3485
3486 let insert_extra_newline =
3487 language.brackets().any(|(pair, enabled)| {
3488 let pair_start = pair.start.trim_end();
3489 let pair_end = pair.end.trim_start();
3490
3491 enabled
3492 && pair.newline
3493 && buffer.contains_str_at(
3494 end + trailing_whitespace_len,
3495 pair_end,
3496 )
3497 && buffer.contains_str_at(
3498 (start - leading_whitespace_len)
3499 .saturating_sub(pair_start.len()),
3500 pair_start,
3501 )
3502 });
3503
3504 // Comment extension on newline is allowed only for cursor selections
3505 let comment_delimiter = maybe!({
3506 if !selection_is_empty {
3507 return None;
3508 }
3509
3510 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3511 return None;
3512 }
3513
3514 let delimiters = language.line_comment_prefixes();
3515 let max_len_of_delimiter =
3516 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3517 let (snapshot, range) =
3518 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3519
3520 let mut index_of_first_non_whitespace = 0;
3521 let comment_candidate = snapshot
3522 .chars_for_range(range)
3523 .skip_while(|c| {
3524 let should_skip = c.is_whitespace();
3525 if should_skip {
3526 index_of_first_non_whitespace += 1;
3527 }
3528 should_skip
3529 })
3530 .take(max_len_of_delimiter)
3531 .collect::<String>();
3532 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3533 comment_candidate.starts_with(comment_prefix.as_ref())
3534 })?;
3535 let cursor_is_placed_after_comment_marker =
3536 index_of_first_non_whitespace + comment_prefix.len()
3537 <= start_point.column as usize;
3538 if cursor_is_placed_after_comment_marker {
3539 Some(comment_prefix.clone())
3540 } else {
3541 None
3542 }
3543 });
3544 (comment_delimiter, insert_extra_newline)
3545 } else {
3546 (None, false)
3547 };
3548
3549 let capacity_for_delimiter = comment_delimiter
3550 .as_deref()
3551 .map(str::len)
3552 .unwrap_or_default();
3553 let mut new_text =
3554 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3555 new_text.push_str("\n");
3556 new_text.extend(indent.chars());
3557 if let Some(delimiter) = &comment_delimiter {
3558 new_text.push_str(&delimiter);
3559 }
3560 if insert_extra_newline {
3561 new_text = new_text.repeat(2);
3562 }
3563
3564 let anchor = buffer.anchor_after(end);
3565 let new_selection = selection.map(|_| anchor);
3566 (
3567 (start..end, new_text),
3568 (insert_extra_newline, new_selection),
3569 )
3570 })
3571 .unzip()
3572 };
3573
3574 this.edit_with_autoindent(edits, cx);
3575 let buffer = this.buffer.read(cx).snapshot(cx);
3576 let new_selections = selection_fixup_info
3577 .into_iter()
3578 .map(|(extra_newline_inserted, new_selection)| {
3579 let mut cursor = new_selection.end.to_point(&buffer);
3580 if extra_newline_inserted {
3581 cursor.row -= 1;
3582 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3583 }
3584 new_selection.map(|_| cursor)
3585 })
3586 .collect();
3587
3588 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3589 this.refresh_inline_completion(true, false, cx);
3590 });
3591 }
3592
3593 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3594 let buffer = self.buffer.read(cx);
3595 let snapshot = buffer.snapshot(cx);
3596
3597 let mut edits = Vec::new();
3598 let mut rows = Vec::new();
3599
3600 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3601 let cursor = selection.head();
3602 let row = cursor.row;
3603
3604 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3605
3606 let newline = "\n".to_string();
3607 edits.push((start_of_line..start_of_line, newline));
3608
3609 rows.push(row + rows_inserted as u32);
3610 }
3611
3612 self.transact(cx, |editor, cx| {
3613 editor.edit(edits, cx);
3614
3615 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3616 let mut index = 0;
3617 s.move_cursors_with(|map, _, _| {
3618 let row = rows[index];
3619 index += 1;
3620
3621 let point = Point::new(row, 0);
3622 let boundary = map.next_line_boundary(point).1;
3623 let clipped = map.clip_point(boundary, Bias::Left);
3624
3625 (clipped, SelectionGoal::None)
3626 });
3627 });
3628
3629 let mut indent_edits = Vec::new();
3630 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3631 for row in rows {
3632 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3633 for (row, indent) in indents {
3634 if indent.len == 0 {
3635 continue;
3636 }
3637
3638 let text = match indent.kind {
3639 IndentKind::Space => " ".repeat(indent.len as usize),
3640 IndentKind::Tab => "\t".repeat(indent.len as usize),
3641 };
3642 let point = Point::new(row.0, 0);
3643 indent_edits.push((point..point, text));
3644 }
3645 }
3646 editor.edit(indent_edits, cx);
3647 });
3648 }
3649
3650 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3651 let buffer = self.buffer.read(cx);
3652 let snapshot = buffer.snapshot(cx);
3653
3654 let mut edits = Vec::new();
3655 let mut rows = Vec::new();
3656 let mut rows_inserted = 0;
3657
3658 for selection in self.selections.all_adjusted(cx) {
3659 let cursor = selection.head();
3660 let row = cursor.row;
3661
3662 let point = Point::new(row + 1, 0);
3663 let start_of_line = snapshot.clip_point(point, Bias::Left);
3664
3665 let newline = "\n".to_string();
3666 edits.push((start_of_line..start_of_line, newline));
3667
3668 rows_inserted += 1;
3669 rows.push(row + rows_inserted);
3670 }
3671
3672 self.transact(cx, |editor, cx| {
3673 editor.edit(edits, cx);
3674
3675 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3676 let mut index = 0;
3677 s.move_cursors_with(|map, _, _| {
3678 let row = rows[index];
3679 index += 1;
3680
3681 let point = Point::new(row, 0);
3682 let boundary = map.next_line_boundary(point).1;
3683 let clipped = map.clip_point(boundary, Bias::Left);
3684
3685 (clipped, SelectionGoal::None)
3686 });
3687 });
3688
3689 let mut indent_edits = Vec::new();
3690 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3691 for row in rows {
3692 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3693 for (row, indent) in indents {
3694 if indent.len == 0 {
3695 continue;
3696 }
3697
3698 let text = match indent.kind {
3699 IndentKind::Space => " ".repeat(indent.len as usize),
3700 IndentKind::Tab => "\t".repeat(indent.len as usize),
3701 };
3702 let point = Point::new(row.0, 0);
3703 indent_edits.push((point..point, text));
3704 }
3705 }
3706 editor.edit(indent_edits, cx);
3707 });
3708 }
3709
3710 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3711 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3712 original_indent_columns: Vec::new(),
3713 });
3714 self.insert_with_autoindent_mode(text, autoindent, cx);
3715 }
3716
3717 fn insert_with_autoindent_mode(
3718 &mut self,
3719 text: &str,
3720 autoindent_mode: Option<AutoindentMode>,
3721 cx: &mut ViewContext<Self>,
3722 ) {
3723 if self.read_only(cx) {
3724 return;
3725 }
3726
3727 let text: Arc<str> = text.into();
3728 self.transact(cx, |this, cx| {
3729 let old_selections = this.selections.all_adjusted(cx);
3730 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3731 let anchors = {
3732 let snapshot = buffer.read(cx);
3733 old_selections
3734 .iter()
3735 .map(|s| {
3736 let anchor = snapshot.anchor_after(s.head());
3737 s.map(|_| anchor)
3738 })
3739 .collect::<Vec<_>>()
3740 };
3741 buffer.edit(
3742 old_selections
3743 .iter()
3744 .map(|s| (s.start..s.end, text.clone())),
3745 autoindent_mode,
3746 cx,
3747 );
3748 anchors
3749 });
3750
3751 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3752 s.select_anchors(selection_anchors);
3753 })
3754 });
3755 }
3756
3757 fn trigger_completion_on_input(
3758 &mut self,
3759 text: &str,
3760 trigger_in_words: bool,
3761 cx: &mut ViewContext<Self>,
3762 ) {
3763 if self.is_completion_trigger(text, trigger_in_words, cx) {
3764 self.show_completions(
3765 &ShowCompletions {
3766 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3767 },
3768 cx,
3769 );
3770 } else {
3771 self.hide_context_menu(cx);
3772 }
3773 }
3774
3775 fn is_completion_trigger(
3776 &self,
3777 text: &str,
3778 trigger_in_words: bool,
3779 cx: &mut ViewContext<Self>,
3780 ) -> bool {
3781 let position = self.selections.newest_anchor().head();
3782 let multibuffer = self.buffer.read(cx);
3783 let Some(buffer) = position
3784 .buffer_id
3785 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3786 else {
3787 return false;
3788 };
3789
3790 if let Some(completion_provider) = &self.completion_provider {
3791 completion_provider.is_completion_trigger(
3792 &buffer,
3793 position.text_anchor,
3794 text,
3795 trigger_in_words,
3796 cx,
3797 )
3798 } else {
3799 false
3800 }
3801 }
3802
3803 /// If any empty selections is touching the start of its innermost containing autoclose
3804 /// region, expand it to select the brackets.
3805 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3806 let selections = self.selections.all::<usize>(cx);
3807 let buffer = self.buffer.read(cx).read(cx);
3808 let new_selections = self
3809 .selections_with_autoclose_regions(selections, &buffer)
3810 .map(|(mut selection, region)| {
3811 if !selection.is_empty() {
3812 return selection;
3813 }
3814
3815 if let Some(region) = region {
3816 let mut range = region.range.to_offset(&buffer);
3817 if selection.start == range.start && range.start >= region.pair.start.len() {
3818 range.start -= region.pair.start.len();
3819 if buffer.contains_str_at(range.start, ®ion.pair.start)
3820 && buffer.contains_str_at(range.end, ®ion.pair.end)
3821 {
3822 range.end += region.pair.end.len();
3823 selection.start = range.start;
3824 selection.end = range.end;
3825
3826 return selection;
3827 }
3828 }
3829 }
3830
3831 let always_treat_brackets_as_autoclosed = buffer
3832 .settings_at(selection.start, cx)
3833 .always_treat_brackets_as_autoclosed;
3834
3835 if !always_treat_brackets_as_autoclosed {
3836 return selection;
3837 }
3838
3839 if let Some(scope) = buffer.language_scope_at(selection.start) {
3840 for (pair, enabled) in scope.brackets() {
3841 if !enabled || !pair.close {
3842 continue;
3843 }
3844
3845 if buffer.contains_str_at(selection.start, &pair.end) {
3846 let pair_start_len = pair.start.len();
3847 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3848 {
3849 selection.start -= pair_start_len;
3850 selection.end += pair.end.len();
3851
3852 return selection;
3853 }
3854 }
3855 }
3856 }
3857
3858 selection
3859 })
3860 .collect();
3861
3862 drop(buffer);
3863 self.change_selections(None, cx, |selections| selections.select(new_selections));
3864 }
3865
3866 /// Iterate the given selections, and for each one, find the smallest surrounding
3867 /// autoclose region. This uses the ordering of the selections and the autoclose
3868 /// regions to avoid repeated comparisons.
3869 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3870 &'a self,
3871 selections: impl IntoIterator<Item = Selection<D>>,
3872 buffer: &'a MultiBufferSnapshot,
3873 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3874 let mut i = 0;
3875 let mut regions = self.autoclose_regions.as_slice();
3876 selections.into_iter().map(move |selection| {
3877 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3878
3879 let mut enclosing = None;
3880 while let Some(pair_state) = regions.get(i) {
3881 if pair_state.range.end.to_offset(buffer) < range.start {
3882 regions = ®ions[i + 1..];
3883 i = 0;
3884 } else if pair_state.range.start.to_offset(buffer) > range.end {
3885 break;
3886 } else {
3887 if pair_state.selection_id == selection.id {
3888 enclosing = Some(pair_state);
3889 }
3890 i += 1;
3891 }
3892 }
3893
3894 (selection.clone(), enclosing)
3895 })
3896 }
3897
3898 /// Remove any autoclose regions that no longer contain their selection.
3899 fn invalidate_autoclose_regions(
3900 &mut self,
3901 mut selections: &[Selection<Anchor>],
3902 buffer: &MultiBufferSnapshot,
3903 ) {
3904 self.autoclose_regions.retain(|state| {
3905 let mut i = 0;
3906 while let Some(selection) = selections.get(i) {
3907 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3908 selections = &selections[1..];
3909 continue;
3910 }
3911 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3912 break;
3913 }
3914 if selection.id == state.selection_id {
3915 return true;
3916 } else {
3917 i += 1;
3918 }
3919 }
3920 false
3921 });
3922 }
3923
3924 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3925 let offset = position.to_offset(buffer);
3926 let (word_range, kind) = buffer.surrounding_word(offset);
3927 if offset > word_range.start && kind == Some(CharKind::Word) {
3928 Some(
3929 buffer
3930 .text_for_range(word_range.start..offset)
3931 .collect::<String>(),
3932 )
3933 } else {
3934 None
3935 }
3936 }
3937
3938 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3939 self.refresh_inlay_hints(
3940 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3941 cx,
3942 );
3943 }
3944
3945 pub fn inlay_hints_enabled(&self) -> bool {
3946 self.inlay_hint_cache.enabled
3947 }
3948
3949 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3950 if self.project.is_none() || self.mode != EditorMode::Full {
3951 return;
3952 }
3953
3954 let reason_description = reason.description();
3955 let ignore_debounce = matches!(
3956 reason,
3957 InlayHintRefreshReason::SettingsChange(_)
3958 | InlayHintRefreshReason::Toggle(_)
3959 | InlayHintRefreshReason::ExcerptsRemoved(_)
3960 );
3961 let (invalidate_cache, required_languages) = match reason {
3962 InlayHintRefreshReason::Toggle(enabled) => {
3963 self.inlay_hint_cache.enabled = enabled;
3964 if enabled {
3965 (InvalidationStrategy::RefreshRequested, None)
3966 } else {
3967 self.inlay_hint_cache.clear();
3968 self.splice_inlays(
3969 self.visible_inlay_hints(cx)
3970 .iter()
3971 .map(|inlay| inlay.id)
3972 .collect(),
3973 Vec::new(),
3974 cx,
3975 );
3976 return;
3977 }
3978 }
3979 InlayHintRefreshReason::SettingsChange(new_settings) => {
3980 match self.inlay_hint_cache.update_settings(
3981 &self.buffer,
3982 new_settings,
3983 self.visible_inlay_hints(cx),
3984 cx,
3985 ) {
3986 ControlFlow::Break(Some(InlaySplice {
3987 to_remove,
3988 to_insert,
3989 })) => {
3990 self.splice_inlays(to_remove, to_insert, cx);
3991 return;
3992 }
3993 ControlFlow::Break(None) => return,
3994 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3995 }
3996 }
3997 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3998 if let Some(InlaySplice {
3999 to_remove,
4000 to_insert,
4001 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4002 {
4003 self.splice_inlays(to_remove, to_insert, cx);
4004 }
4005 return;
4006 }
4007 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4008 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4009 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4010 }
4011 InlayHintRefreshReason::RefreshRequested => {
4012 (InvalidationStrategy::RefreshRequested, None)
4013 }
4014 };
4015
4016 if let Some(InlaySplice {
4017 to_remove,
4018 to_insert,
4019 }) = self.inlay_hint_cache.spawn_hint_refresh(
4020 reason_description,
4021 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4022 invalidate_cache,
4023 ignore_debounce,
4024 cx,
4025 ) {
4026 self.splice_inlays(to_remove, to_insert, cx);
4027 }
4028 }
4029
4030 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4031 self.display_map
4032 .read(cx)
4033 .current_inlays()
4034 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4035 .cloned()
4036 .collect()
4037 }
4038
4039 pub fn excerpts_for_inlay_hints_query(
4040 &self,
4041 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4042 cx: &mut ViewContext<Editor>,
4043 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4044 let Some(project) = self.project.as_ref() else {
4045 return HashMap::default();
4046 };
4047 let project = project.read(cx);
4048 let multi_buffer = self.buffer().read(cx);
4049 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4050 let multi_buffer_visible_start = self
4051 .scroll_manager
4052 .anchor()
4053 .anchor
4054 .to_point(&multi_buffer_snapshot);
4055 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4056 multi_buffer_visible_start
4057 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4058 Bias::Left,
4059 );
4060 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4061 multi_buffer
4062 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4063 .into_iter()
4064 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4065 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4066 let buffer = buffer_handle.read(cx);
4067 let buffer_file = project::File::from_dyn(buffer.file())?;
4068 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4069 let worktree_entry = buffer_worktree
4070 .read(cx)
4071 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4072 if worktree_entry.is_ignored {
4073 return None;
4074 }
4075
4076 let language = buffer.language()?;
4077 if let Some(restrict_to_languages) = restrict_to_languages {
4078 if !restrict_to_languages.contains(language) {
4079 return None;
4080 }
4081 }
4082 Some((
4083 excerpt_id,
4084 (
4085 buffer_handle,
4086 buffer.version().clone(),
4087 excerpt_visible_range,
4088 ),
4089 ))
4090 })
4091 .collect()
4092 }
4093
4094 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4095 TextLayoutDetails {
4096 text_system: cx.text_system().clone(),
4097 editor_style: self.style.clone().unwrap(),
4098 rem_size: cx.rem_size(),
4099 scroll_anchor: self.scroll_manager.anchor(),
4100 visible_rows: self.visible_line_count(),
4101 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4102 }
4103 }
4104
4105 fn splice_inlays(
4106 &self,
4107 to_remove: Vec<InlayId>,
4108 to_insert: Vec<Inlay>,
4109 cx: &mut ViewContext<Self>,
4110 ) {
4111 self.display_map.update(cx, |display_map, cx| {
4112 display_map.splice_inlays(to_remove, to_insert, cx);
4113 });
4114 cx.notify();
4115 }
4116
4117 fn trigger_on_type_formatting(
4118 &self,
4119 input: String,
4120 cx: &mut ViewContext<Self>,
4121 ) -> Option<Task<Result<()>>> {
4122 if input.len() != 1 {
4123 return None;
4124 }
4125
4126 let project = self.project.as_ref()?;
4127 let position = self.selections.newest_anchor().head();
4128 let (buffer, buffer_position) = self
4129 .buffer
4130 .read(cx)
4131 .text_anchor_for_position(position, cx)?;
4132
4133 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4134 // hence we do LSP request & edit on host side only — add formats to host's history.
4135 let push_to_lsp_host_history = true;
4136 // If this is not the host, append its history with new edits.
4137 let push_to_client_history = project.read(cx).is_via_collab();
4138
4139 let on_type_formatting = project.update(cx, |project, cx| {
4140 project.on_type_format(
4141 buffer.clone(),
4142 buffer_position,
4143 input,
4144 push_to_lsp_host_history,
4145 cx,
4146 )
4147 });
4148 Some(cx.spawn(|editor, mut cx| async move {
4149 if let Some(transaction) = on_type_formatting.await? {
4150 if push_to_client_history {
4151 buffer
4152 .update(&mut cx, |buffer, _| {
4153 buffer.push_transaction(transaction, Instant::now());
4154 })
4155 .ok();
4156 }
4157 editor.update(&mut cx, |editor, cx| {
4158 editor.refresh_document_highlights(cx);
4159 })?;
4160 }
4161 Ok(())
4162 }))
4163 }
4164
4165 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4166 if self.pending_rename.is_some() {
4167 return;
4168 }
4169
4170 let Some(provider) = self.completion_provider.as_ref() else {
4171 return;
4172 };
4173
4174 let position = self.selections.newest_anchor().head();
4175 let (buffer, buffer_position) =
4176 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4177 output
4178 } else {
4179 return;
4180 };
4181
4182 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4183 let is_followup_invoke = {
4184 let context_menu_state = self.context_menu.read();
4185 matches!(
4186 context_menu_state.deref(),
4187 Some(ContextMenu::Completions(_))
4188 )
4189 };
4190 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4191 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4192 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(&trigger) => {
4193 CompletionTriggerKind::TRIGGER_CHARACTER
4194 }
4195
4196 _ => CompletionTriggerKind::INVOKED,
4197 };
4198 let completion_context = CompletionContext {
4199 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4200 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4201 Some(String::from(trigger))
4202 } else {
4203 None
4204 }
4205 }),
4206 trigger_kind,
4207 };
4208 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4209 let sort_completions = provider.sort_completions();
4210
4211 let id = post_inc(&mut self.next_completion_id);
4212 let task = cx.spawn(|this, mut cx| {
4213 async move {
4214 this.update(&mut cx, |this, _| {
4215 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4216 })?;
4217 let completions = completions.await.log_err();
4218 let menu = if let Some(completions) = completions {
4219 let mut menu = CompletionsMenu {
4220 id,
4221 sort_completions,
4222 initial_position: position,
4223 match_candidates: completions
4224 .iter()
4225 .enumerate()
4226 .map(|(id, completion)| {
4227 StringMatchCandidate::new(
4228 id,
4229 completion.label.text[completion.label.filter_range.clone()]
4230 .into(),
4231 )
4232 })
4233 .collect(),
4234 buffer: buffer.clone(),
4235 completions: Arc::new(RwLock::new(completions.into())),
4236 matches: Vec::new().into(),
4237 selected_item: 0,
4238 scroll_handle: UniformListScrollHandle::new(),
4239 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4240 DebouncedDelay::new(),
4241 )),
4242 };
4243 menu.filter(query.as_deref(), cx.background_executor().clone())
4244 .await;
4245
4246 if menu.matches.is_empty() {
4247 None
4248 } else {
4249 this.update(&mut cx, |editor, cx| {
4250 let completions = menu.completions.clone();
4251 let matches = menu.matches.clone();
4252
4253 let delay_ms = EditorSettings::get_global(cx)
4254 .completion_documentation_secondary_query_debounce;
4255 let delay = Duration::from_millis(delay_ms);
4256 editor
4257 .completion_documentation_pre_resolve_debounce
4258 .fire_new(delay, cx, |editor, cx| {
4259 CompletionsMenu::pre_resolve_completion_documentation(
4260 buffer,
4261 completions,
4262 matches,
4263 editor,
4264 cx,
4265 )
4266 });
4267 })
4268 .ok();
4269 Some(menu)
4270 }
4271 } else {
4272 None
4273 };
4274
4275 this.update(&mut cx, |this, cx| {
4276 let mut context_menu = this.context_menu.write();
4277 match context_menu.as_ref() {
4278 None => {}
4279
4280 Some(ContextMenu::Completions(prev_menu)) => {
4281 if prev_menu.id > id {
4282 return;
4283 }
4284 }
4285
4286 _ => return,
4287 }
4288
4289 if this.focus_handle.is_focused(cx) && menu.is_some() {
4290 let menu = menu.unwrap();
4291 *context_menu = Some(ContextMenu::Completions(menu));
4292 drop(context_menu);
4293 this.discard_inline_completion(false, cx);
4294 cx.notify();
4295 } else if this.completion_tasks.len() <= 1 {
4296 // If there are no more completion tasks and the last menu was
4297 // empty, we should hide it. If it was already hidden, we should
4298 // also show the copilot completion when available.
4299 drop(context_menu);
4300 if this.hide_context_menu(cx).is_none() {
4301 this.update_visible_inline_completion(cx);
4302 }
4303 }
4304 })?;
4305
4306 Ok::<_, anyhow::Error>(())
4307 }
4308 .log_err()
4309 });
4310
4311 self.completion_tasks.push((id, task));
4312 }
4313
4314 pub fn confirm_completion(
4315 &mut self,
4316 action: &ConfirmCompletion,
4317 cx: &mut ViewContext<Self>,
4318 ) -> Option<Task<Result<()>>> {
4319 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4320 }
4321
4322 pub fn compose_completion(
4323 &mut self,
4324 action: &ComposeCompletion,
4325 cx: &mut ViewContext<Self>,
4326 ) -> Option<Task<Result<()>>> {
4327 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4328 }
4329
4330 fn do_completion(
4331 &mut self,
4332 item_ix: Option<usize>,
4333 intent: CompletionIntent,
4334 cx: &mut ViewContext<Editor>,
4335 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4336 use language::ToOffset as _;
4337
4338 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4339 menu
4340 } else {
4341 return None;
4342 };
4343
4344 let mat = completions_menu
4345 .matches
4346 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4347 let buffer_handle = completions_menu.buffer;
4348 let completions = completions_menu.completions.read();
4349 let completion = completions.get(mat.candidate_id)?;
4350 cx.stop_propagation();
4351
4352 let snippet;
4353 let text;
4354
4355 if completion.is_snippet() {
4356 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4357 text = snippet.as_ref().unwrap().text.clone();
4358 } else {
4359 snippet = None;
4360 text = completion.new_text.clone();
4361 };
4362 let selections = self.selections.all::<usize>(cx);
4363 let buffer = buffer_handle.read(cx);
4364 let old_range = completion.old_range.to_offset(buffer);
4365 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4366
4367 let newest_selection = self.selections.newest_anchor();
4368 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4369 return None;
4370 }
4371
4372 let lookbehind = newest_selection
4373 .start
4374 .text_anchor
4375 .to_offset(buffer)
4376 .saturating_sub(old_range.start);
4377 let lookahead = old_range
4378 .end
4379 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4380 let mut common_prefix_len = old_text
4381 .bytes()
4382 .zip(text.bytes())
4383 .take_while(|(a, b)| a == b)
4384 .count();
4385
4386 let snapshot = self.buffer.read(cx).snapshot(cx);
4387 let mut range_to_replace: Option<Range<isize>> = None;
4388 let mut ranges = Vec::new();
4389 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4390 for selection in &selections {
4391 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4392 let start = selection.start.saturating_sub(lookbehind);
4393 let end = selection.end + lookahead;
4394 if selection.id == newest_selection.id {
4395 range_to_replace = Some(
4396 ((start + common_prefix_len) as isize - selection.start as isize)
4397 ..(end as isize - selection.start as isize),
4398 );
4399 }
4400 ranges.push(start + common_prefix_len..end);
4401 } else {
4402 common_prefix_len = 0;
4403 ranges.clear();
4404 ranges.extend(selections.iter().map(|s| {
4405 if s.id == newest_selection.id {
4406 range_to_replace = Some(
4407 old_range.start.to_offset_utf16(&snapshot).0 as isize
4408 - selection.start as isize
4409 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4410 - selection.start as isize,
4411 );
4412 old_range.clone()
4413 } else {
4414 s.start..s.end
4415 }
4416 }));
4417 break;
4418 }
4419 if !self.linked_edit_ranges.is_empty() {
4420 let start_anchor = snapshot.anchor_before(selection.head());
4421 let end_anchor = snapshot.anchor_after(selection.tail());
4422 if let Some(ranges) = self
4423 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4424 {
4425 for (buffer, edits) in ranges {
4426 linked_edits.entry(buffer.clone()).or_default().extend(
4427 edits
4428 .into_iter()
4429 .map(|range| (range, text[common_prefix_len..].to_owned())),
4430 );
4431 }
4432 }
4433 }
4434 }
4435 let text = &text[common_prefix_len..];
4436
4437 cx.emit(EditorEvent::InputHandled {
4438 utf16_range_to_replace: range_to_replace,
4439 text: text.into(),
4440 });
4441
4442 self.transact(cx, |this, cx| {
4443 if let Some(mut snippet) = snippet {
4444 snippet.text = text.to_string();
4445 for tabstop in snippet.tabstops.iter_mut().flatten() {
4446 tabstop.start -= common_prefix_len as isize;
4447 tabstop.end -= common_prefix_len as isize;
4448 }
4449
4450 this.insert_snippet(&ranges, snippet, cx).log_err();
4451 } else {
4452 this.buffer.update(cx, |buffer, cx| {
4453 buffer.edit(
4454 ranges.iter().map(|range| (range.clone(), text)),
4455 this.autoindent_mode.clone(),
4456 cx,
4457 );
4458 });
4459 }
4460 for (buffer, edits) in linked_edits {
4461 buffer.update(cx, |buffer, cx| {
4462 let snapshot = buffer.snapshot();
4463 let edits = edits
4464 .into_iter()
4465 .map(|(range, text)| {
4466 use text::ToPoint as TP;
4467 let end_point = TP::to_point(&range.end, &snapshot);
4468 let start_point = TP::to_point(&range.start, &snapshot);
4469 (start_point..end_point, text)
4470 })
4471 .sorted_by_key(|(range, _)| range.start)
4472 .collect::<Vec<_>>();
4473 buffer.edit(edits, None, cx);
4474 })
4475 }
4476
4477 this.refresh_inline_completion(true, false, cx);
4478 });
4479
4480 let show_new_completions_on_confirm = completion
4481 .confirm
4482 .as_ref()
4483 .map_or(false, |confirm| confirm(intent, cx));
4484 if show_new_completions_on_confirm {
4485 self.show_completions(&ShowCompletions { trigger: None }, cx);
4486 }
4487
4488 let provider = self.completion_provider.as_ref()?;
4489 let apply_edits = provider.apply_additional_edits_for_completion(
4490 buffer_handle,
4491 completion.clone(),
4492 true,
4493 cx,
4494 );
4495
4496 let editor_settings = EditorSettings::get_global(cx);
4497 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4498 // After the code completion is finished, users often want to know what signatures are needed.
4499 // so we should automatically call signature_help
4500 self.show_signature_help(&ShowSignatureHelp, cx);
4501 }
4502
4503 Some(cx.foreground_executor().spawn(async move {
4504 apply_edits.await?;
4505 Ok(())
4506 }))
4507 }
4508
4509 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4510 let mut context_menu = self.context_menu.write();
4511 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4512 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4513 // Toggle if we're selecting the same one
4514 *context_menu = None;
4515 cx.notify();
4516 return;
4517 } else {
4518 // Otherwise, clear it and start a new one
4519 *context_menu = None;
4520 cx.notify();
4521 }
4522 }
4523 drop(context_menu);
4524 let snapshot = self.snapshot(cx);
4525 let deployed_from_indicator = action.deployed_from_indicator;
4526 let mut task = self.code_actions_task.take();
4527 let action = action.clone();
4528 cx.spawn(|editor, mut cx| async move {
4529 while let Some(prev_task) = task {
4530 prev_task.await;
4531 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4532 }
4533
4534 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4535 if editor.focus_handle.is_focused(cx) {
4536 let multibuffer_point = action
4537 .deployed_from_indicator
4538 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4539 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4540 let (buffer, buffer_row) = snapshot
4541 .buffer_snapshot
4542 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4543 .and_then(|(buffer_snapshot, range)| {
4544 editor
4545 .buffer
4546 .read(cx)
4547 .buffer(buffer_snapshot.remote_id())
4548 .map(|buffer| (buffer, range.start.row))
4549 })?;
4550 let (_, code_actions) = editor
4551 .available_code_actions
4552 .clone()
4553 .and_then(|(location, code_actions)| {
4554 let snapshot = location.buffer.read(cx).snapshot();
4555 let point_range = location.range.to_point(&snapshot);
4556 let point_range = point_range.start.row..=point_range.end.row;
4557 if point_range.contains(&buffer_row) {
4558 Some((location, code_actions))
4559 } else {
4560 None
4561 }
4562 })
4563 .unzip();
4564 let buffer_id = buffer.read(cx).remote_id();
4565 let tasks = editor
4566 .tasks
4567 .get(&(buffer_id, buffer_row))
4568 .map(|t| Arc::new(t.to_owned()));
4569 if tasks.is_none() && code_actions.is_none() {
4570 return None;
4571 }
4572
4573 editor.completion_tasks.clear();
4574 editor.discard_inline_completion(false, cx);
4575 let task_context =
4576 tasks
4577 .as_ref()
4578 .zip(editor.project.clone())
4579 .map(|(tasks, project)| {
4580 let position = Point::new(buffer_row, tasks.column);
4581 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4582 let location = Location {
4583 buffer: buffer.clone(),
4584 range: range_start..range_start,
4585 };
4586 // Fill in the environmental variables from the tree-sitter captures
4587 let mut captured_task_variables = TaskVariables::default();
4588 for (capture_name, value) in tasks.extra_variables.clone() {
4589 captured_task_variables.insert(
4590 task::VariableName::Custom(capture_name.into()),
4591 value.clone(),
4592 );
4593 }
4594 project.update(cx, |project, cx| {
4595 project.task_context_for_location(
4596 captured_task_variables,
4597 location,
4598 cx,
4599 )
4600 })
4601 });
4602
4603 Some(cx.spawn(|editor, mut cx| async move {
4604 let task_context = match task_context {
4605 Some(task_context) => task_context.await,
4606 None => None,
4607 };
4608 let resolved_tasks =
4609 tasks.zip(task_context).map(|(tasks, task_context)| {
4610 Arc::new(ResolvedTasks {
4611 templates: tasks
4612 .templates
4613 .iter()
4614 .filter_map(|(kind, template)| {
4615 template
4616 .resolve_task(&kind.to_id_base(), &task_context)
4617 .map(|task| (kind.clone(), task))
4618 })
4619 .collect(),
4620 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4621 multibuffer_point.row,
4622 tasks.column,
4623 )),
4624 })
4625 });
4626 let spawn_straight_away = resolved_tasks
4627 .as_ref()
4628 .map_or(false, |tasks| tasks.templates.len() == 1)
4629 && code_actions
4630 .as_ref()
4631 .map_or(true, |actions| actions.is_empty());
4632 if let Some(task) = editor
4633 .update(&mut cx, |editor, cx| {
4634 *editor.context_menu.write() =
4635 Some(ContextMenu::CodeActions(CodeActionsMenu {
4636 buffer,
4637 actions: CodeActionContents {
4638 tasks: resolved_tasks,
4639 actions: code_actions,
4640 },
4641 selected_item: Default::default(),
4642 scroll_handle: UniformListScrollHandle::default(),
4643 deployed_from_indicator,
4644 }));
4645 if spawn_straight_away {
4646 if let Some(task) = editor.confirm_code_action(
4647 &ConfirmCodeAction { item_ix: Some(0) },
4648 cx,
4649 ) {
4650 cx.notify();
4651 return task;
4652 }
4653 }
4654 cx.notify();
4655 Task::ready(Ok(()))
4656 })
4657 .ok()
4658 {
4659 task.await
4660 } else {
4661 Ok(())
4662 }
4663 }))
4664 } else {
4665 Some(Task::ready(Ok(())))
4666 }
4667 })?;
4668 if let Some(task) = spawned_test_task {
4669 task.await?;
4670 }
4671
4672 Ok::<_, anyhow::Error>(())
4673 })
4674 .detach_and_log_err(cx);
4675 }
4676
4677 pub fn confirm_code_action(
4678 &mut self,
4679 action: &ConfirmCodeAction,
4680 cx: &mut ViewContext<Self>,
4681 ) -> Option<Task<Result<()>>> {
4682 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4683 menu
4684 } else {
4685 return None;
4686 };
4687 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4688 let action = actions_menu.actions.get(action_ix)?;
4689 let title = action.label();
4690 let buffer = actions_menu.buffer;
4691 let workspace = self.workspace()?;
4692
4693 match action {
4694 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4695 workspace.update(cx, |workspace, cx| {
4696 workspace::tasks::schedule_resolved_task(
4697 workspace,
4698 task_source_kind,
4699 resolved_task,
4700 false,
4701 cx,
4702 );
4703
4704 Some(Task::ready(Ok(())))
4705 })
4706 }
4707 CodeActionsItem::CodeAction(action) => {
4708 let apply_code_actions = workspace
4709 .read(cx)
4710 .project()
4711 .clone()
4712 .update(cx, |project, cx| {
4713 project.apply_code_action(buffer, action, true, cx)
4714 });
4715 let workspace = workspace.downgrade();
4716 Some(cx.spawn(|editor, cx| async move {
4717 let project_transaction = apply_code_actions.await?;
4718 Self::open_project_transaction(
4719 &editor,
4720 workspace,
4721 project_transaction,
4722 title,
4723 cx,
4724 )
4725 .await
4726 }))
4727 }
4728 }
4729 }
4730
4731 pub async fn open_project_transaction(
4732 this: &WeakView<Editor>,
4733 workspace: WeakView<Workspace>,
4734 transaction: ProjectTransaction,
4735 title: String,
4736 mut cx: AsyncWindowContext,
4737 ) -> Result<()> {
4738 let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
4739
4740 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4741 cx.update(|cx| {
4742 entries.sort_unstable_by_key(|(buffer, _)| {
4743 buffer.read(cx).file().map(|f| f.path().clone())
4744 });
4745 })?;
4746
4747 // If the project transaction's edits are all contained within this editor, then
4748 // avoid opening a new editor to display them.
4749
4750 if let Some((buffer, transaction)) = entries.first() {
4751 if entries.len() == 1 {
4752 let excerpt = this.update(&mut cx, |editor, cx| {
4753 editor
4754 .buffer()
4755 .read(cx)
4756 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4757 })?;
4758 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4759 if excerpted_buffer == *buffer {
4760 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4761 let excerpt_range = excerpt_range.to_offset(buffer);
4762 buffer
4763 .edited_ranges_for_transaction::<usize>(transaction)
4764 .all(|range| {
4765 excerpt_range.start <= range.start
4766 && excerpt_range.end >= range.end
4767 })
4768 })?;
4769
4770 if all_edits_within_excerpt {
4771 return Ok(());
4772 }
4773 }
4774 }
4775 }
4776 } else {
4777 return Ok(());
4778 }
4779
4780 let mut ranges_to_highlight = Vec::new();
4781 let excerpt_buffer = cx.new_model(|cx| {
4782 let mut multibuffer =
4783 MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
4784 for (buffer_handle, transaction) in &entries {
4785 let buffer = buffer_handle.read(cx);
4786 ranges_to_highlight.extend(
4787 multibuffer.push_excerpts_with_context_lines(
4788 buffer_handle.clone(),
4789 buffer
4790 .edited_ranges_for_transaction::<usize>(transaction)
4791 .collect(),
4792 DEFAULT_MULTIBUFFER_CONTEXT,
4793 cx,
4794 ),
4795 );
4796 }
4797 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4798 multibuffer
4799 })?;
4800
4801 workspace.update(&mut cx, |workspace, cx| {
4802 let project = workspace.project().clone();
4803 let editor =
4804 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4805 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4806 editor.update(cx, |editor, cx| {
4807 editor.highlight_background::<Self>(
4808 &ranges_to_highlight,
4809 |theme| theme.editor_highlighted_line_background,
4810 cx,
4811 );
4812 });
4813 })?;
4814
4815 Ok(())
4816 }
4817
4818 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4819 let project = self.project.clone()?;
4820 let buffer = self.buffer.read(cx);
4821 let newest_selection = self.selections.newest_anchor().clone();
4822 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4823 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4824 if start_buffer != end_buffer {
4825 return None;
4826 }
4827
4828 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4829 cx.background_executor()
4830 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4831 .await;
4832
4833 let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
4834 project.code_actions(&start_buffer, start..end, cx)
4835 }) {
4836 code_actions.await
4837 } else {
4838 Vec::new()
4839 };
4840
4841 this.update(&mut cx, |this, cx| {
4842 this.available_code_actions = if actions.is_empty() {
4843 None
4844 } else {
4845 Some((
4846 Location {
4847 buffer: start_buffer,
4848 range: start..end,
4849 },
4850 actions.into(),
4851 ))
4852 };
4853 cx.notify();
4854 })
4855 .log_err();
4856 }));
4857 None
4858 }
4859
4860 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4861 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4862 self.show_git_blame_inline = false;
4863
4864 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4865 cx.background_executor().timer(delay).await;
4866
4867 this.update(&mut cx, |this, cx| {
4868 this.show_git_blame_inline = true;
4869 cx.notify();
4870 })
4871 .log_err();
4872 }));
4873 }
4874 }
4875
4876 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4877 if self.pending_rename.is_some() {
4878 return None;
4879 }
4880
4881 let project = self.project.clone()?;
4882 let buffer = self.buffer.read(cx);
4883 let newest_selection = self.selections.newest_anchor().clone();
4884 let cursor_position = newest_selection.head();
4885 let (cursor_buffer, cursor_buffer_position) =
4886 buffer.text_anchor_for_position(cursor_position, cx)?;
4887 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4888 if cursor_buffer != tail_buffer {
4889 return None;
4890 }
4891
4892 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4893 cx.background_executor()
4894 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
4895 .await;
4896
4897 let highlights = if let Some(highlights) = project
4898 .update(&mut cx, |project, cx| {
4899 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4900 })
4901 .log_err()
4902 {
4903 highlights.await.log_err()
4904 } else {
4905 None
4906 };
4907
4908 if let Some(highlights) = highlights {
4909 this.update(&mut cx, |this, cx| {
4910 if this.pending_rename.is_some() {
4911 return;
4912 }
4913
4914 let buffer_id = cursor_position.buffer_id;
4915 let buffer = this.buffer.read(cx);
4916 if !buffer
4917 .text_anchor_for_position(cursor_position, cx)
4918 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4919 {
4920 return;
4921 }
4922
4923 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4924 let mut write_ranges = Vec::new();
4925 let mut read_ranges = Vec::new();
4926 for highlight in highlights {
4927 for (excerpt_id, excerpt_range) in
4928 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4929 {
4930 let start = highlight
4931 .range
4932 .start
4933 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4934 let end = highlight
4935 .range
4936 .end
4937 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4938 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4939 continue;
4940 }
4941
4942 let range = Anchor {
4943 buffer_id,
4944 excerpt_id,
4945 text_anchor: start,
4946 }..Anchor {
4947 buffer_id,
4948 excerpt_id,
4949 text_anchor: end,
4950 };
4951 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4952 write_ranges.push(range);
4953 } else {
4954 read_ranges.push(range);
4955 }
4956 }
4957 }
4958
4959 this.highlight_background::<DocumentHighlightRead>(
4960 &read_ranges,
4961 |theme| theme.editor_document_highlight_read_background,
4962 cx,
4963 );
4964 this.highlight_background::<DocumentHighlightWrite>(
4965 &write_ranges,
4966 |theme| theme.editor_document_highlight_write_background,
4967 cx,
4968 );
4969 cx.notify();
4970 })
4971 .log_err();
4972 }
4973 }));
4974 None
4975 }
4976
4977 pub fn refresh_inline_completion(
4978 &mut self,
4979 debounce: bool,
4980 user_requested: bool,
4981 cx: &mut ViewContext<Self>,
4982 ) -> Option<()> {
4983 let provider = self.inline_completion_provider()?;
4984 let cursor = self.selections.newest_anchor().head();
4985 let (buffer, cursor_buffer_position) =
4986 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4987 if !user_requested
4988 && !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4989 {
4990 self.discard_inline_completion(false, cx);
4991 return None;
4992 }
4993
4994 self.update_visible_inline_completion(cx);
4995 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4996 Some(())
4997 }
4998
4999 fn cycle_inline_completion(
5000 &mut self,
5001 direction: Direction,
5002 cx: &mut ViewContext<Self>,
5003 ) -> Option<()> {
5004 let provider = self.inline_completion_provider()?;
5005 let cursor = self.selections.newest_anchor().head();
5006 let (buffer, cursor_buffer_position) =
5007 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5008 if !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx) {
5009 return None;
5010 }
5011
5012 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5013 self.update_visible_inline_completion(cx);
5014
5015 Some(())
5016 }
5017
5018 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5019 if !self.has_active_inline_completion(cx) {
5020 self.refresh_inline_completion(false, true, cx);
5021 return;
5022 }
5023
5024 self.update_visible_inline_completion(cx);
5025 }
5026
5027 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5028 self.show_cursor_names(cx);
5029 }
5030
5031 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5032 self.show_cursor_names = true;
5033 cx.notify();
5034 cx.spawn(|this, mut cx| async move {
5035 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5036 this.update(&mut cx, |this, cx| {
5037 this.show_cursor_names = false;
5038 cx.notify()
5039 })
5040 .ok()
5041 })
5042 .detach();
5043 }
5044
5045 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5046 if self.has_active_inline_completion(cx) {
5047 self.cycle_inline_completion(Direction::Next, cx);
5048 } else {
5049 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5050 if is_copilot_disabled {
5051 cx.propagate();
5052 }
5053 }
5054 }
5055
5056 pub fn previous_inline_completion(
5057 &mut self,
5058 _: &PreviousInlineCompletion,
5059 cx: &mut ViewContext<Self>,
5060 ) {
5061 if self.has_active_inline_completion(cx) {
5062 self.cycle_inline_completion(Direction::Prev, cx);
5063 } else {
5064 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5065 if is_copilot_disabled {
5066 cx.propagate();
5067 }
5068 }
5069 }
5070
5071 pub fn accept_inline_completion(
5072 &mut self,
5073 _: &AcceptInlineCompletion,
5074 cx: &mut ViewContext<Self>,
5075 ) {
5076 let Some((completion, delete_range)) = self.take_active_inline_completion(cx) else {
5077 return;
5078 };
5079 if let Some(provider) = self.inline_completion_provider() {
5080 provider.accept(cx);
5081 }
5082
5083 cx.emit(EditorEvent::InputHandled {
5084 utf16_range_to_replace: None,
5085 text: completion.text.to_string().into(),
5086 });
5087
5088 if let Some(range) = delete_range {
5089 self.change_selections(None, cx, |s| s.select_ranges([range]))
5090 }
5091 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5092 self.refresh_inline_completion(true, true, cx);
5093 cx.notify();
5094 }
5095
5096 pub fn accept_partial_inline_completion(
5097 &mut self,
5098 _: &AcceptPartialInlineCompletion,
5099 cx: &mut ViewContext<Self>,
5100 ) {
5101 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5102 if let Some((completion, delete_range)) = self.take_active_inline_completion(cx) {
5103 let mut partial_completion = completion
5104 .text
5105 .chars()
5106 .by_ref()
5107 .take_while(|c| c.is_alphabetic())
5108 .collect::<String>();
5109 if partial_completion.is_empty() {
5110 partial_completion = completion
5111 .text
5112 .chars()
5113 .by_ref()
5114 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5115 .collect::<String>();
5116 }
5117
5118 cx.emit(EditorEvent::InputHandled {
5119 utf16_range_to_replace: None,
5120 text: partial_completion.clone().into(),
5121 });
5122
5123 if let Some(range) = delete_range {
5124 self.change_selections(None, cx, |s| s.select_ranges([range]))
5125 }
5126 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5127
5128 self.refresh_inline_completion(true, true, cx);
5129 cx.notify();
5130 }
5131 }
5132 }
5133
5134 fn discard_inline_completion(
5135 &mut self,
5136 should_report_inline_completion_event: bool,
5137 cx: &mut ViewContext<Self>,
5138 ) -> bool {
5139 if let Some(provider) = self.inline_completion_provider() {
5140 provider.discard(should_report_inline_completion_event, cx);
5141 }
5142
5143 self.take_active_inline_completion(cx).is_some()
5144 }
5145
5146 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5147 if let Some(completion) = self.active_inline_completion.as_ref() {
5148 let buffer = self.buffer.read(cx).read(cx);
5149 completion.0.position.is_valid(&buffer)
5150 } else {
5151 false
5152 }
5153 }
5154
5155 fn take_active_inline_completion(
5156 &mut self,
5157 cx: &mut ViewContext<Self>,
5158 ) -> Option<(Inlay, Option<Range<Anchor>>)> {
5159 let completion = self.active_inline_completion.take()?;
5160 self.display_map.update(cx, |map, cx| {
5161 map.splice_inlays(vec![completion.0.id], Default::default(), cx);
5162 });
5163 let buffer = self.buffer.read(cx).read(cx);
5164
5165 if completion.0.position.is_valid(&buffer) {
5166 Some(completion)
5167 } else {
5168 None
5169 }
5170 }
5171
5172 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5173 let selection = self.selections.newest_anchor();
5174 let cursor = selection.head();
5175
5176 let excerpt_id = cursor.excerpt_id;
5177
5178 if self.context_menu.read().is_none()
5179 && self.completion_tasks.is_empty()
5180 && selection.start == selection.end
5181 {
5182 if let Some(provider) = self.inline_completion_provider() {
5183 if let Some((buffer, cursor_buffer_position)) =
5184 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5185 {
5186 if let Some((text, text_anchor_range)) =
5187 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5188 {
5189 let text = Rope::from(text);
5190 let mut to_remove = Vec::new();
5191 if let Some(completion) = self.active_inline_completion.take() {
5192 to_remove.push(completion.0.id);
5193 }
5194
5195 let completion_inlay =
5196 Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
5197
5198 let multibuffer_anchor_range = text_anchor_range.and_then(|range| {
5199 let snapshot = self.buffer.read(cx).snapshot(cx);
5200 Some(
5201 snapshot.anchor_in_excerpt(excerpt_id, range.start)?
5202 ..snapshot.anchor_in_excerpt(excerpt_id, range.end)?,
5203 )
5204 });
5205 self.active_inline_completion =
5206 Some((completion_inlay.clone(), multibuffer_anchor_range));
5207
5208 self.display_map.update(cx, move |map, cx| {
5209 map.splice_inlays(to_remove, vec![completion_inlay], cx)
5210 });
5211 cx.notify();
5212 return;
5213 }
5214 }
5215 }
5216 }
5217
5218 self.discard_inline_completion(false, cx);
5219 }
5220
5221 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5222 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5223 }
5224
5225 fn render_code_actions_indicator(
5226 &self,
5227 _style: &EditorStyle,
5228 row: DisplayRow,
5229 is_active: bool,
5230 cx: &mut ViewContext<Self>,
5231 ) -> Option<IconButton> {
5232 if self.available_code_actions.is_some() {
5233 Some(
5234 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5235 .shape(ui::IconButtonShape::Square)
5236 .icon_size(IconSize::XSmall)
5237 .icon_color(Color::Muted)
5238 .selected(is_active)
5239 .on_click(cx.listener(move |editor, _e, cx| {
5240 editor.focus(cx);
5241 editor.toggle_code_actions(
5242 &ToggleCodeActions {
5243 deployed_from_indicator: Some(row),
5244 },
5245 cx,
5246 );
5247 })),
5248 )
5249 } else {
5250 None
5251 }
5252 }
5253
5254 fn clear_tasks(&mut self) {
5255 self.tasks.clear()
5256 }
5257
5258 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5259 if let Some(_) = self.tasks.insert(key, value) {
5260 // This case should hopefully be rare, but just in case...
5261 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5262 }
5263 }
5264
5265 fn render_run_indicator(
5266 &self,
5267 _style: &EditorStyle,
5268 is_active: bool,
5269 row: DisplayRow,
5270 cx: &mut ViewContext<Self>,
5271 ) -> IconButton {
5272 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5273 .shape(ui::IconButtonShape::Square)
5274 .icon_size(IconSize::XSmall)
5275 .icon_color(Color::Muted)
5276 .selected(is_active)
5277 .on_click(cx.listener(move |editor, _e, cx| {
5278 editor.focus(cx);
5279 editor.toggle_code_actions(
5280 &ToggleCodeActions {
5281 deployed_from_indicator: Some(row),
5282 },
5283 cx,
5284 );
5285 }))
5286 }
5287
5288 fn close_hunk_diff_button(
5289 &self,
5290 hunk: HoveredHunk,
5291 row: DisplayRow,
5292 cx: &mut ViewContext<Self>,
5293 ) -> IconButton {
5294 IconButton::new(
5295 ("close_hunk_diff_indicator", row.0 as usize),
5296 ui::IconName::Close,
5297 )
5298 .shape(ui::IconButtonShape::Square)
5299 .icon_size(IconSize::XSmall)
5300 .icon_color(Color::Muted)
5301 .tooltip(|cx| Tooltip::for_action("Close hunk diff", &ToggleHunkDiff, cx))
5302 .on_click(cx.listener(move |editor, _e, cx| editor.toggle_hovered_hunk(&hunk, cx)))
5303 }
5304
5305 pub fn context_menu_visible(&self) -> bool {
5306 self.context_menu
5307 .read()
5308 .as_ref()
5309 .map_or(false, |menu| menu.visible())
5310 }
5311
5312 fn render_context_menu(
5313 &self,
5314 cursor_position: DisplayPoint,
5315 style: &EditorStyle,
5316 max_height: Pixels,
5317 cx: &mut ViewContext<Editor>,
5318 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5319 self.context_menu.read().as_ref().map(|menu| {
5320 menu.render(
5321 cursor_position,
5322 style,
5323 max_height,
5324 self.workspace.as_ref().map(|(w, _)| w.clone()),
5325 cx,
5326 )
5327 })
5328 }
5329
5330 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5331 cx.notify();
5332 self.completion_tasks.clear();
5333 let context_menu = self.context_menu.write().take();
5334 if context_menu.is_some() {
5335 self.update_visible_inline_completion(cx);
5336 }
5337 context_menu
5338 }
5339
5340 pub fn insert_snippet(
5341 &mut self,
5342 insertion_ranges: &[Range<usize>],
5343 snippet: Snippet,
5344 cx: &mut ViewContext<Self>,
5345 ) -> Result<()> {
5346 struct Tabstop<T> {
5347 is_end_tabstop: bool,
5348 ranges: Vec<Range<T>>,
5349 }
5350
5351 let tabstops = self.buffer.update(cx, |buffer, cx| {
5352 let snippet_text: Arc<str> = snippet.text.clone().into();
5353 buffer.edit(
5354 insertion_ranges
5355 .iter()
5356 .cloned()
5357 .map(|range| (range, snippet_text.clone())),
5358 Some(AutoindentMode::EachLine),
5359 cx,
5360 );
5361
5362 let snapshot = &*buffer.read(cx);
5363 let snippet = &snippet;
5364 snippet
5365 .tabstops
5366 .iter()
5367 .map(|tabstop| {
5368 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5369 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5370 });
5371 let mut tabstop_ranges = tabstop
5372 .iter()
5373 .flat_map(|tabstop_range| {
5374 let mut delta = 0_isize;
5375 insertion_ranges.iter().map(move |insertion_range| {
5376 let insertion_start = insertion_range.start as isize + delta;
5377 delta +=
5378 snippet.text.len() as isize - insertion_range.len() as isize;
5379
5380 let start = ((insertion_start + tabstop_range.start) as usize)
5381 .min(snapshot.len());
5382 let end = ((insertion_start + tabstop_range.end) as usize)
5383 .min(snapshot.len());
5384 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5385 })
5386 })
5387 .collect::<Vec<_>>();
5388 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5389
5390 Tabstop {
5391 is_end_tabstop,
5392 ranges: tabstop_ranges,
5393 }
5394 })
5395 .collect::<Vec<_>>()
5396 });
5397 if let Some(tabstop) = tabstops.first() {
5398 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5399 s.select_ranges(tabstop.ranges.iter().cloned());
5400 });
5401
5402 // If we're already at the last tabstop and it's at the end of the snippet,
5403 // we're done, we don't need to keep the state around.
5404 if !tabstop.is_end_tabstop {
5405 let ranges = tabstops
5406 .into_iter()
5407 .map(|tabstop| tabstop.ranges)
5408 .collect::<Vec<_>>();
5409 self.snippet_stack.push(SnippetState {
5410 active_index: 0,
5411 ranges,
5412 });
5413 }
5414
5415 // Check whether the just-entered snippet ends with an auto-closable bracket.
5416 if self.autoclose_regions.is_empty() {
5417 let snapshot = self.buffer.read(cx).snapshot(cx);
5418 for selection in &mut self.selections.all::<Point>(cx) {
5419 let selection_head = selection.head();
5420 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5421 continue;
5422 };
5423
5424 let mut bracket_pair = None;
5425 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5426 let prev_chars = snapshot
5427 .reversed_chars_at(selection_head)
5428 .collect::<String>();
5429 for (pair, enabled) in scope.brackets() {
5430 if enabled
5431 && pair.close
5432 && prev_chars.starts_with(pair.start.as_str())
5433 && next_chars.starts_with(pair.end.as_str())
5434 {
5435 bracket_pair = Some(pair.clone());
5436 break;
5437 }
5438 }
5439 if let Some(pair) = bracket_pair {
5440 let start = snapshot.anchor_after(selection_head);
5441 let end = snapshot.anchor_after(selection_head);
5442 self.autoclose_regions.push(AutocloseRegion {
5443 selection_id: selection.id,
5444 range: start..end,
5445 pair,
5446 });
5447 }
5448 }
5449 }
5450 }
5451 Ok(())
5452 }
5453
5454 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5455 self.move_to_snippet_tabstop(Bias::Right, cx)
5456 }
5457
5458 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5459 self.move_to_snippet_tabstop(Bias::Left, cx)
5460 }
5461
5462 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5463 if let Some(mut snippet) = self.snippet_stack.pop() {
5464 match bias {
5465 Bias::Left => {
5466 if snippet.active_index > 0 {
5467 snippet.active_index -= 1;
5468 } else {
5469 self.snippet_stack.push(snippet);
5470 return false;
5471 }
5472 }
5473 Bias::Right => {
5474 if snippet.active_index + 1 < snippet.ranges.len() {
5475 snippet.active_index += 1;
5476 } else {
5477 self.snippet_stack.push(snippet);
5478 return false;
5479 }
5480 }
5481 }
5482 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5483 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5484 s.select_anchor_ranges(current_ranges.iter().cloned())
5485 });
5486 // If snippet state is not at the last tabstop, push it back on the stack
5487 if snippet.active_index + 1 < snippet.ranges.len() {
5488 self.snippet_stack.push(snippet);
5489 }
5490 return true;
5491 }
5492 }
5493
5494 false
5495 }
5496
5497 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5498 self.transact(cx, |this, cx| {
5499 this.select_all(&SelectAll, cx);
5500 this.insert("", cx);
5501 });
5502 }
5503
5504 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5505 self.transact(cx, |this, cx| {
5506 this.select_autoclose_pair(cx);
5507 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5508 if !this.linked_edit_ranges.is_empty() {
5509 let selections = this.selections.all::<MultiBufferPoint>(cx);
5510 let snapshot = this.buffer.read(cx).snapshot(cx);
5511
5512 for selection in selections.iter() {
5513 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5514 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5515 if selection_start.buffer_id != selection_end.buffer_id {
5516 continue;
5517 }
5518 if let Some(ranges) =
5519 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5520 {
5521 for (buffer, entries) in ranges {
5522 linked_ranges.entry(buffer).or_default().extend(entries);
5523 }
5524 }
5525 }
5526 }
5527
5528 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5529 if !this.selections.line_mode {
5530 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5531 for selection in &mut selections {
5532 if selection.is_empty() {
5533 let old_head = selection.head();
5534 let mut new_head =
5535 movement::left(&display_map, old_head.to_display_point(&display_map))
5536 .to_point(&display_map);
5537 if let Some((buffer, line_buffer_range)) = display_map
5538 .buffer_snapshot
5539 .buffer_line_for_row(MultiBufferRow(old_head.row))
5540 {
5541 let indent_size =
5542 buffer.indent_size_for_line(line_buffer_range.start.row);
5543 let indent_len = match indent_size.kind {
5544 IndentKind::Space => {
5545 buffer.settings_at(line_buffer_range.start, cx).tab_size
5546 }
5547 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5548 };
5549 if old_head.column <= indent_size.len && old_head.column > 0 {
5550 let indent_len = indent_len.get();
5551 new_head = cmp::min(
5552 new_head,
5553 MultiBufferPoint::new(
5554 old_head.row,
5555 ((old_head.column - 1) / indent_len) * indent_len,
5556 ),
5557 );
5558 }
5559 }
5560
5561 selection.set_head(new_head, SelectionGoal::None);
5562 }
5563 }
5564 }
5565
5566 this.signature_help_state.set_backspace_pressed(true);
5567 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5568 this.insert("", cx);
5569 let empty_str: Arc<str> = Arc::from("");
5570 for (buffer, edits) in linked_ranges {
5571 let snapshot = buffer.read(cx).snapshot();
5572 use text::ToPoint as TP;
5573
5574 let edits = edits
5575 .into_iter()
5576 .map(|range| {
5577 let end_point = TP::to_point(&range.end, &snapshot);
5578 let mut start_point = TP::to_point(&range.start, &snapshot);
5579
5580 if end_point == start_point {
5581 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5582 .saturating_sub(1);
5583 start_point = TP::to_point(&offset, &snapshot);
5584 };
5585
5586 (start_point..end_point, empty_str.clone())
5587 })
5588 .sorted_by_key(|(range, _)| range.start)
5589 .collect::<Vec<_>>();
5590 buffer.update(cx, |this, cx| {
5591 this.edit(edits, None, cx);
5592 })
5593 }
5594 this.refresh_inline_completion(true, false, cx);
5595 linked_editing_ranges::refresh_linked_ranges(this, cx);
5596 });
5597 }
5598
5599 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5600 self.transact(cx, |this, cx| {
5601 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5602 let line_mode = s.line_mode;
5603 s.move_with(|map, selection| {
5604 if selection.is_empty() && !line_mode {
5605 let cursor = movement::right(map, selection.head());
5606 selection.end = cursor;
5607 selection.reversed = true;
5608 selection.goal = SelectionGoal::None;
5609 }
5610 })
5611 });
5612 this.insert("", cx);
5613 this.refresh_inline_completion(true, false, cx);
5614 });
5615 }
5616
5617 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5618 if self.move_to_prev_snippet_tabstop(cx) {
5619 return;
5620 }
5621
5622 self.outdent(&Outdent, cx);
5623 }
5624
5625 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5626 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5627 return;
5628 }
5629
5630 let mut selections = self.selections.all_adjusted(cx);
5631 let buffer = self.buffer.read(cx);
5632 let snapshot = buffer.snapshot(cx);
5633 let rows_iter = selections.iter().map(|s| s.head().row);
5634 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5635
5636 let mut edits = Vec::new();
5637 let mut prev_edited_row = 0;
5638 let mut row_delta = 0;
5639 for selection in &mut selections {
5640 if selection.start.row != prev_edited_row {
5641 row_delta = 0;
5642 }
5643 prev_edited_row = selection.end.row;
5644
5645 // If the selection is non-empty, then increase the indentation of the selected lines.
5646 if !selection.is_empty() {
5647 row_delta =
5648 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5649 continue;
5650 }
5651
5652 // If the selection is empty and the cursor is in the leading whitespace before the
5653 // suggested indentation, then auto-indent the line.
5654 let cursor = selection.head();
5655 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5656 if let Some(suggested_indent) =
5657 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5658 {
5659 if cursor.column < suggested_indent.len
5660 && cursor.column <= current_indent.len
5661 && current_indent.len <= suggested_indent.len
5662 {
5663 selection.start = Point::new(cursor.row, suggested_indent.len);
5664 selection.end = selection.start;
5665 if row_delta == 0 {
5666 edits.extend(Buffer::edit_for_indent_size_adjustment(
5667 cursor.row,
5668 current_indent,
5669 suggested_indent,
5670 ));
5671 row_delta = suggested_indent.len - current_indent.len;
5672 }
5673 continue;
5674 }
5675 }
5676
5677 // Otherwise, insert a hard or soft tab.
5678 let settings = buffer.settings_at(cursor, cx);
5679 let tab_size = if settings.hard_tabs {
5680 IndentSize::tab()
5681 } else {
5682 let tab_size = settings.tab_size.get();
5683 let char_column = snapshot
5684 .text_for_range(Point::new(cursor.row, 0)..cursor)
5685 .flat_map(str::chars)
5686 .count()
5687 + row_delta as usize;
5688 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5689 IndentSize::spaces(chars_to_next_tab_stop)
5690 };
5691 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5692 selection.end = selection.start;
5693 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5694 row_delta += tab_size.len;
5695 }
5696
5697 self.transact(cx, |this, cx| {
5698 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5699 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5700 this.refresh_inline_completion(true, false, cx);
5701 });
5702 }
5703
5704 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5705 if self.read_only(cx) {
5706 return;
5707 }
5708 let mut selections = self.selections.all::<Point>(cx);
5709 let mut prev_edited_row = 0;
5710 let mut row_delta = 0;
5711 let mut edits = Vec::new();
5712 let buffer = self.buffer.read(cx);
5713 let snapshot = buffer.snapshot(cx);
5714 for selection in &mut selections {
5715 if selection.start.row != prev_edited_row {
5716 row_delta = 0;
5717 }
5718 prev_edited_row = selection.end.row;
5719
5720 row_delta =
5721 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5722 }
5723
5724 self.transact(cx, |this, cx| {
5725 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5726 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5727 });
5728 }
5729
5730 fn indent_selection(
5731 buffer: &MultiBuffer,
5732 snapshot: &MultiBufferSnapshot,
5733 selection: &mut Selection<Point>,
5734 edits: &mut Vec<(Range<Point>, String)>,
5735 delta_for_start_row: u32,
5736 cx: &AppContext,
5737 ) -> u32 {
5738 let settings = buffer.settings_at(selection.start, cx);
5739 let tab_size = settings.tab_size.get();
5740 let indent_kind = if settings.hard_tabs {
5741 IndentKind::Tab
5742 } else {
5743 IndentKind::Space
5744 };
5745 let mut start_row = selection.start.row;
5746 let mut end_row = selection.end.row + 1;
5747
5748 // If a selection ends at the beginning of a line, don't indent
5749 // that last line.
5750 if selection.end.column == 0 && selection.end.row > selection.start.row {
5751 end_row -= 1;
5752 }
5753
5754 // Avoid re-indenting a row that has already been indented by a
5755 // previous selection, but still update this selection's column
5756 // to reflect that indentation.
5757 if delta_for_start_row > 0 {
5758 start_row += 1;
5759 selection.start.column += delta_for_start_row;
5760 if selection.end.row == selection.start.row {
5761 selection.end.column += delta_for_start_row;
5762 }
5763 }
5764
5765 let mut delta_for_end_row = 0;
5766 let has_multiple_rows = start_row + 1 != end_row;
5767 for row in start_row..end_row {
5768 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5769 let indent_delta = match (current_indent.kind, indent_kind) {
5770 (IndentKind::Space, IndentKind::Space) => {
5771 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5772 IndentSize::spaces(columns_to_next_tab_stop)
5773 }
5774 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5775 (_, IndentKind::Tab) => IndentSize::tab(),
5776 };
5777
5778 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5779 0
5780 } else {
5781 selection.start.column
5782 };
5783 let row_start = Point::new(row, start);
5784 edits.push((
5785 row_start..row_start,
5786 indent_delta.chars().collect::<String>(),
5787 ));
5788
5789 // Update this selection's endpoints to reflect the indentation.
5790 if row == selection.start.row {
5791 selection.start.column += indent_delta.len;
5792 }
5793 if row == selection.end.row {
5794 selection.end.column += indent_delta.len;
5795 delta_for_end_row = indent_delta.len;
5796 }
5797 }
5798
5799 if selection.start.row == selection.end.row {
5800 delta_for_start_row + delta_for_end_row
5801 } else {
5802 delta_for_end_row
5803 }
5804 }
5805
5806 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5807 if self.read_only(cx) {
5808 return;
5809 }
5810 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5811 let selections = self.selections.all::<Point>(cx);
5812 let mut deletion_ranges = Vec::new();
5813 let mut last_outdent = None;
5814 {
5815 let buffer = self.buffer.read(cx);
5816 let snapshot = buffer.snapshot(cx);
5817 for selection in &selections {
5818 let settings = buffer.settings_at(selection.start, cx);
5819 let tab_size = settings.tab_size.get();
5820 let mut rows = selection.spanned_rows(false, &display_map);
5821
5822 // Avoid re-outdenting a row that has already been outdented by a
5823 // previous selection.
5824 if let Some(last_row) = last_outdent {
5825 if last_row == rows.start {
5826 rows.start = rows.start.next_row();
5827 }
5828 }
5829 let has_multiple_rows = rows.len() > 1;
5830 for row in rows.iter_rows() {
5831 let indent_size = snapshot.indent_size_for_line(row);
5832 if indent_size.len > 0 {
5833 let deletion_len = match indent_size.kind {
5834 IndentKind::Space => {
5835 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5836 if columns_to_prev_tab_stop == 0 {
5837 tab_size
5838 } else {
5839 columns_to_prev_tab_stop
5840 }
5841 }
5842 IndentKind::Tab => 1,
5843 };
5844 let start = if has_multiple_rows
5845 || deletion_len > selection.start.column
5846 || indent_size.len < selection.start.column
5847 {
5848 0
5849 } else {
5850 selection.start.column - deletion_len
5851 };
5852 deletion_ranges.push(
5853 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5854 );
5855 last_outdent = Some(row);
5856 }
5857 }
5858 }
5859 }
5860
5861 self.transact(cx, |this, cx| {
5862 this.buffer.update(cx, |buffer, cx| {
5863 let empty_str: Arc<str> = Arc::default();
5864 buffer.edit(
5865 deletion_ranges
5866 .into_iter()
5867 .map(|range| (range, empty_str.clone())),
5868 None,
5869 cx,
5870 );
5871 });
5872 let selections = this.selections.all::<usize>(cx);
5873 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5874 });
5875 }
5876
5877 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5878 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5879 let selections = self.selections.all::<Point>(cx);
5880
5881 let mut new_cursors = Vec::new();
5882 let mut edit_ranges = Vec::new();
5883 let mut selections = selections.iter().peekable();
5884 while let Some(selection) = selections.next() {
5885 let mut rows = selection.spanned_rows(false, &display_map);
5886 let goal_display_column = selection.head().to_display_point(&display_map).column();
5887
5888 // Accumulate contiguous regions of rows that we want to delete.
5889 while let Some(next_selection) = selections.peek() {
5890 let next_rows = next_selection.spanned_rows(false, &display_map);
5891 if next_rows.start <= rows.end {
5892 rows.end = next_rows.end;
5893 selections.next().unwrap();
5894 } else {
5895 break;
5896 }
5897 }
5898
5899 let buffer = &display_map.buffer_snapshot;
5900 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5901 let edit_end;
5902 let cursor_buffer_row;
5903 if buffer.max_point().row >= rows.end.0 {
5904 // If there's a line after the range, delete the \n from the end of the row range
5905 // and position the cursor on the next line.
5906 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5907 cursor_buffer_row = rows.end;
5908 } else {
5909 // If there isn't a line after the range, delete the \n from the line before the
5910 // start of the row range and position the cursor there.
5911 edit_start = edit_start.saturating_sub(1);
5912 edit_end = buffer.len();
5913 cursor_buffer_row = rows.start.previous_row();
5914 }
5915
5916 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5917 *cursor.column_mut() =
5918 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5919
5920 new_cursors.push((
5921 selection.id,
5922 buffer.anchor_after(cursor.to_point(&display_map)),
5923 ));
5924 edit_ranges.push(edit_start..edit_end);
5925 }
5926
5927 self.transact(cx, |this, cx| {
5928 let buffer = this.buffer.update(cx, |buffer, cx| {
5929 let empty_str: Arc<str> = Arc::default();
5930 buffer.edit(
5931 edit_ranges
5932 .into_iter()
5933 .map(|range| (range, empty_str.clone())),
5934 None,
5935 cx,
5936 );
5937 buffer.snapshot(cx)
5938 });
5939 let new_selections = new_cursors
5940 .into_iter()
5941 .map(|(id, cursor)| {
5942 let cursor = cursor.to_point(&buffer);
5943 Selection {
5944 id,
5945 start: cursor,
5946 end: cursor,
5947 reversed: false,
5948 goal: SelectionGoal::None,
5949 }
5950 })
5951 .collect();
5952
5953 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5954 s.select(new_selections);
5955 });
5956 });
5957 }
5958
5959 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5960 if self.read_only(cx) {
5961 return;
5962 }
5963 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5964 for selection in self.selections.all::<Point>(cx) {
5965 let start = MultiBufferRow(selection.start.row);
5966 let end = if selection.start.row == selection.end.row {
5967 MultiBufferRow(selection.start.row + 1)
5968 } else {
5969 MultiBufferRow(selection.end.row)
5970 };
5971
5972 if let Some(last_row_range) = row_ranges.last_mut() {
5973 if start <= last_row_range.end {
5974 last_row_range.end = end;
5975 continue;
5976 }
5977 }
5978 row_ranges.push(start..end);
5979 }
5980
5981 let snapshot = self.buffer.read(cx).snapshot(cx);
5982 let mut cursor_positions = Vec::new();
5983 for row_range in &row_ranges {
5984 let anchor = snapshot.anchor_before(Point::new(
5985 row_range.end.previous_row().0,
5986 snapshot.line_len(row_range.end.previous_row()),
5987 ));
5988 cursor_positions.push(anchor..anchor);
5989 }
5990
5991 self.transact(cx, |this, cx| {
5992 for row_range in row_ranges.into_iter().rev() {
5993 for row in row_range.iter_rows().rev() {
5994 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5995 let next_line_row = row.next_row();
5996 let indent = snapshot.indent_size_for_line(next_line_row);
5997 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5998
5999 let replace = if snapshot.line_len(next_line_row) > indent.len {
6000 " "
6001 } else {
6002 ""
6003 };
6004
6005 this.buffer.update(cx, |buffer, cx| {
6006 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6007 });
6008 }
6009 }
6010
6011 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6012 s.select_anchor_ranges(cursor_positions)
6013 });
6014 });
6015 }
6016
6017 pub fn sort_lines_case_sensitive(
6018 &mut self,
6019 _: &SortLinesCaseSensitive,
6020 cx: &mut ViewContext<Self>,
6021 ) {
6022 self.manipulate_lines(cx, |lines| lines.sort())
6023 }
6024
6025 pub fn sort_lines_case_insensitive(
6026 &mut self,
6027 _: &SortLinesCaseInsensitive,
6028 cx: &mut ViewContext<Self>,
6029 ) {
6030 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6031 }
6032
6033 pub fn unique_lines_case_insensitive(
6034 &mut self,
6035 _: &UniqueLinesCaseInsensitive,
6036 cx: &mut ViewContext<Self>,
6037 ) {
6038 self.manipulate_lines(cx, |lines| {
6039 let mut seen = HashSet::default();
6040 lines.retain(|line| seen.insert(line.to_lowercase()));
6041 })
6042 }
6043
6044 pub fn unique_lines_case_sensitive(
6045 &mut self,
6046 _: &UniqueLinesCaseSensitive,
6047 cx: &mut ViewContext<Self>,
6048 ) {
6049 self.manipulate_lines(cx, |lines| {
6050 let mut seen = HashSet::default();
6051 lines.retain(|line| seen.insert(*line));
6052 })
6053 }
6054
6055 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6056 let mut revert_changes = HashMap::default();
6057 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6058 for hunk in hunks_for_rows(
6059 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6060 &multi_buffer_snapshot,
6061 ) {
6062 Self::prepare_revert_change(&mut revert_changes, &self.buffer(), &hunk, cx);
6063 }
6064 if !revert_changes.is_empty() {
6065 self.transact(cx, |editor, cx| {
6066 editor.revert(revert_changes, cx);
6067 });
6068 }
6069 }
6070
6071 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6072 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6073 if !revert_changes.is_empty() {
6074 self.transact(cx, |editor, cx| {
6075 editor.revert(revert_changes, cx);
6076 });
6077 }
6078 }
6079
6080 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6081 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6082 let project_path = buffer.read(cx).project_path(cx)?;
6083 let project = self.project.as_ref()?.read(cx);
6084 let entry = project.entry_for_path(&project_path, cx)?;
6085 let abs_path = project.absolute_path(&project_path, cx)?;
6086 let parent = if entry.is_symlink {
6087 abs_path.canonicalize().ok()?
6088 } else {
6089 abs_path
6090 }
6091 .parent()?
6092 .to_path_buf();
6093 Some(parent)
6094 }) {
6095 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6096 }
6097 }
6098
6099 fn gather_revert_changes(
6100 &mut self,
6101 selections: &[Selection<Anchor>],
6102 cx: &mut ViewContext<'_, Editor>,
6103 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6104 let mut revert_changes = HashMap::default();
6105 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6106 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6107 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6108 }
6109 revert_changes
6110 }
6111
6112 pub fn prepare_revert_change(
6113 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6114 multi_buffer: &Model<MultiBuffer>,
6115 hunk: &DiffHunk<MultiBufferRow>,
6116 cx: &AppContext,
6117 ) -> Option<()> {
6118 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6119 let buffer = buffer.read(cx);
6120 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6121 let buffer_snapshot = buffer.snapshot();
6122 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6123 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6124 probe
6125 .0
6126 .start
6127 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6128 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6129 }) {
6130 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6131 Some(())
6132 } else {
6133 None
6134 }
6135 }
6136
6137 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6138 self.manipulate_lines(cx, |lines| lines.reverse())
6139 }
6140
6141 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6142 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6143 }
6144
6145 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6146 where
6147 Fn: FnMut(&mut Vec<&str>),
6148 {
6149 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6150 let buffer = self.buffer.read(cx).snapshot(cx);
6151
6152 let mut edits = Vec::new();
6153
6154 let selections = self.selections.all::<Point>(cx);
6155 let mut selections = selections.iter().peekable();
6156 let mut contiguous_row_selections = Vec::new();
6157 let mut new_selections = Vec::new();
6158 let mut added_lines = 0;
6159 let mut removed_lines = 0;
6160
6161 while let Some(selection) = selections.next() {
6162 let (start_row, end_row) = consume_contiguous_rows(
6163 &mut contiguous_row_selections,
6164 selection,
6165 &display_map,
6166 &mut selections,
6167 );
6168
6169 let start_point = Point::new(start_row.0, 0);
6170 let end_point = Point::new(
6171 end_row.previous_row().0,
6172 buffer.line_len(end_row.previous_row()),
6173 );
6174 let text = buffer
6175 .text_for_range(start_point..end_point)
6176 .collect::<String>();
6177
6178 let mut lines = text.split('\n').collect_vec();
6179
6180 let lines_before = lines.len();
6181 callback(&mut lines);
6182 let lines_after = lines.len();
6183
6184 edits.push((start_point..end_point, lines.join("\n")));
6185
6186 // Selections must change based on added and removed line count
6187 let start_row =
6188 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6189 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6190 new_selections.push(Selection {
6191 id: selection.id,
6192 start: start_row,
6193 end: end_row,
6194 goal: SelectionGoal::None,
6195 reversed: selection.reversed,
6196 });
6197
6198 if lines_after > lines_before {
6199 added_lines += lines_after - lines_before;
6200 } else if lines_before > lines_after {
6201 removed_lines += lines_before - lines_after;
6202 }
6203 }
6204
6205 self.transact(cx, |this, cx| {
6206 let buffer = this.buffer.update(cx, |buffer, cx| {
6207 buffer.edit(edits, None, cx);
6208 buffer.snapshot(cx)
6209 });
6210
6211 // Recalculate offsets on newly edited buffer
6212 let new_selections = new_selections
6213 .iter()
6214 .map(|s| {
6215 let start_point = Point::new(s.start.0, 0);
6216 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6217 Selection {
6218 id: s.id,
6219 start: buffer.point_to_offset(start_point),
6220 end: buffer.point_to_offset(end_point),
6221 goal: s.goal,
6222 reversed: s.reversed,
6223 }
6224 })
6225 .collect();
6226
6227 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6228 s.select(new_selections);
6229 });
6230
6231 this.request_autoscroll(Autoscroll::fit(), cx);
6232 });
6233 }
6234
6235 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6236 self.manipulate_text(cx, |text| text.to_uppercase())
6237 }
6238
6239 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6240 self.manipulate_text(cx, |text| text.to_lowercase())
6241 }
6242
6243 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6244 self.manipulate_text(cx, |text| {
6245 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6246 // https://github.com/rutrum/convert-case/issues/16
6247 text.split('\n')
6248 .map(|line| line.to_case(Case::Title))
6249 .join("\n")
6250 })
6251 }
6252
6253 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6254 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6255 }
6256
6257 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6258 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6259 }
6260
6261 pub fn convert_to_upper_camel_case(
6262 &mut self,
6263 _: &ConvertToUpperCamelCase,
6264 cx: &mut ViewContext<Self>,
6265 ) {
6266 self.manipulate_text(cx, |text| {
6267 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6268 // https://github.com/rutrum/convert-case/issues/16
6269 text.split('\n')
6270 .map(|line| line.to_case(Case::UpperCamel))
6271 .join("\n")
6272 })
6273 }
6274
6275 pub fn convert_to_lower_camel_case(
6276 &mut self,
6277 _: &ConvertToLowerCamelCase,
6278 cx: &mut ViewContext<Self>,
6279 ) {
6280 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6281 }
6282
6283 pub fn convert_to_opposite_case(
6284 &mut self,
6285 _: &ConvertToOppositeCase,
6286 cx: &mut ViewContext<Self>,
6287 ) {
6288 self.manipulate_text(cx, |text| {
6289 text.chars()
6290 .fold(String::with_capacity(text.len()), |mut t, c| {
6291 if c.is_uppercase() {
6292 t.extend(c.to_lowercase());
6293 } else {
6294 t.extend(c.to_uppercase());
6295 }
6296 t
6297 })
6298 })
6299 }
6300
6301 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6302 where
6303 Fn: FnMut(&str) -> String,
6304 {
6305 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6306 let buffer = self.buffer.read(cx).snapshot(cx);
6307
6308 let mut new_selections = Vec::new();
6309 let mut edits = Vec::new();
6310 let mut selection_adjustment = 0i32;
6311
6312 for selection in self.selections.all::<usize>(cx) {
6313 let selection_is_empty = selection.is_empty();
6314
6315 let (start, end) = if selection_is_empty {
6316 let word_range = movement::surrounding_word(
6317 &display_map,
6318 selection.start.to_display_point(&display_map),
6319 );
6320 let start = word_range.start.to_offset(&display_map, Bias::Left);
6321 let end = word_range.end.to_offset(&display_map, Bias::Left);
6322 (start, end)
6323 } else {
6324 (selection.start, selection.end)
6325 };
6326
6327 let text = buffer.text_for_range(start..end).collect::<String>();
6328 let old_length = text.len() as i32;
6329 let text = callback(&text);
6330
6331 new_selections.push(Selection {
6332 start: (start as i32 - selection_adjustment) as usize,
6333 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6334 goal: SelectionGoal::None,
6335 ..selection
6336 });
6337
6338 selection_adjustment += old_length - text.len() as i32;
6339
6340 edits.push((start..end, text));
6341 }
6342
6343 self.transact(cx, |this, cx| {
6344 this.buffer.update(cx, |buffer, cx| {
6345 buffer.edit(edits, None, cx);
6346 });
6347
6348 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6349 s.select(new_selections);
6350 });
6351
6352 this.request_autoscroll(Autoscroll::fit(), cx);
6353 });
6354 }
6355
6356 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6357 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6358 let buffer = &display_map.buffer_snapshot;
6359 let selections = self.selections.all::<Point>(cx);
6360
6361 let mut edits = Vec::new();
6362 let mut selections_iter = selections.iter().peekable();
6363 while let Some(selection) = selections_iter.next() {
6364 // Avoid duplicating the same lines twice.
6365 let mut rows = selection.spanned_rows(false, &display_map);
6366
6367 while let Some(next_selection) = selections_iter.peek() {
6368 let next_rows = next_selection.spanned_rows(false, &display_map);
6369 if next_rows.start < rows.end {
6370 rows.end = next_rows.end;
6371 selections_iter.next().unwrap();
6372 } else {
6373 break;
6374 }
6375 }
6376
6377 // Copy the text from the selected row region and splice it either at the start
6378 // or end of the region.
6379 let start = Point::new(rows.start.0, 0);
6380 let end = Point::new(
6381 rows.end.previous_row().0,
6382 buffer.line_len(rows.end.previous_row()),
6383 );
6384 let text = buffer
6385 .text_for_range(start..end)
6386 .chain(Some("\n"))
6387 .collect::<String>();
6388 let insert_location = if upwards {
6389 Point::new(rows.end.0, 0)
6390 } else {
6391 start
6392 };
6393 edits.push((insert_location..insert_location, text));
6394 }
6395
6396 self.transact(cx, |this, cx| {
6397 this.buffer.update(cx, |buffer, cx| {
6398 buffer.edit(edits, None, cx);
6399 });
6400
6401 this.request_autoscroll(Autoscroll::fit(), cx);
6402 });
6403 }
6404
6405 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6406 self.duplicate_line(true, cx);
6407 }
6408
6409 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6410 self.duplicate_line(false, cx);
6411 }
6412
6413 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6414 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6415 let buffer = self.buffer.read(cx).snapshot(cx);
6416
6417 let mut edits = Vec::new();
6418 let mut unfold_ranges = Vec::new();
6419 let mut refold_ranges = Vec::new();
6420
6421 let selections = self.selections.all::<Point>(cx);
6422 let mut selections = selections.iter().peekable();
6423 let mut contiguous_row_selections = Vec::new();
6424 let mut new_selections = Vec::new();
6425
6426 while let Some(selection) = selections.next() {
6427 // Find all the selections that span a contiguous row range
6428 let (start_row, end_row) = consume_contiguous_rows(
6429 &mut contiguous_row_selections,
6430 selection,
6431 &display_map,
6432 &mut selections,
6433 );
6434
6435 // Move the text spanned by the row range to be before the line preceding the row range
6436 if start_row.0 > 0 {
6437 let range_to_move = Point::new(
6438 start_row.previous_row().0,
6439 buffer.line_len(start_row.previous_row()),
6440 )
6441 ..Point::new(
6442 end_row.previous_row().0,
6443 buffer.line_len(end_row.previous_row()),
6444 );
6445 let insertion_point = display_map
6446 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6447 .0;
6448
6449 // Don't move lines across excerpts
6450 if buffer
6451 .excerpt_boundaries_in_range((
6452 Bound::Excluded(insertion_point),
6453 Bound::Included(range_to_move.end),
6454 ))
6455 .next()
6456 .is_none()
6457 {
6458 let text = buffer
6459 .text_for_range(range_to_move.clone())
6460 .flat_map(|s| s.chars())
6461 .skip(1)
6462 .chain(['\n'])
6463 .collect::<String>();
6464
6465 edits.push((
6466 buffer.anchor_after(range_to_move.start)
6467 ..buffer.anchor_before(range_to_move.end),
6468 String::new(),
6469 ));
6470 let insertion_anchor = buffer.anchor_after(insertion_point);
6471 edits.push((insertion_anchor..insertion_anchor, text));
6472
6473 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6474
6475 // Move selections up
6476 new_selections.extend(contiguous_row_selections.drain(..).map(
6477 |mut selection| {
6478 selection.start.row -= row_delta;
6479 selection.end.row -= row_delta;
6480 selection
6481 },
6482 ));
6483
6484 // Move folds up
6485 unfold_ranges.push(range_to_move.clone());
6486 for fold in display_map.folds_in_range(
6487 buffer.anchor_before(range_to_move.start)
6488 ..buffer.anchor_after(range_to_move.end),
6489 ) {
6490 let mut start = fold.range.start.to_point(&buffer);
6491 let mut end = fold.range.end.to_point(&buffer);
6492 start.row -= row_delta;
6493 end.row -= row_delta;
6494 refold_ranges.push((start..end, fold.placeholder.clone()));
6495 }
6496 }
6497 }
6498
6499 // If we didn't move line(s), preserve the existing selections
6500 new_selections.append(&mut contiguous_row_selections);
6501 }
6502
6503 self.transact(cx, |this, cx| {
6504 this.unfold_ranges(unfold_ranges, true, true, cx);
6505 this.buffer.update(cx, |buffer, cx| {
6506 for (range, text) in edits {
6507 buffer.edit([(range, text)], None, cx);
6508 }
6509 });
6510 this.fold_ranges(refold_ranges, true, cx);
6511 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6512 s.select(new_selections);
6513 })
6514 });
6515 }
6516
6517 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6518 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6519 let buffer = self.buffer.read(cx).snapshot(cx);
6520
6521 let mut edits = Vec::new();
6522 let mut unfold_ranges = Vec::new();
6523 let mut refold_ranges = Vec::new();
6524
6525 let selections = self.selections.all::<Point>(cx);
6526 let mut selections = selections.iter().peekable();
6527 let mut contiguous_row_selections = Vec::new();
6528 let mut new_selections = Vec::new();
6529
6530 while let Some(selection) = selections.next() {
6531 // Find all the selections that span a contiguous row range
6532 let (start_row, end_row) = consume_contiguous_rows(
6533 &mut contiguous_row_selections,
6534 selection,
6535 &display_map,
6536 &mut selections,
6537 );
6538
6539 // Move the text spanned by the row range to be after the last line of the row range
6540 if end_row.0 <= buffer.max_point().row {
6541 let range_to_move =
6542 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6543 let insertion_point = display_map
6544 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6545 .0;
6546
6547 // Don't move lines across excerpt boundaries
6548 if buffer
6549 .excerpt_boundaries_in_range((
6550 Bound::Excluded(range_to_move.start),
6551 Bound::Included(insertion_point),
6552 ))
6553 .next()
6554 .is_none()
6555 {
6556 let mut text = String::from("\n");
6557 text.extend(buffer.text_for_range(range_to_move.clone()));
6558 text.pop(); // Drop trailing newline
6559 edits.push((
6560 buffer.anchor_after(range_to_move.start)
6561 ..buffer.anchor_before(range_to_move.end),
6562 String::new(),
6563 ));
6564 let insertion_anchor = buffer.anchor_after(insertion_point);
6565 edits.push((insertion_anchor..insertion_anchor, text));
6566
6567 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6568
6569 // Move selections down
6570 new_selections.extend(contiguous_row_selections.drain(..).map(
6571 |mut selection| {
6572 selection.start.row += row_delta;
6573 selection.end.row += row_delta;
6574 selection
6575 },
6576 ));
6577
6578 // Move folds down
6579 unfold_ranges.push(range_to_move.clone());
6580 for fold in display_map.folds_in_range(
6581 buffer.anchor_before(range_to_move.start)
6582 ..buffer.anchor_after(range_to_move.end),
6583 ) {
6584 let mut start = fold.range.start.to_point(&buffer);
6585 let mut end = fold.range.end.to_point(&buffer);
6586 start.row += row_delta;
6587 end.row += row_delta;
6588 refold_ranges.push((start..end, fold.placeholder.clone()));
6589 }
6590 }
6591 }
6592
6593 // If we didn't move line(s), preserve the existing selections
6594 new_selections.append(&mut contiguous_row_selections);
6595 }
6596
6597 self.transact(cx, |this, cx| {
6598 this.unfold_ranges(unfold_ranges, true, true, cx);
6599 this.buffer.update(cx, |buffer, cx| {
6600 for (range, text) in edits {
6601 buffer.edit([(range, text)], None, cx);
6602 }
6603 });
6604 this.fold_ranges(refold_ranges, true, cx);
6605 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6606 });
6607 }
6608
6609 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6610 let text_layout_details = &self.text_layout_details(cx);
6611 self.transact(cx, |this, cx| {
6612 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6613 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6614 let line_mode = s.line_mode;
6615 s.move_with(|display_map, selection| {
6616 if !selection.is_empty() || line_mode {
6617 return;
6618 }
6619
6620 let mut head = selection.head();
6621 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6622 if head.column() == display_map.line_len(head.row()) {
6623 transpose_offset = display_map
6624 .buffer_snapshot
6625 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6626 }
6627
6628 if transpose_offset == 0 {
6629 return;
6630 }
6631
6632 *head.column_mut() += 1;
6633 head = display_map.clip_point(head, Bias::Right);
6634 let goal = SelectionGoal::HorizontalPosition(
6635 display_map
6636 .x_for_display_point(head, &text_layout_details)
6637 .into(),
6638 );
6639 selection.collapse_to(head, goal);
6640
6641 let transpose_start = display_map
6642 .buffer_snapshot
6643 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6644 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6645 let transpose_end = display_map
6646 .buffer_snapshot
6647 .clip_offset(transpose_offset + 1, Bias::Right);
6648 if let Some(ch) =
6649 display_map.buffer_snapshot.chars_at(transpose_start).next()
6650 {
6651 edits.push((transpose_start..transpose_offset, String::new()));
6652 edits.push((transpose_end..transpose_end, ch.to_string()));
6653 }
6654 }
6655 });
6656 edits
6657 });
6658 this.buffer
6659 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6660 let selections = this.selections.all::<usize>(cx);
6661 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6662 s.select(selections);
6663 });
6664 });
6665 }
6666
6667 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6668 let mut text = String::new();
6669 let buffer = self.buffer.read(cx).snapshot(cx);
6670 let mut selections = self.selections.all::<Point>(cx);
6671 let mut clipboard_selections = Vec::with_capacity(selections.len());
6672 {
6673 let max_point = buffer.max_point();
6674 let mut is_first = true;
6675 for selection in &mut selections {
6676 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6677 if is_entire_line {
6678 selection.start = Point::new(selection.start.row, 0);
6679 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6680 selection.goal = SelectionGoal::None;
6681 }
6682 if is_first {
6683 is_first = false;
6684 } else {
6685 text += "\n";
6686 }
6687 let mut len = 0;
6688 for chunk in buffer.text_for_range(selection.start..selection.end) {
6689 text.push_str(chunk);
6690 len += chunk.len();
6691 }
6692 clipboard_selections.push(ClipboardSelection {
6693 len,
6694 is_entire_line,
6695 first_line_indent: buffer
6696 .indent_size_for_line(MultiBufferRow(selection.start.row))
6697 .len,
6698 });
6699 }
6700 }
6701
6702 self.transact(cx, |this, cx| {
6703 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6704 s.select(selections);
6705 });
6706 this.insert("", cx);
6707 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6708 text,
6709 clipboard_selections,
6710 ));
6711 });
6712 }
6713
6714 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6715 let selections = self.selections.all::<Point>(cx);
6716 let buffer = self.buffer.read(cx).read(cx);
6717 let mut text = String::new();
6718
6719 let mut clipboard_selections = Vec::with_capacity(selections.len());
6720 {
6721 let max_point = buffer.max_point();
6722 let mut is_first = true;
6723 for selection in selections.iter() {
6724 let mut start = selection.start;
6725 let mut end = selection.end;
6726 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6727 if is_entire_line {
6728 start = Point::new(start.row, 0);
6729 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6730 }
6731 if is_first {
6732 is_first = false;
6733 } else {
6734 text += "\n";
6735 }
6736 let mut len = 0;
6737 for chunk in buffer.text_for_range(start..end) {
6738 text.push_str(chunk);
6739 len += chunk.len();
6740 }
6741 clipboard_selections.push(ClipboardSelection {
6742 len,
6743 is_entire_line,
6744 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6745 });
6746 }
6747 }
6748
6749 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6750 text,
6751 clipboard_selections,
6752 ));
6753 }
6754
6755 pub fn do_paste(
6756 &mut self,
6757 text: &String,
6758 clipboard_selections: Option<Vec<ClipboardSelection>>,
6759 handle_entire_lines: bool,
6760 cx: &mut ViewContext<Self>,
6761 ) {
6762 if self.read_only(cx) {
6763 return;
6764 }
6765
6766 let clipboard_text = Cow::Borrowed(text);
6767
6768 self.transact(cx, |this, cx| {
6769 if let Some(mut clipboard_selections) = clipboard_selections {
6770 let old_selections = this.selections.all::<usize>(cx);
6771 let all_selections_were_entire_line =
6772 clipboard_selections.iter().all(|s| s.is_entire_line);
6773 let first_selection_indent_column =
6774 clipboard_selections.first().map(|s| s.first_line_indent);
6775 if clipboard_selections.len() != old_selections.len() {
6776 clipboard_selections.drain(..);
6777 }
6778
6779 this.buffer.update(cx, |buffer, cx| {
6780 let snapshot = buffer.read(cx);
6781 let mut start_offset = 0;
6782 let mut edits = Vec::new();
6783 let mut original_indent_columns = Vec::new();
6784 for (ix, selection) in old_selections.iter().enumerate() {
6785 let to_insert;
6786 let entire_line;
6787 let original_indent_column;
6788 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6789 let end_offset = start_offset + clipboard_selection.len;
6790 to_insert = &clipboard_text[start_offset..end_offset];
6791 entire_line = clipboard_selection.is_entire_line;
6792 start_offset = end_offset + 1;
6793 original_indent_column = Some(clipboard_selection.first_line_indent);
6794 } else {
6795 to_insert = clipboard_text.as_str();
6796 entire_line = all_selections_were_entire_line;
6797 original_indent_column = first_selection_indent_column
6798 }
6799
6800 // If the corresponding selection was empty when this slice of the
6801 // clipboard text was written, then the entire line containing the
6802 // selection was copied. If this selection is also currently empty,
6803 // then paste the line before the current line of the buffer.
6804 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6805 let column = selection.start.to_point(&snapshot).column as usize;
6806 let line_start = selection.start - column;
6807 line_start..line_start
6808 } else {
6809 selection.range()
6810 };
6811
6812 edits.push((range, to_insert));
6813 original_indent_columns.extend(original_indent_column);
6814 }
6815 drop(snapshot);
6816
6817 buffer.edit(
6818 edits,
6819 Some(AutoindentMode::Block {
6820 original_indent_columns,
6821 }),
6822 cx,
6823 );
6824 });
6825
6826 let selections = this.selections.all::<usize>(cx);
6827 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6828 } else {
6829 this.insert(&clipboard_text, cx);
6830 }
6831 });
6832 }
6833
6834 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
6835 if let Some(item) = cx.read_from_clipboard() {
6836 let entries = item.entries();
6837
6838 match entries.first() {
6839 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
6840 // of all the pasted entries.
6841 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
6842 .do_paste(
6843 clipboard_string.text(),
6844 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
6845 true,
6846 cx,
6847 ),
6848 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
6849 }
6850 }
6851 }
6852
6853 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
6854 if self.read_only(cx) {
6855 return;
6856 }
6857
6858 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
6859 if let Some((selections, _)) =
6860 self.selection_history.transaction(transaction_id).cloned()
6861 {
6862 self.change_selections(None, cx, |s| {
6863 s.select_anchors(selections.to_vec());
6864 });
6865 }
6866 self.request_autoscroll(Autoscroll::fit(), cx);
6867 self.unmark_text(cx);
6868 self.refresh_inline_completion(true, false, cx);
6869 cx.emit(EditorEvent::Edited { transaction_id });
6870 cx.emit(EditorEvent::TransactionUndone { transaction_id });
6871 }
6872 }
6873
6874 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
6875 if self.read_only(cx) {
6876 return;
6877 }
6878
6879 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
6880 if let Some((_, Some(selections))) =
6881 self.selection_history.transaction(transaction_id).cloned()
6882 {
6883 self.change_selections(None, cx, |s| {
6884 s.select_anchors(selections.to_vec());
6885 });
6886 }
6887 self.request_autoscroll(Autoscroll::fit(), cx);
6888 self.unmark_text(cx);
6889 self.refresh_inline_completion(true, false, cx);
6890 cx.emit(EditorEvent::Edited { transaction_id });
6891 }
6892 }
6893
6894 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
6895 self.buffer
6896 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
6897 }
6898
6899 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
6900 self.buffer
6901 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
6902 }
6903
6904 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
6905 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6906 let line_mode = s.line_mode;
6907 s.move_with(|map, selection| {
6908 let cursor = if selection.is_empty() && !line_mode {
6909 movement::left(map, selection.start)
6910 } else {
6911 selection.start
6912 };
6913 selection.collapse_to(cursor, SelectionGoal::None);
6914 });
6915 })
6916 }
6917
6918 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
6919 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6920 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
6921 })
6922 }
6923
6924 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
6925 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6926 let line_mode = s.line_mode;
6927 s.move_with(|map, selection| {
6928 let cursor = if selection.is_empty() && !line_mode {
6929 movement::right(map, selection.end)
6930 } else {
6931 selection.end
6932 };
6933 selection.collapse_to(cursor, SelectionGoal::None)
6934 });
6935 })
6936 }
6937
6938 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
6939 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6940 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
6941 })
6942 }
6943
6944 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
6945 if self.take_rename(true, cx).is_some() {
6946 return;
6947 }
6948
6949 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6950 cx.propagate();
6951 return;
6952 }
6953
6954 let text_layout_details = &self.text_layout_details(cx);
6955 let selection_count = self.selections.count();
6956 let first_selection = self.selections.first_anchor();
6957
6958 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6959 let line_mode = s.line_mode;
6960 s.move_with(|map, selection| {
6961 if !selection.is_empty() && !line_mode {
6962 selection.goal = SelectionGoal::None;
6963 }
6964 let (cursor, goal) = movement::up(
6965 map,
6966 selection.start,
6967 selection.goal,
6968 false,
6969 &text_layout_details,
6970 );
6971 selection.collapse_to(cursor, goal);
6972 });
6973 });
6974
6975 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
6976 {
6977 cx.propagate();
6978 }
6979 }
6980
6981 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
6982 if self.take_rename(true, cx).is_some() {
6983 return;
6984 }
6985
6986 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6987 cx.propagate();
6988 return;
6989 }
6990
6991 let text_layout_details = &self.text_layout_details(cx);
6992
6993 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6994 let line_mode = s.line_mode;
6995 s.move_with(|map, selection| {
6996 if !selection.is_empty() && !line_mode {
6997 selection.goal = SelectionGoal::None;
6998 }
6999 let (cursor, goal) = movement::up_by_rows(
7000 map,
7001 selection.start,
7002 action.lines,
7003 selection.goal,
7004 false,
7005 &text_layout_details,
7006 );
7007 selection.collapse_to(cursor, goal);
7008 });
7009 })
7010 }
7011
7012 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7013 if self.take_rename(true, cx).is_some() {
7014 return;
7015 }
7016
7017 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7018 cx.propagate();
7019 return;
7020 }
7021
7022 let text_layout_details = &self.text_layout_details(cx);
7023
7024 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7025 let line_mode = s.line_mode;
7026 s.move_with(|map, selection| {
7027 if !selection.is_empty() && !line_mode {
7028 selection.goal = SelectionGoal::None;
7029 }
7030 let (cursor, goal) = movement::down_by_rows(
7031 map,
7032 selection.start,
7033 action.lines,
7034 selection.goal,
7035 false,
7036 &text_layout_details,
7037 );
7038 selection.collapse_to(cursor, goal);
7039 });
7040 })
7041 }
7042
7043 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7044 let text_layout_details = &self.text_layout_details(cx);
7045 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7046 s.move_heads_with(|map, head, goal| {
7047 movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
7048 })
7049 })
7050 }
7051
7052 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7053 let text_layout_details = &self.text_layout_details(cx);
7054 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7055 s.move_heads_with(|map, head, goal| {
7056 movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
7057 })
7058 })
7059 }
7060
7061 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7062 let Some(row_count) = self.visible_row_count() else {
7063 return;
7064 };
7065
7066 let text_layout_details = &self.text_layout_details(cx);
7067
7068 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7069 s.move_heads_with(|map, head, goal| {
7070 movement::up_by_rows(map, head, row_count, goal, false, &text_layout_details)
7071 })
7072 })
7073 }
7074
7075 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7076 if self.take_rename(true, cx).is_some() {
7077 return;
7078 }
7079
7080 if self
7081 .context_menu
7082 .write()
7083 .as_mut()
7084 .map(|menu| menu.select_first(self.project.as_ref(), cx))
7085 .unwrap_or(false)
7086 {
7087 return;
7088 }
7089
7090 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7091 cx.propagate();
7092 return;
7093 }
7094
7095 let Some(row_count) = self.visible_row_count() else {
7096 return;
7097 };
7098
7099 let autoscroll = if action.center_cursor {
7100 Autoscroll::center()
7101 } else {
7102 Autoscroll::fit()
7103 };
7104
7105 let text_layout_details = &self.text_layout_details(cx);
7106
7107 self.change_selections(Some(autoscroll), cx, |s| {
7108 let line_mode = s.line_mode;
7109 s.move_with(|map, selection| {
7110 if !selection.is_empty() && !line_mode {
7111 selection.goal = SelectionGoal::None;
7112 }
7113 let (cursor, goal) = movement::up_by_rows(
7114 map,
7115 selection.end,
7116 row_count,
7117 selection.goal,
7118 false,
7119 &text_layout_details,
7120 );
7121 selection.collapse_to(cursor, goal);
7122 });
7123 });
7124 }
7125
7126 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7127 let text_layout_details = &self.text_layout_details(cx);
7128 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7129 s.move_heads_with(|map, head, goal| {
7130 movement::up(map, head, goal, false, &text_layout_details)
7131 })
7132 })
7133 }
7134
7135 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7136 self.take_rename(true, cx);
7137
7138 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7139 cx.propagate();
7140 return;
7141 }
7142
7143 let text_layout_details = &self.text_layout_details(cx);
7144 let selection_count = self.selections.count();
7145 let first_selection = self.selections.first_anchor();
7146
7147 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7148 let line_mode = s.line_mode;
7149 s.move_with(|map, selection| {
7150 if !selection.is_empty() && !line_mode {
7151 selection.goal = SelectionGoal::None;
7152 }
7153 let (cursor, goal) = movement::down(
7154 map,
7155 selection.end,
7156 selection.goal,
7157 false,
7158 &text_layout_details,
7159 );
7160 selection.collapse_to(cursor, goal);
7161 });
7162 });
7163
7164 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7165 {
7166 cx.propagate();
7167 }
7168 }
7169
7170 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7171 let Some(row_count) = self.visible_row_count() else {
7172 return;
7173 };
7174
7175 let text_layout_details = &self.text_layout_details(cx);
7176
7177 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7178 s.move_heads_with(|map, head, goal| {
7179 movement::down_by_rows(map, head, row_count, goal, false, &text_layout_details)
7180 })
7181 })
7182 }
7183
7184 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7185 if self.take_rename(true, cx).is_some() {
7186 return;
7187 }
7188
7189 if self
7190 .context_menu
7191 .write()
7192 .as_mut()
7193 .map(|menu| menu.select_last(self.project.as_ref(), cx))
7194 .unwrap_or(false)
7195 {
7196 return;
7197 }
7198
7199 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7200 cx.propagate();
7201 return;
7202 }
7203
7204 let Some(row_count) = self.visible_row_count() else {
7205 return;
7206 };
7207
7208 let autoscroll = if action.center_cursor {
7209 Autoscroll::center()
7210 } else {
7211 Autoscroll::fit()
7212 };
7213
7214 let text_layout_details = &self.text_layout_details(cx);
7215 self.change_selections(Some(autoscroll), cx, |s| {
7216 let line_mode = s.line_mode;
7217 s.move_with(|map, selection| {
7218 if !selection.is_empty() && !line_mode {
7219 selection.goal = SelectionGoal::None;
7220 }
7221 let (cursor, goal) = movement::down_by_rows(
7222 map,
7223 selection.end,
7224 row_count,
7225 selection.goal,
7226 false,
7227 &text_layout_details,
7228 );
7229 selection.collapse_to(cursor, goal);
7230 });
7231 });
7232 }
7233
7234 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7235 let text_layout_details = &self.text_layout_details(cx);
7236 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7237 s.move_heads_with(|map, head, goal| {
7238 movement::down(map, head, goal, false, &text_layout_details)
7239 })
7240 });
7241 }
7242
7243 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7244 if let Some(context_menu) = self.context_menu.write().as_mut() {
7245 context_menu.select_first(self.project.as_ref(), cx);
7246 }
7247 }
7248
7249 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7250 if let Some(context_menu) = self.context_menu.write().as_mut() {
7251 context_menu.select_prev(self.project.as_ref(), cx);
7252 }
7253 }
7254
7255 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7256 if let Some(context_menu) = self.context_menu.write().as_mut() {
7257 context_menu.select_next(self.project.as_ref(), cx);
7258 }
7259 }
7260
7261 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7262 if let Some(context_menu) = self.context_menu.write().as_mut() {
7263 context_menu.select_last(self.project.as_ref(), cx);
7264 }
7265 }
7266
7267 pub fn move_to_previous_word_start(
7268 &mut self,
7269 _: &MoveToPreviousWordStart,
7270 cx: &mut ViewContext<Self>,
7271 ) {
7272 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7273 s.move_cursors_with(|map, head, _| {
7274 (
7275 movement::previous_word_start(map, head),
7276 SelectionGoal::None,
7277 )
7278 });
7279 })
7280 }
7281
7282 pub fn move_to_previous_subword_start(
7283 &mut self,
7284 _: &MoveToPreviousSubwordStart,
7285 cx: &mut ViewContext<Self>,
7286 ) {
7287 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7288 s.move_cursors_with(|map, head, _| {
7289 (
7290 movement::previous_subword_start(map, head),
7291 SelectionGoal::None,
7292 )
7293 });
7294 })
7295 }
7296
7297 pub fn select_to_previous_word_start(
7298 &mut self,
7299 _: &SelectToPreviousWordStart,
7300 cx: &mut ViewContext<Self>,
7301 ) {
7302 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7303 s.move_heads_with(|map, head, _| {
7304 (
7305 movement::previous_word_start(map, head),
7306 SelectionGoal::None,
7307 )
7308 });
7309 })
7310 }
7311
7312 pub fn select_to_previous_subword_start(
7313 &mut self,
7314 _: &SelectToPreviousSubwordStart,
7315 cx: &mut ViewContext<Self>,
7316 ) {
7317 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7318 s.move_heads_with(|map, head, _| {
7319 (
7320 movement::previous_subword_start(map, head),
7321 SelectionGoal::None,
7322 )
7323 });
7324 })
7325 }
7326
7327 pub fn delete_to_previous_word_start(
7328 &mut self,
7329 _: &DeleteToPreviousWordStart,
7330 cx: &mut ViewContext<Self>,
7331 ) {
7332 self.transact(cx, |this, cx| {
7333 this.select_autoclose_pair(cx);
7334 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7335 let line_mode = s.line_mode;
7336 s.move_with(|map, selection| {
7337 if selection.is_empty() && !line_mode {
7338 let cursor = movement::previous_word_start(map, selection.head());
7339 selection.set_head(cursor, SelectionGoal::None);
7340 }
7341 });
7342 });
7343 this.insert("", cx);
7344 });
7345 }
7346
7347 pub fn delete_to_previous_subword_start(
7348 &mut self,
7349 _: &DeleteToPreviousSubwordStart,
7350 cx: &mut ViewContext<Self>,
7351 ) {
7352 self.transact(cx, |this, cx| {
7353 this.select_autoclose_pair(cx);
7354 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7355 let line_mode = s.line_mode;
7356 s.move_with(|map, selection| {
7357 if selection.is_empty() && !line_mode {
7358 let cursor = movement::previous_subword_start(map, selection.head());
7359 selection.set_head(cursor, SelectionGoal::None);
7360 }
7361 });
7362 });
7363 this.insert("", cx);
7364 });
7365 }
7366
7367 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7368 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7369 s.move_cursors_with(|map, head, _| {
7370 (movement::next_word_end(map, head), SelectionGoal::None)
7371 });
7372 })
7373 }
7374
7375 pub fn move_to_next_subword_end(
7376 &mut self,
7377 _: &MoveToNextSubwordEnd,
7378 cx: &mut ViewContext<Self>,
7379 ) {
7380 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7381 s.move_cursors_with(|map, head, _| {
7382 (movement::next_subword_end(map, head), SelectionGoal::None)
7383 });
7384 })
7385 }
7386
7387 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7388 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7389 s.move_heads_with(|map, head, _| {
7390 (movement::next_word_end(map, head), SelectionGoal::None)
7391 });
7392 })
7393 }
7394
7395 pub fn select_to_next_subword_end(
7396 &mut self,
7397 _: &SelectToNextSubwordEnd,
7398 cx: &mut ViewContext<Self>,
7399 ) {
7400 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7401 s.move_heads_with(|map, head, _| {
7402 (movement::next_subword_end(map, head), SelectionGoal::None)
7403 });
7404 })
7405 }
7406
7407 pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
7408 self.transact(cx, |this, cx| {
7409 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7410 let line_mode = s.line_mode;
7411 s.move_with(|map, selection| {
7412 if selection.is_empty() && !line_mode {
7413 let cursor = movement::next_word_end(map, selection.head());
7414 selection.set_head(cursor, SelectionGoal::None);
7415 }
7416 });
7417 });
7418 this.insert("", cx);
7419 });
7420 }
7421
7422 pub fn delete_to_next_subword_end(
7423 &mut self,
7424 _: &DeleteToNextSubwordEnd,
7425 cx: &mut ViewContext<Self>,
7426 ) {
7427 self.transact(cx, |this, cx| {
7428 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7429 s.move_with(|map, selection| {
7430 if selection.is_empty() {
7431 let cursor = movement::next_subword_end(map, selection.head());
7432 selection.set_head(cursor, SelectionGoal::None);
7433 }
7434 });
7435 });
7436 this.insert("", cx);
7437 });
7438 }
7439
7440 pub fn move_to_beginning_of_line(
7441 &mut self,
7442 action: &MoveToBeginningOfLine,
7443 cx: &mut ViewContext<Self>,
7444 ) {
7445 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7446 s.move_cursors_with(|map, head, _| {
7447 (
7448 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7449 SelectionGoal::None,
7450 )
7451 });
7452 })
7453 }
7454
7455 pub fn select_to_beginning_of_line(
7456 &mut self,
7457 action: &SelectToBeginningOfLine,
7458 cx: &mut ViewContext<Self>,
7459 ) {
7460 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7461 s.move_heads_with(|map, head, _| {
7462 (
7463 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7464 SelectionGoal::None,
7465 )
7466 });
7467 });
7468 }
7469
7470 pub fn delete_to_beginning_of_line(
7471 &mut self,
7472 _: &DeleteToBeginningOfLine,
7473 cx: &mut ViewContext<Self>,
7474 ) {
7475 self.transact(cx, |this, cx| {
7476 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7477 s.move_with(|_, selection| {
7478 selection.reversed = true;
7479 });
7480 });
7481
7482 this.select_to_beginning_of_line(
7483 &SelectToBeginningOfLine {
7484 stop_at_soft_wraps: false,
7485 },
7486 cx,
7487 );
7488 this.backspace(&Backspace, cx);
7489 });
7490 }
7491
7492 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7493 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7494 s.move_cursors_with(|map, head, _| {
7495 (
7496 movement::line_end(map, head, action.stop_at_soft_wraps),
7497 SelectionGoal::None,
7498 )
7499 });
7500 })
7501 }
7502
7503 pub fn select_to_end_of_line(
7504 &mut self,
7505 action: &SelectToEndOfLine,
7506 cx: &mut ViewContext<Self>,
7507 ) {
7508 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7509 s.move_heads_with(|map, head, _| {
7510 (
7511 movement::line_end(map, head, action.stop_at_soft_wraps),
7512 SelectionGoal::None,
7513 )
7514 });
7515 })
7516 }
7517
7518 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7519 self.transact(cx, |this, cx| {
7520 this.select_to_end_of_line(
7521 &SelectToEndOfLine {
7522 stop_at_soft_wraps: false,
7523 },
7524 cx,
7525 );
7526 this.delete(&Delete, cx);
7527 });
7528 }
7529
7530 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7531 self.transact(cx, |this, cx| {
7532 this.select_to_end_of_line(
7533 &SelectToEndOfLine {
7534 stop_at_soft_wraps: false,
7535 },
7536 cx,
7537 );
7538 this.cut(&Cut, cx);
7539 });
7540 }
7541
7542 pub fn move_to_start_of_paragraph(
7543 &mut self,
7544 _: &MoveToStartOfParagraph,
7545 cx: &mut ViewContext<Self>,
7546 ) {
7547 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7548 cx.propagate();
7549 return;
7550 }
7551
7552 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7553 s.move_with(|map, selection| {
7554 selection.collapse_to(
7555 movement::start_of_paragraph(map, selection.head(), 1),
7556 SelectionGoal::None,
7557 )
7558 });
7559 })
7560 }
7561
7562 pub fn move_to_end_of_paragraph(
7563 &mut self,
7564 _: &MoveToEndOfParagraph,
7565 cx: &mut ViewContext<Self>,
7566 ) {
7567 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7568 cx.propagate();
7569 return;
7570 }
7571
7572 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7573 s.move_with(|map, selection| {
7574 selection.collapse_to(
7575 movement::end_of_paragraph(map, selection.head(), 1),
7576 SelectionGoal::None,
7577 )
7578 });
7579 })
7580 }
7581
7582 pub fn select_to_start_of_paragraph(
7583 &mut self,
7584 _: &SelectToStartOfParagraph,
7585 cx: &mut ViewContext<Self>,
7586 ) {
7587 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7588 cx.propagate();
7589 return;
7590 }
7591
7592 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7593 s.move_heads_with(|map, head, _| {
7594 (
7595 movement::start_of_paragraph(map, head, 1),
7596 SelectionGoal::None,
7597 )
7598 });
7599 })
7600 }
7601
7602 pub fn select_to_end_of_paragraph(
7603 &mut self,
7604 _: &SelectToEndOfParagraph,
7605 cx: &mut ViewContext<Self>,
7606 ) {
7607 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7608 cx.propagate();
7609 return;
7610 }
7611
7612 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7613 s.move_heads_with(|map, head, _| {
7614 (
7615 movement::end_of_paragraph(map, head, 1),
7616 SelectionGoal::None,
7617 )
7618 });
7619 })
7620 }
7621
7622 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7623 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7624 cx.propagate();
7625 return;
7626 }
7627
7628 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7629 s.select_ranges(vec![0..0]);
7630 });
7631 }
7632
7633 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7634 let mut selection = self.selections.last::<Point>(cx);
7635 selection.set_head(Point::zero(), SelectionGoal::None);
7636
7637 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7638 s.select(vec![selection]);
7639 });
7640 }
7641
7642 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7643 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7644 cx.propagate();
7645 return;
7646 }
7647
7648 let cursor = self.buffer.read(cx).read(cx).len();
7649 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7650 s.select_ranges(vec![cursor..cursor])
7651 });
7652 }
7653
7654 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7655 self.nav_history = nav_history;
7656 }
7657
7658 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7659 self.nav_history.as_ref()
7660 }
7661
7662 fn push_to_nav_history(
7663 &mut self,
7664 cursor_anchor: Anchor,
7665 new_position: Option<Point>,
7666 cx: &mut ViewContext<Self>,
7667 ) {
7668 if let Some(nav_history) = self.nav_history.as_mut() {
7669 let buffer = self.buffer.read(cx).read(cx);
7670 let cursor_position = cursor_anchor.to_point(&buffer);
7671 let scroll_state = self.scroll_manager.anchor();
7672 let scroll_top_row = scroll_state.top_row(&buffer);
7673 drop(buffer);
7674
7675 if let Some(new_position) = new_position {
7676 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7677 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7678 return;
7679 }
7680 }
7681
7682 nav_history.push(
7683 Some(NavigationData {
7684 cursor_anchor,
7685 cursor_position,
7686 scroll_anchor: scroll_state,
7687 scroll_top_row,
7688 }),
7689 cx,
7690 );
7691 }
7692 }
7693
7694 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7695 let buffer = self.buffer.read(cx).snapshot(cx);
7696 let mut selection = self.selections.first::<usize>(cx);
7697 selection.set_head(buffer.len(), SelectionGoal::None);
7698 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7699 s.select(vec![selection]);
7700 });
7701 }
7702
7703 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7704 let end = self.buffer.read(cx).read(cx).len();
7705 self.change_selections(None, cx, |s| {
7706 s.select_ranges(vec![0..end]);
7707 });
7708 }
7709
7710 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7711 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7712 let mut selections = self.selections.all::<Point>(cx);
7713 let max_point = display_map.buffer_snapshot.max_point();
7714 for selection in &mut selections {
7715 let rows = selection.spanned_rows(true, &display_map);
7716 selection.start = Point::new(rows.start.0, 0);
7717 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7718 selection.reversed = false;
7719 }
7720 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7721 s.select(selections);
7722 });
7723 }
7724
7725 pub fn split_selection_into_lines(
7726 &mut self,
7727 _: &SplitSelectionIntoLines,
7728 cx: &mut ViewContext<Self>,
7729 ) {
7730 let mut to_unfold = Vec::new();
7731 let mut new_selection_ranges = Vec::new();
7732 {
7733 let selections = self.selections.all::<Point>(cx);
7734 let buffer = self.buffer.read(cx).read(cx);
7735 for selection in selections {
7736 for row in selection.start.row..selection.end.row {
7737 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7738 new_selection_ranges.push(cursor..cursor);
7739 }
7740 new_selection_ranges.push(selection.end..selection.end);
7741 to_unfold.push(selection.start..selection.end);
7742 }
7743 }
7744 self.unfold_ranges(to_unfold, true, true, cx);
7745 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7746 s.select_ranges(new_selection_ranges);
7747 });
7748 }
7749
7750 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7751 self.add_selection(true, cx);
7752 }
7753
7754 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7755 self.add_selection(false, cx);
7756 }
7757
7758 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7759 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7760 let mut selections = self.selections.all::<Point>(cx);
7761 let text_layout_details = self.text_layout_details(cx);
7762 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7763 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7764 let range = oldest_selection.display_range(&display_map).sorted();
7765
7766 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7767 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7768 let positions = start_x.min(end_x)..start_x.max(end_x);
7769
7770 selections.clear();
7771 let mut stack = Vec::new();
7772 for row in range.start.row().0..=range.end.row().0 {
7773 if let Some(selection) = self.selections.build_columnar_selection(
7774 &display_map,
7775 DisplayRow(row),
7776 &positions,
7777 oldest_selection.reversed,
7778 &text_layout_details,
7779 ) {
7780 stack.push(selection.id);
7781 selections.push(selection);
7782 }
7783 }
7784
7785 if above {
7786 stack.reverse();
7787 }
7788
7789 AddSelectionsState { above, stack }
7790 });
7791
7792 let last_added_selection = *state.stack.last().unwrap();
7793 let mut new_selections = Vec::new();
7794 if above == state.above {
7795 let end_row = if above {
7796 DisplayRow(0)
7797 } else {
7798 display_map.max_point().row()
7799 };
7800
7801 'outer: for selection in selections {
7802 if selection.id == last_added_selection {
7803 let range = selection.display_range(&display_map).sorted();
7804 debug_assert_eq!(range.start.row(), range.end.row());
7805 let mut row = range.start.row();
7806 let positions =
7807 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7808 px(start)..px(end)
7809 } else {
7810 let start_x =
7811 display_map.x_for_display_point(range.start, &text_layout_details);
7812 let end_x =
7813 display_map.x_for_display_point(range.end, &text_layout_details);
7814 start_x.min(end_x)..start_x.max(end_x)
7815 };
7816
7817 while row != end_row {
7818 if above {
7819 row.0 -= 1;
7820 } else {
7821 row.0 += 1;
7822 }
7823
7824 if let Some(new_selection) = self.selections.build_columnar_selection(
7825 &display_map,
7826 row,
7827 &positions,
7828 selection.reversed,
7829 &text_layout_details,
7830 ) {
7831 state.stack.push(new_selection.id);
7832 if above {
7833 new_selections.push(new_selection);
7834 new_selections.push(selection);
7835 } else {
7836 new_selections.push(selection);
7837 new_selections.push(new_selection);
7838 }
7839
7840 continue 'outer;
7841 }
7842 }
7843 }
7844
7845 new_selections.push(selection);
7846 }
7847 } else {
7848 new_selections = selections;
7849 new_selections.retain(|s| s.id != last_added_selection);
7850 state.stack.pop();
7851 }
7852
7853 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7854 s.select(new_selections);
7855 });
7856 if state.stack.len() > 1 {
7857 self.add_selections_state = Some(state);
7858 }
7859 }
7860
7861 pub fn select_next_match_internal(
7862 &mut self,
7863 display_map: &DisplaySnapshot,
7864 replace_newest: bool,
7865 autoscroll: Option<Autoscroll>,
7866 cx: &mut ViewContext<Self>,
7867 ) -> Result<()> {
7868 fn select_next_match_ranges(
7869 this: &mut Editor,
7870 range: Range<usize>,
7871 replace_newest: bool,
7872 auto_scroll: Option<Autoscroll>,
7873 cx: &mut ViewContext<Editor>,
7874 ) {
7875 this.unfold_ranges([range.clone()], false, true, cx);
7876 this.change_selections(auto_scroll, cx, |s| {
7877 if replace_newest {
7878 s.delete(s.newest_anchor().id);
7879 }
7880 s.insert_range(range.clone());
7881 });
7882 }
7883
7884 let buffer = &display_map.buffer_snapshot;
7885 let mut selections = self.selections.all::<usize>(cx);
7886 if let Some(mut select_next_state) = self.select_next_state.take() {
7887 let query = &select_next_state.query;
7888 if !select_next_state.done {
7889 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7890 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7891 let mut next_selected_range = None;
7892
7893 let bytes_after_last_selection =
7894 buffer.bytes_in_range(last_selection.end..buffer.len());
7895 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
7896 let query_matches = query
7897 .stream_find_iter(bytes_after_last_selection)
7898 .map(|result| (last_selection.end, result))
7899 .chain(
7900 query
7901 .stream_find_iter(bytes_before_first_selection)
7902 .map(|result| (0, result)),
7903 );
7904
7905 for (start_offset, query_match) in query_matches {
7906 let query_match = query_match.unwrap(); // can only fail due to I/O
7907 let offset_range =
7908 start_offset + query_match.start()..start_offset + query_match.end();
7909 let display_range = offset_range.start.to_display_point(&display_map)
7910 ..offset_range.end.to_display_point(&display_map);
7911
7912 if !select_next_state.wordwise
7913 || (!movement::is_inside_word(&display_map, display_range.start)
7914 && !movement::is_inside_word(&display_map, display_range.end))
7915 {
7916 // TODO: This is n^2, because we might check all the selections
7917 if !selections
7918 .iter()
7919 .any(|selection| selection.range().overlaps(&offset_range))
7920 {
7921 next_selected_range = Some(offset_range);
7922 break;
7923 }
7924 }
7925 }
7926
7927 if let Some(next_selected_range) = next_selected_range {
7928 select_next_match_ranges(
7929 self,
7930 next_selected_range,
7931 replace_newest,
7932 autoscroll,
7933 cx,
7934 );
7935 } else {
7936 select_next_state.done = true;
7937 }
7938 }
7939
7940 self.select_next_state = Some(select_next_state);
7941 } else {
7942 let mut only_carets = true;
7943 let mut same_text_selected = true;
7944 let mut selected_text = None;
7945
7946 let mut selections_iter = selections.iter().peekable();
7947 while let Some(selection) = selections_iter.next() {
7948 if selection.start != selection.end {
7949 only_carets = false;
7950 }
7951
7952 if same_text_selected {
7953 if selected_text.is_none() {
7954 selected_text =
7955 Some(buffer.text_for_range(selection.range()).collect::<String>());
7956 }
7957
7958 if let Some(next_selection) = selections_iter.peek() {
7959 if next_selection.range().len() == selection.range().len() {
7960 let next_selected_text = buffer
7961 .text_for_range(next_selection.range())
7962 .collect::<String>();
7963 if Some(next_selected_text) != selected_text {
7964 same_text_selected = false;
7965 selected_text = None;
7966 }
7967 } else {
7968 same_text_selected = false;
7969 selected_text = None;
7970 }
7971 }
7972 }
7973 }
7974
7975 if only_carets {
7976 for selection in &mut selections {
7977 let word_range = movement::surrounding_word(
7978 &display_map,
7979 selection.start.to_display_point(&display_map),
7980 );
7981 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
7982 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
7983 selection.goal = SelectionGoal::None;
7984 selection.reversed = false;
7985 select_next_match_ranges(
7986 self,
7987 selection.start..selection.end,
7988 replace_newest,
7989 autoscroll,
7990 cx,
7991 );
7992 }
7993
7994 if selections.len() == 1 {
7995 let selection = selections
7996 .last()
7997 .expect("ensured that there's only one selection");
7998 let query = buffer
7999 .text_for_range(selection.start..selection.end)
8000 .collect::<String>();
8001 let is_empty = query.is_empty();
8002 let select_state = SelectNextState {
8003 query: AhoCorasick::new(&[query])?,
8004 wordwise: true,
8005 done: is_empty,
8006 };
8007 self.select_next_state = Some(select_state);
8008 } else {
8009 self.select_next_state = None;
8010 }
8011 } else if let Some(selected_text) = selected_text {
8012 self.select_next_state = Some(SelectNextState {
8013 query: AhoCorasick::new(&[selected_text])?,
8014 wordwise: false,
8015 done: false,
8016 });
8017 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8018 }
8019 }
8020 Ok(())
8021 }
8022
8023 pub fn select_all_matches(
8024 &mut self,
8025 _action: &SelectAllMatches,
8026 cx: &mut ViewContext<Self>,
8027 ) -> Result<()> {
8028 self.push_to_selection_history();
8029 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8030
8031 self.select_next_match_internal(&display_map, false, None, cx)?;
8032 let Some(select_next_state) = self.select_next_state.as_mut() else {
8033 return Ok(());
8034 };
8035 if select_next_state.done {
8036 return Ok(());
8037 }
8038
8039 let mut new_selections = self.selections.all::<usize>(cx);
8040
8041 let buffer = &display_map.buffer_snapshot;
8042 let query_matches = select_next_state
8043 .query
8044 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8045
8046 for query_match in query_matches {
8047 let query_match = query_match.unwrap(); // can only fail due to I/O
8048 let offset_range = query_match.start()..query_match.end();
8049 let display_range = offset_range.start.to_display_point(&display_map)
8050 ..offset_range.end.to_display_point(&display_map);
8051
8052 if !select_next_state.wordwise
8053 || (!movement::is_inside_word(&display_map, display_range.start)
8054 && !movement::is_inside_word(&display_map, display_range.end))
8055 {
8056 self.selections.change_with(cx, |selections| {
8057 new_selections.push(Selection {
8058 id: selections.new_selection_id(),
8059 start: offset_range.start,
8060 end: offset_range.end,
8061 reversed: false,
8062 goal: SelectionGoal::None,
8063 });
8064 });
8065 }
8066 }
8067
8068 new_selections.sort_by_key(|selection| selection.start);
8069 let mut ix = 0;
8070 while ix + 1 < new_selections.len() {
8071 let current_selection = &new_selections[ix];
8072 let next_selection = &new_selections[ix + 1];
8073 if current_selection.range().overlaps(&next_selection.range()) {
8074 if current_selection.id < next_selection.id {
8075 new_selections.remove(ix + 1);
8076 } else {
8077 new_selections.remove(ix);
8078 }
8079 } else {
8080 ix += 1;
8081 }
8082 }
8083
8084 select_next_state.done = true;
8085 self.unfold_ranges(
8086 new_selections.iter().map(|selection| selection.range()),
8087 false,
8088 false,
8089 cx,
8090 );
8091 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8092 selections.select(new_selections)
8093 });
8094
8095 Ok(())
8096 }
8097
8098 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8099 self.push_to_selection_history();
8100 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8101 self.select_next_match_internal(
8102 &display_map,
8103 action.replace_newest,
8104 Some(Autoscroll::newest()),
8105 cx,
8106 )?;
8107 Ok(())
8108 }
8109
8110 pub fn select_previous(
8111 &mut self,
8112 action: &SelectPrevious,
8113 cx: &mut ViewContext<Self>,
8114 ) -> Result<()> {
8115 self.push_to_selection_history();
8116 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8117 let buffer = &display_map.buffer_snapshot;
8118 let mut selections = self.selections.all::<usize>(cx);
8119 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8120 let query = &select_prev_state.query;
8121 if !select_prev_state.done {
8122 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8123 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8124 let mut next_selected_range = None;
8125 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8126 let bytes_before_last_selection =
8127 buffer.reversed_bytes_in_range(0..last_selection.start);
8128 let bytes_after_first_selection =
8129 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8130 let query_matches = query
8131 .stream_find_iter(bytes_before_last_selection)
8132 .map(|result| (last_selection.start, result))
8133 .chain(
8134 query
8135 .stream_find_iter(bytes_after_first_selection)
8136 .map(|result| (buffer.len(), result)),
8137 );
8138 for (end_offset, query_match) in query_matches {
8139 let query_match = query_match.unwrap(); // can only fail due to I/O
8140 let offset_range =
8141 end_offset - query_match.end()..end_offset - query_match.start();
8142 let display_range = offset_range.start.to_display_point(&display_map)
8143 ..offset_range.end.to_display_point(&display_map);
8144
8145 if !select_prev_state.wordwise
8146 || (!movement::is_inside_word(&display_map, display_range.start)
8147 && !movement::is_inside_word(&display_map, display_range.end))
8148 {
8149 next_selected_range = Some(offset_range);
8150 break;
8151 }
8152 }
8153
8154 if let Some(next_selected_range) = next_selected_range {
8155 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8156 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8157 if action.replace_newest {
8158 s.delete(s.newest_anchor().id);
8159 }
8160 s.insert_range(next_selected_range);
8161 });
8162 } else {
8163 select_prev_state.done = true;
8164 }
8165 }
8166
8167 self.select_prev_state = Some(select_prev_state);
8168 } else {
8169 let mut only_carets = true;
8170 let mut same_text_selected = true;
8171 let mut selected_text = None;
8172
8173 let mut selections_iter = selections.iter().peekable();
8174 while let Some(selection) = selections_iter.next() {
8175 if selection.start != selection.end {
8176 only_carets = false;
8177 }
8178
8179 if same_text_selected {
8180 if selected_text.is_none() {
8181 selected_text =
8182 Some(buffer.text_for_range(selection.range()).collect::<String>());
8183 }
8184
8185 if let Some(next_selection) = selections_iter.peek() {
8186 if next_selection.range().len() == selection.range().len() {
8187 let next_selected_text = buffer
8188 .text_for_range(next_selection.range())
8189 .collect::<String>();
8190 if Some(next_selected_text) != selected_text {
8191 same_text_selected = false;
8192 selected_text = None;
8193 }
8194 } else {
8195 same_text_selected = false;
8196 selected_text = None;
8197 }
8198 }
8199 }
8200 }
8201
8202 if only_carets {
8203 for selection in &mut selections {
8204 let word_range = movement::surrounding_word(
8205 &display_map,
8206 selection.start.to_display_point(&display_map),
8207 );
8208 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8209 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8210 selection.goal = SelectionGoal::None;
8211 selection.reversed = false;
8212 }
8213 if selections.len() == 1 {
8214 let selection = selections
8215 .last()
8216 .expect("ensured that there's only one selection");
8217 let query = buffer
8218 .text_for_range(selection.start..selection.end)
8219 .collect::<String>();
8220 let is_empty = query.is_empty();
8221 let select_state = SelectNextState {
8222 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8223 wordwise: true,
8224 done: is_empty,
8225 };
8226 self.select_prev_state = Some(select_state);
8227 } else {
8228 self.select_prev_state = None;
8229 }
8230
8231 self.unfold_ranges(
8232 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8233 false,
8234 true,
8235 cx,
8236 );
8237 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8238 s.select(selections);
8239 });
8240 } else if let Some(selected_text) = selected_text {
8241 self.select_prev_state = Some(SelectNextState {
8242 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8243 wordwise: false,
8244 done: false,
8245 });
8246 self.select_previous(action, cx)?;
8247 }
8248 }
8249 Ok(())
8250 }
8251
8252 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8253 let text_layout_details = &self.text_layout_details(cx);
8254 self.transact(cx, |this, cx| {
8255 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8256 let mut edits = Vec::new();
8257 let mut selection_edit_ranges = Vec::new();
8258 let mut last_toggled_row = None;
8259 let snapshot = this.buffer.read(cx).read(cx);
8260 let empty_str: Arc<str> = Arc::default();
8261 let mut suffixes_inserted = Vec::new();
8262
8263 fn comment_prefix_range(
8264 snapshot: &MultiBufferSnapshot,
8265 row: MultiBufferRow,
8266 comment_prefix: &str,
8267 comment_prefix_whitespace: &str,
8268 ) -> Range<Point> {
8269 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8270
8271 let mut line_bytes = snapshot
8272 .bytes_in_range(start..snapshot.max_point())
8273 .flatten()
8274 .copied();
8275
8276 // If this line currently begins with the line comment prefix, then record
8277 // the range containing the prefix.
8278 if line_bytes
8279 .by_ref()
8280 .take(comment_prefix.len())
8281 .eq(comment_prefix.bytes())
8282 {
8283 // Include any whitespace that matches the comment prefix.
8284 let matching_whitespace_len = line_bytes
8285 .zip(comment_prefix_whitespace.bytes())
8286 .take_while(|(a, b)| a == b)
8287 .count() as u32;
8288 let end = Point::new(
8289 start.row,
8290 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8291 );
8292 start..end
8293 } else {
8294 start..start
8295 }
8296 }
8297
8298 fn comment_suffix_range(
8299 snapshot: &MultiBufferSnapshot,
8300 row: MultiBufferRow,
8301 comment_suffix: &str,
8302 comment_suffix_has_leading_space: bool,
8303 ) -> Range<Point> {
8304 let end = Point::new(row.0, snapshot.line_len(row));
8305 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8306
8307 let mut line_end_bytes = snapshot
8308 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8309 .flatten()
8310 .copied();
8311
8312 let leading_space_len = if suffix_start_column > 0
8313 && line_end_bytes.next() == Some(b' ')
8314 && comment_suffix_has_leading_space
8315 {
8316 1
8317 } else {
8318 0
8319 };
8320
8321 // If this line currently begins with the line comment prefix, then record
8322 // the range containing the prefix.
8323 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8324 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8325 start..end
8326 } else {
8327 end..end
8328 }
8329 }
8330
8331 // TODO: Handle selections that cross excerpts
8332 for selection in &mut selections {
8333 let start_column = snapshot
8334 .indent_size_for_line(MultiBufferRow(selection.start.row))
8335 .len;
8336 let language = if let Some(language) =
8337 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8338 {
8339 language
8340 } else {
8341 continue;
8342 };
8343
8344 selection_edit_ranges.clear();
8345
8346 // If multiple selections contain a given row, avoid processing that
8347 // row more than once.
8348 let mut start_row = MultiBufferRow(selection.start.row);
8349 if last_toggled_row == Some(start_row) {
8350 start_row = start_row.next_row();
8351 }
8352 let end_row =
8353 if selection.end.row > selection.start.row && selection.end.column == 0 {
8354 MultiBufferRow(selection.end.row - 1)
8355 } else {
8356 MultiBufferRow(selection.end.row)
8357 };
8358 last_toggled_row = Some(end_row);
8359
8360 if start_row > end_row {
8361 continue;
8362 }
8363
8364 // If the language has line comments, toggle those.
8365 let full_comment_prefixes = language.line_comment_prefixes();
8366 if !full_comment_prefixes.is_empty() {
8367 let first_prefix = full_comment_prefixes
8368 .first()
8369 .expect("prefixes is non-empty");
8370 let prefix_trimmed_lengths = full_comment_prefixes
8371 .iter()
8372 .map(|p| p.trim_end_matches(' ').len())
8373 .collect::<SmallVec<[usize; 4]>>();
8374
8375 let mut all_selection_lines_are_comments = true;
8376
8377 for row in start_row.0..=end_row.0 {
8378 let row = MultiBufferRow(row);
8379 if start_row < end_row && snapshot.is_line_blank(row) {
8380 continue;
8381 }
8382
8383 let prefix_range = full_comment_prefixes
8384 .iter()
8385 .zip(prefix_trimmed_lengths.iter().copied())
8386 .map(|(prefix, trimmed_prefix_len)| {
8387 comment_prefix_range(
8388 snapshot.deref(),
8389 row,
8390 &prefix[..trimmed_prefix_len],
8391 &prefix[trimmed_prefix_len..],
8392 )
8393 })
8394 .max_by_key(|range| range.end.column - range.start.column)
8395 .expect("prefixes is non-empty");
8396
8397 if prefix_range.is_empty() {
8398 all_selection_lines_are_comments = false;
8399 }
8400
8401 selection_edit_ranges.push(prefix_range);
8402 }
8403
8404 if all_selection_lines_are_comments {
8405 edits.extend(
8406 selection_edit_ranges
8407 .iter()
8408 .cloned()
8409 .map(|range| (range, empty_str.clone())),
8410 );
8411 } else {
8412 let min_column = selection_edit_ranges
8413 .iter()
8414 .map(|range| range.start.column)
8415 .min()
8416 .unwrap_or(0);
8417 edits.extend(selection_edit_ranges.iter().map(|range| {
8418 let position = Point::new(range.start.row, min_column);
8419 (position..position, first_prefix.clone())
8420 }));
8421 }
8422 } else if let Some((full_comment_prefix, comment_suffix)) =
8423 language.block_comment_delimiters()
8424 {
8425 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8426 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8427 let prefix_range = comment_prefix_range(
8428 snapshot.deref(),
8429 start_row,
8430 comment_prefix,
8431 comment_prefix_whitespace,
8432 );
8433 let suffix_range = comment_suffix_range(
8434 snapshot.deref(),
8435 end_row,
8436 comment_suffix.trim_start_matches(' '),
8437 comment_suffix.starts_with(' '),
8438 );
8439
8440 if prefix_range.is_empty() || suffix_range.is_empty() {
8441 edits.push((
8442 prefix_range.start..prefix_range.start,
8443 full_comment_prefix.clone(),
8444 ));
8445 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8446 suffixes_inserted.push((end_row, comment_suffix.len()));
8447 } else {
8448 edits.push((prefix_range, empty_str.clone()));
8449 edits.push((suffix_range, empty_str.clone()));
8450 }
8451 } else {
8452 continue;
8453 }
8454 }
8455
8456 drop(snapshot);
8457 this.buffer.update(cx, |buffer, cx| {
8458 buffer.edit(edits, None, cx);
8459 });
8460
8461 // Adjust selections so that they end before any comment suffixes that
8462 // were inserted.
8463 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8464 let mut selections = this.selections.all::<Point>(cx);
8465 let snapshot = this.buffer.read(cx).read(cx);
8466 for selection in &mut selections {
8467 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8468 match row.cmp(&MultiBufferRow(selection.end.row)) {
8469 Ordering::Less => {
8470 suffixes_inserted.next();
8471 continue;
8472 }
8473 Ordering::Greater => break,
8474 Ordering::Equal => {
8475 if selection.end.column == snapshot.line_len(row) {
8476 if selection.is_empty() {
8477 selection.start.column -= suffix_len as u32;
8478 }
8479 selection.end.column -= suffix_len as u32;
8480 }
8481 break;
8482 }
8483 }
8484 }
8485 }
8486
8487 drop(snapshot);
8488 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8489
8490 let selections = this.selections.all::<Point>(cx);
8491 let selections_on_single_row = selections.windows(2).all(|selections| {
8492 selections[0].start.row == selections[1].start.row
8493 && selections[0].end.row == selections[1].end.row
8494 && selections[0].start.row == selections[0].end.row
8495 });
8496 let selections_selecting = selections
8497 .iter()
8498 .any(|selection| selection.start != selection.end);
8499 let advance_downwards = action.advance_downwards
8500 && selections_on_single_row
8501 && !selections_selecting
8502 && !matches!(this.mode, EditorMode::SingleLine { .. });
8503
8504 if advance_downwards {
8505 let snapshot = this.buffer.read(cx).snapshot(cx);
8506
8507 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8508 s.move_cursors_with(|display_snapshot, display_point, _| {
8509 let mut point = display_point.to_point(display_snapshot);
8510 point.row += 1;
8511 point = snapshot.clip_point(point, Bias::Left);
8512 let display_point = point.to_display_point(display_snapshot);
8513 let goal = SelectionGoal::HorizontalPosition(
8514 display_snapshot
8515 .x_for_display_point(display_point, &text_layout_details)
8516 .into(),
8517 );
8518 (display_point, goal)
8519 })
8520 });
8521 }
8522 });
8523 }
8524
8525 pub fn select_enclosing_symbol(
8526 &mut self,
8527 _: &SelectEnclosingSymbol,
8528 cx: &mut ViewContext<Self>,
8529 ) {
8530 let buffer = self.buffer.read(cx).snapshot(cx);
8531 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8532
8533 fn update_selection(
8534 selection: &Selection<usize>,
8535 buffer_snap: &MultiBufferSnapshot,
8536 ) -> Option<Selection<usize>> {
8537 let cursor = selection.head();
8538 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8539 for symbol in symbols.iter().rev() {
8540 let start = symbol.range.start.to_offset(&buffer_snap);
8541 let end = symbol.range.end.to_offset(&buffer_snap);
8542 let new_range = start..end;
8543 if start < selection.start || end > selection.end {
8544 return Some(Selection {
8545 id: selection.id,
8546 start: new_range.start,
8547 end: new_range.end,
8548 goal: SelectionGoal::None,
8549 reversed: selection.reversed,
8550 });
8551 }
8552 }
8553 None
8554 }
8555
8556 let mut selected_larger_symbol = false;
8557 let new_selections = old_selections
8558 .iter()
8559 .map(|selection| match update_selection(selection, &buffer) {
8560 Some(new_selection) => {
8561 if new_selection.range() != selection.range() {
8562 selected_larger_symbol = true;
8563 }
8564 new_selection
8565 }
8566 None => selection.clone(),
8567 })
8568 .collect::<Vec<_>>();
8569
8570 if selected_larger_symbol {
8571 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8572 s.select(new_selections);
8573 });
8574 }
8575 }
8576
8577 pub fn select_larger_syntax_node(
8578 &mut self,
8579 _: &SelectLargerSyntaxNode,
8580 cx: &mut ViewContext<Self>,
8581 ) {
8582 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8583 let buffer = self.buffer.read(cx).snapshot(cx);
8584 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8585
8586 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8587 let mut selected_larger_node = false;
8588 let new_selections = old_selections
8589 .iter()
8590 .map(|selection| {
8591 let old_range = selection.start..selection.end;
8592 let mut new_range = old_range.clone();
8593 while let Some(containing_range) =
8594 buffer.range_for_syntax_ancestor(new_range.clone())
8595 {
8596 new_range = containing_range;
8597 if !display_map.intersects_fold(new_range.start)
8598 && !display_map.intersects_fold(new_range.end)
8599 {
8600 break;
8601 }
8602 }
8603
8604 selected_larger_node |= new_range != old_range;
8605 Selection {
8606 id: selection.id,
8607 start: new_range.start,
8608 end: new_range.end,
8609 goal: SelectionGoal::None,
8610 reversed: selection.reversed,
8611 }
8612 })
8613 .collect::<Vec<_>>();
8614
8615 if selected_larger_node {
8616 stack.push(old_selections);
8617 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8618 s.select(new_selections);
8619 });
8620 }
8621 self.select_larger_syntax_node_stack = stack;
8622 }
8623
8624 pub fn select_smaller_syntax_node(
8625 &mut self,
8626 _: &SelectSmallerSyntaxNode,
8627 cx: &mut ViewContext<Self>,
8628 ) {
8629 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8630 if let Some(selections) = stack.pop() {
8631 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8632 s.select(selections.to_vec());
8633 });
8634 }
8635 self.select_larger_syntax_node_stack = stack;
8636 }
8637
8638 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8639 if !EditorSettings::get_global(cx).gutter.runnables {
8640 self.clear_tasks();
8641 return Task::ready(());
8642 }
8643 let project = self.project.clone();
8644 cx.spawn(|this, mut cx| async move {
8645 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8646 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8647 }) else {
8648 return;
8649 };
8650
8651 let Some(project) = project else {
8652 return;
8653 };
8654
8655 let hide_runnables = project
8656 .update(&mut cx, |project, cx| {
8657 // Do not display any test indicators in non-dev server remote projects.
8658 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8659 })
8660 .unwrap_or(true);
8661 if hide_runnables {
8662 return;
8663 }
8664 let new_rows =
8665 cx.background_executor()
8666 .spawn({
8667 let snapshot = display_snapshot.clone();
8668 async move {
8669 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8670 }
8671 })
8672 .await;
8673 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8674
8675 this.update(&mut cx, |this, _| {
8676 this.clear_tasks();
8677 for (key, value) in rows {
8678 this.insert_tasks(key, value);
8679 }
8680 })
8681 .ok();
8682 })
8683 }
8684 fn fetch_runnable_ranges(
8685 snapshot: &DisplaySnapshot,
8686 range: Range<Anchor>,
8687 ) -> Vec<language::RunnableRange> {
8688 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8689 }
8690
8691 fn runnable_rows(
8692 project: Model<Project>,
8693 snapshot: DisplaySnapshot,
8694 runnable_ranges: Vec<RunnableRange>,
8695 mut cx: AsyncWindowContext,
8696 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8697 runnable_ranges
8698 .into_iter()
8699 .filter_map(|mut runnable| {
8700 let tasks = cx
8701 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8702 .ok()?;
8703 if tasks.is_empty() {
8704 return None;
8705 }
8706
8707 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8708
8709 let row = snapshot
8710 .buffer_snapshot
8711 .buffer_line_for_row(MultiBufferRow(point.row))?
8712 .1
8713 .start
8714 .row;
8715
8716 let context_range =
8717 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8718 Some((
8719 (runnable.buffer_id, row),
8720 RunnableTasks {
8721 templates: tasks,
8722 offset: MultiBufferOffset(runnable.run_range.start),
8723 context_range,
8724 column: point.column,
8725 extra_variables: runnable.extra_captures,
8726 },
8727 ))
8728 })
8729 .collect()
8730 }
8731
8732 fn templates_with_tags(
8733 project: &Model<Project>,
8734 runnable: &mut Runnable,
8735 cx: &WindowContext<'_>,
8736 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8737 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8738 let (worktree_id, file) = project
8739 .buffer_for_id(runnable.buffer, cx)
8740 .and_then(|buffer| buffer.read(cx).file())
8741 .map(|file| (WorktreeId::from_usize(file.worktree_id()), file.clone()))
8742 .unzip();
8743
8744 (project.task_inventory().clone(), worktree_id, file)
8745 });
8746
8747 let inventory = inventory.read(cx);
8748 let tags = mem::take(&mut runnable.tags);
8749 let mut tags: Vec<_> = tags
8750 .into_iter()
8751 .flat_map(|tag| {
8752 let tag = tag.0.clone();
8753 inventory
8754 .list_tasks(
8755 file.clone(),
8756 Some(runnable.language.clone()),
8757 worktree_id,
8758 cx,
8759 )
8760 .into_iter()
8761 .filter(move |(_, template)| {
8762 template.tags.iter().any(|source_tag| source_tag == &tag)
8763 })
8764 })
8765 .sorted_by_key(|(kind, _)| kind.to_owned())
8766 .collect();
8767 if let Some((leading_tag_source, _)) = tags.first() {
8768 // Strongest source wins; if we have worktree tag binding, prefer that to
8769 // global and language bindings;
8770 // if we have a global binding, prefer that to language binding.
8771 let first_mismatch = tags
8772 .iter()
8773 .position(|(tag_source, _)| tag_source != leading_tag_source);
8774 if let Some(index) = first_mismatch {
8775 tags.truncate(index);
8776 }
8777 }
8778
8779 tags
8780 }
8781
8782 pub fn move_to_enclosing_bracket(
8783 &mut self,
8784 _: &MoveToEnclosingBracket,
8785 cx: &mut ViewContext<Self>,
8786 ) {
8787 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8788 s.move_offsets_with(|snapshot, selection| {
8789 let Some(enclosing_bracket_ranges) =
8790 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
8791 else {
8792 return;
8793 };
8794
8795 let mut best_length = usize::MAX;
8796 let mut best_inside = false;
8797 let mut best_in_bracket_range = false;
8798 let mut best_destination = None;
8799 for (open, close) in enclosing_bracket_ranges {
8800 let close = close.to_inclusive();
8801 let length = close.end() - open.start;
8802 let inside = selection.start >= open.end && selection.end <= *close.start();
8803 let in_bracket_range = open.to_inclusive().contains(&selection.head())
8804 || close.contains(&selection.head());
8805
8806 // If best is next to a bracket and current isn't, skip
8807 if !in_bracket_range && best_in_bracket_range {
8808 continue;
8809 }
8810
8811 // Prefer smaller lengths unless best is inside and current isn't
8812 if length > best_length && (best_inside || !inside) {
8813 continue;
8814 }
8815
8816 best_length = length;
8817 best_inside = inside;
8818 best_in_bracket_range = in_bracket_range;
8819 best_destination = Some(
8820 if close.contains(&selection.start) && close.contains(&selection.end) {
8821 if inside {
8822 open.end
8823 } else {
8824 open.start
8825 }
8826 } else {
8827 if inside {
8828 *close.start()
8829 } else {
8830 *close.end()
8831 }
8832 },
8833 );
8834 }
8835
8836 if let Some(destination) = best_destination {
8837 selection.collapse_to(destination, SelectionGoal::None);
8838 }
8839 })
8840 });
8841 }
8842
8843 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
8844 self.end_selection(cx);
8845 self.selection_history.mode = SelectionHistoryMode::Undoing;
8846 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
8847 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8848 self.select_next_state = entry.select_next_state;
8849 self.select_prev_state = entry.select_prev_state;
8850 self.add_selections_state = entry.add_selections_state;
8851 self.request_autoscroll(Autoscroll::newest(), cx);
8852 }
8853 self.selection_history.mode = SelectionHistoryMode::Normal;
8854 }
8855
8856 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
8857 self.end_selection(cx);
8858 self.selection_history.mode = SelectionHistoryMode::Redoing;
8859 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
8860 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8861 self.select_next_state = entry.select_next_state;
8862 self.select_prev_state = entry.select_prev_state;
8863 self.add_selections_state = entry.add_selections_state;
8864 self.request_autoscroll(Autoscroll::newest(), cx);
8865 }
8866 self.selection_history.mode = SelectionHistoryMode::Normal;
8867 }
8868
8869 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
8870 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
8871 }
8872
8873 pub fn expand_excerpts_down(
8874 &mut self,
8875 action: &ExpandExcerptsDown,
8876 cx: &mut ViewContext<Self>,
8877 ) {
8878 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
8879 }
8880
8881 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
8882 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
8883 }
8884
8885 pub fn expand_excerpts_for_direction(
8886 &mut self,
8887 lines: u32,
8888 direction: ExpandExcerptDirection,
8889 cx: &mut ViewContext<Self>,
8890 ) {
8891 let selections = self.selections.disjoint_anchors();
8892
8893 let lines = if lines == 0 {
8894 EditorSettings::get_global(cx).expand_excerpt_lines
8895 } else {
8896 lines
8897 };
8898
8899 self.buffer.update(cx, |buffer, cx| {
8900 buffer.expand_excerpts(
8901 selections
8902 .into_iter()
8903 .map(|selection| selection.head().excerpt_id)
8904 .dedup(),
8905 lines,
8906 direction,
8907 cx,
8908 )
8909 })
8910 }
8911
8912 pub fn expand_excerpt(
8913 &mut self,
8914 excerpt: ExcerptId,
8915 direction: ExpandExcerptDirection,
8916 cx: &mut ViewContext<Self>,
8917 ) {
8918 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
8919 self.buffer.update(cx, |buffer, cx| {
8920 buffer.expand_excerpts([excerpt], lines, direction, cx)
8921 })
8922 }
8923
8924 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
8925 self.go_to_diagnostic_impl(Direction::Next, cx)
8926 }
8927
8928 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
8929 self.go_to_diagnostic_impl(Direction::Prev, cx)
8930 }
8931
8932 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
8933 let buffer = self.buffer.read(cx).snapshot(cx);
8934 let selection = self.selections.newest::<usize>(cx);
8935
8936 // If there is an active Diagnostic Popover jump to its diagnostic instead.
8937 if direction == Direction::Next {
8938 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
8939 let (group_id, jump_to) = popover.activation_info();
8940 if self.activate_diagnostics(group_id, cx) {
8941 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8942 let mut new_selection = s.newest_anchor().clone();
8943 new_selection.collapse_to(jump_to, SelectionGoal::None);
8944 s.select_anchors(vec![new_selection.clone()]);
8945 });
8946 }
8947 return;
8948 }
8949 }
8950
8951 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
8952 active_diagnostics
8953 .primary_range
8954 .to_offset(&buffer)
8955 .to_inclusive()
8956 });
8957 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
8958 if active_primary_range.contains(&selection.head()) {
8959 *active_primary_range.start()
8960 } else {
8961 selection.head()
8962 }
8963 } else {
8964 selection.head()
8965 };
8966 let snapshot = self.snapshot(cx);
8967 loop {
8968 let diagnostics = if direction == Direction::Prev {
8969 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
8970 } else {
8971 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
8972 }
8973 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
8974 let group = diagnostics
8975 // relies on diagnostics_in_range to return diagnostics with the same starting range to
8976 // be sorted in a stable way
8977 // skip until we are at current active diagnostic, if it exists
8978 .skip_while(|entry| {
8979 (match direction {
8980 Direction::Prev => entry.range.start >= search_start,
8981 Direction::Next => entry.range.start <= search_start,
8982 }) && self
8983 .active_diagnostics
8984 .as_ref()
8985 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
8986 })
8987 .find_map(|entry| {
8988 if entry.diagnostic.is_primary
8989 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
8990 && !entry.range.is_empty()
8991 // if we match with the active diagnostic, skip it
8992 && Some(entry.diagnostic.group_id)
8993 != self.active_diagnostics.as_ref().map(|d| d.group_id)
8994 {
8995 Some((entry.range, entry.diagnostic.group_id))
8996 } else {
8997 None
8998 }
8999 });
9000
9001 if let Some((primary_range, group_id)) = group {
9002 if self.activate_diagnostics(group_id, cx) {
9003 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9004 s.select(vec![Selection {
9005 id: selection.id,
9006 start: primary_range.start,
9007 end: primary_range.start,
9008 reversed: false,
9009 goal: SelectionGoal::None,
9010 }]);
9011 });
9012 }
9013 break;
9014 } else {
9015 // Cycle around to the start of the buffer, potentially moving back to the start of
9016 // the currently active diagnostic.
9017 active_primary_range.take();
9018 if direction == Direction::Prev {
9019 if search_start == buffer.len() {
9020 break;
9021 } else {
9022 search_start = buffer.len();
9023 }
9024 } else if search_start == 0 {
9025 break;
9026 } else {
9027 search_start = 0;
9028 }
9029 }
9030 }
9031 }
9032
9033 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9034 let snapshot = self
9035 .display_map
9036 .update(cx, |display_map, cx| display_map.snapshot(cx));
9037 let selection = self.selections.newest::<Point>(cx);
9038
9039 if !self.seek_in_direction(
9040 &snapshot,
9041 selection.head(),
9042 false,
9043 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9044 MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
9045 ),
9046 cx,
9047 ) {
9048 let wrapped_point = Point::zero();
9049 self.seek_in_direction(
9050 &snapshot,
9051 wrapped_point,
9052 true,
9053 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9054 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9055 ),
9056 cx,
9057 );
9058 }
9059 }
9060
9061 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9062 let snapshot = self
9063 .display_map
9064 .update(cx, |display_map, cx| display_map.snapshot(cx));
9065 let selection = self.selections.newest::<Point>(cx);
9066
9067 if !self.seek_in_direction(
9068 &snapshot,
9069 selection.head(),
9070 false,
9071 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9072 MultiBufferRow(0)..MultiBufferRow(selection.head().row),
9073 ),
9074 cx,
9075 ) {
9076 let wrapped_point = snapshot.buffer_snapshot.max_point();
9077 self.seek_in_direction(
9078 &snapshot,
9079 wrapped_point,
9080 true,
9081 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9082 MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
9083 ),
9084 cx,
9085 );
9086 }
9087 }
9088
9089 fn seek_in_direction(
9090 &mut self,
9091 snapshot: &DisplaySnapshot,
9092 initial_point: Point,
9093 is_wrapped: bool,
9094 hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
9095 cx: &mut ViewContext<Editor>,
9096 ) -> bool {
9097 let display_point = initial_point.to_display_point(snapshot);
9098 let mut hunks = hunks
9099 .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
9100 .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
9101 .dedup();
9102
9103 if let Some(hunk) = hunks.next() {
9104 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9105 let row = hunk.start_display_row();
9106 let point = DisplayPoint::new(row, 0);
9107 s.select_display_ranges([point..point]);
9108 });
9109
9110 true
9111 } else {
9112 false
9113 }
9114 }
9115
9116 pub fn go_to_definition(
9117 &mut self,
9118 _: &GoToDefinition,
9119 cx: &mut ViewContext<Self>,
9120 ) -> Task<Result<Navigated>> {
9121 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9122 cx.spawn(|editor, mut cx| async move {
9123 if definition.await? == Navigated::Yes {
9124 return Ok(Navigated::Yes);
9125 }
9126 match editor.update(&mut cx, |editor, cx| {
9127 editor.find_all_references(&FindAllReferences, cx)
9128 })? {
9129 Some(references) => references.await,
9130 None => Ok(Navigated::No),
9131 }
9132 })
9133 }
9134
9135 pub fn go_to_declaration(
9136 &mut self,
9137 _: &GoToDeclaration,
9138 cx: &mut ViewContext<Self>,
9139 ) -> Task<Result<Navigated>> {
9140 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9141 }
9142
9143 pub fn go_to_declaration_split(
9144 &mut self,
9145 _: &GoToDeclaration,
9146 cx: &mut ViewContext<Self>,
9147 ) -> Task<Result<Navigated>> {
9148 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9149 }
9150
9151 pub fn go_to_implementation(
9152 &mut self,
9153 _: &GoToImplementation,
9154 cx: &mut ViewContext<Self>,
9155 ) -> Task<Result<Navigated>> {
9156 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9157 }
9158
9159 pub fn go_to_implementation_split(
9160 &mut self,
9161 _: &GoToImplementationSplit,
9162 cx: &mut ViewContext<Self>,
9163 ) -> Task<Result<Navigated>> {
9164 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9165 }
9166
9167 pub fn go_to_type_definition(
9168 &mut self,
9169 _: &GoToTypeDefinition,
9170 cx: &mut ViewContext<Self>,
9171 ) -> Task<Result<Navigated>> {
9172 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9173 }
9174
9175 pub fn go_to_definition_split(
9176 &mut self,
9177 _: &GoToDefinitionSplit,
9178 cx: &mut ViewContext<Self>,
9179 ) -> Task<Result<Navigated>> {
9180 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9181 }
9182
9183 pub fn go_to_type_definition_split(
9184 &mut self,
9185 _: &GoToTypeDefinitionSplit,
9186 cx: &mut ViewContext<Self>,
9187 ) -> Task<Result<Navigated>> {
9188 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9189 }
9190
9191 fn go_to_definition_of_kind(
9192 &mut self,
9193 kind: GotoDefinitionKind,
9194 split: bool,
9195 cx: &mut ViewContext<Self>,
9196 ) -> Task<Result<Navigated>> {
9197 let Some(workspace) = self.workspace() else {
9198 return Task::ready(Ok(Navigated::No));
9199 };
9200 let buffer = self.buffer.read(cx);
9201 let head = self.selections.newest::<usize>(cx).head();
9202 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9203 text_anchor
9204 } else {
9205 return Task::ready(Ok(Navigated::No));
9206 };
9207
9208 let project = workspace.read(cx).project().clone();
9209 let definitions = project.update(cx, |project, cx| match kind {
9210 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
9211 GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
9212 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
9213 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
9214 });
9215
9216 cx.spawn(|editor, mut cx| async move {
9217 let definitions = definitions.await?;
9218 let navigated = editor
9219 .update(&mut cx, |editor, cx| {
9220 editor.navigate_to_hover_links(
9221 Some(kind),
9222 definitions
9223 .into_iter()
9224 .filter(|location| {
9225 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9226 })
9227 .map(HoverLink::Text)
9228 .collect::<Vec<_>>(),
9229 split,
9230 cx,
9231 )
9232 })?
9233 .await?;
9234 anyhow::Ok(navigated)
9235 })
9236 }
9237
9238 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9239 let position = self.selections.newest_anchor().head();
9240 let Some((buffer, buffer_position)) =
9241 self.buffer.read(cx).text_anchor_for_position(position, cx)
9242 else {
9243 return;
9244 };
9245
9246 cx.spawn(|editor, mut cx| async move {
9247 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9248 editor.update(&mut cx, |_, cx| {
9249 cx.open_url(&url);
9250 })
9251 } else {
9252 Ok(())
9253 }
9254 })
9255 .detach();
9256 }
9257
9258 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9259 let Some(workspace) = self.workspace() else {
9260 return;
9261 };
9262
9263 let position = self.selections.newest_anchor().head();
9264
9265 let Some((buffer, buffer_position)) =
9266 self.buffer.read(cx).text_anchor_for_position(position, cx)
9267 else {
9268 return;
9269 };
9270
9271 let Some(project) = self.project.clone() else {
9272 return;
9273 };
9274
9275 cx.spawn(|_, mut cx| async move {
9276 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9277
9278 if let Some((_, path)) = result {
9279 workspace
9280 .update(&mut cx, |workspace, cx| {
9281 workspace.open_resolved_path(path, cx)
9282 })?
9283 .await?;
9284 }
9285 anyhow::Ok(())
9286 })
9287 .detach();
9288 }
9289
9290 pub(crate) fn navigate_to_hover_links(
9291 &mut self,
9292 kind: Option<GotoDefinitionKind>,
9293 mut definitions: Vec<HoverLink>,
9294 split: bool,
9295 cx: &mut ViewContext<Editor>,
9296 ) -> Task<Result<Navigated>> {
9297 // If there is one definition, just open it directly
9298 if definitions.len() == 1 {
9299 let definition = definitions.pop().unwrap();
9300
9301 enum TargetTaskResult {
9302 Location(Option<Location>),
9303 AlreadyNavigated,
9304 }
9305
9306 let target_task = match definition {
9307 HoverLink::Text(link) => {
9308 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9309 }
9310 HoverLink::InlayHint(lsp_location, server_id) => {
9311 let computation = self.compute_target_location(lsp_location, server_id, cx);
9312 cx.background_executor().spawn(async move {
9313 let location = computation.await?;
9314 Ok(TargetTaskResult::Location(location))
9315 })
9316 }
9317 HoverLink::Url(url) => {
9318 cx.open_url(&url);
9319 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9320 }
9321 HoverLink::File(path) => {
9322 if let Some(workspace) = self.workspace() {
9323 cx.spawn(|_, mut cx| async move {
9324 workspace
9325 .update(&mut cx, |workspace, cx| {
9326 workspace.open_resolved_path(path, cx)
9327 })?
9328 .await
9329 .map(|_| TargetTaskResult::AlreadyNavigated)
9330 })
9331 } else {
9332 Task::ready(Ok(TargetTaskResult::Location(None)))
9333 }
9334 }
9335 };
9336 cx.spawn(|editor, mut cx| async move {
9337 let target = match target_task.await.context("target resolution task")? {
9338 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9339 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9340 TargetTaskResult::Location(Some(target)) => target,
9341 };
9342
9343 editor.update(&mut cx, |editor, cx| {
9344 let Some(workspace) = editor.workspace() else {
9345 return Navigated::No;
9346 };
9347 let pane = workspace.read(cx).active_pane().clone();
9348
9349 let range = target.range.to_offset(target.buffer.read(cx));
9350 let range = editor.range_for_match(&range);
9351
9352 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9353 let buffer = target.buffer.read(cx);
9354 let range = check_multiline_range(buffer, range);
9355 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
9356 s.select_ranges([range]);
9357 });
9358 } else {
9359 cx.window_context().defer(move |cx| {
9360 let target_editor: View<Self> =
9361 workspace.update(cx, |workspace, cx| {
9362 let pane = if split {
9363 workspace.adjacent_pane(cx)
9364 } else {
9365 workspace.active_pane().clone()
9366 };
9367
9368 workspace.open_project_item(
9369 pane,
9370 target.buffer.clone(),
9371 true,
9372 true,
9373 cx,
9374 )
9375 });
9376 target_editor.update(cx, |target_editor, cx| {
9377 // When selecting a definition in a different buffer, disable the nav history
9378 // to avoid creating a history entry at the previous cursor location.
9379 pane.update(cx, |pane, _| pane.disable_history());
9380 let buffer = target.buffer.read(cx);
9381 let range = check_multiline_range(buffer, range);
9382 target_editor.change_selections(
9383 Some(Autoscroll::focused()),
9384 cx,
9385 |s| {
9386 s.select_ranges([range]);
9387 },
9388 );
9389 pane.update(cx, |pane, _| pane.enable_history());
9390 });
9391 });
9392 }
9393 Navigated::Yes
9394 })
9395 })
9396 } else if !definitions.is_empty() {
9397 let replica_id = self.replica_id(cx);
9398 cx.spawn(|editor, mut cx| async move {
9399 let (title, location_tasks, workspace) = editor
9400 .update(&mut cx, |editor, cx| {
9401 let tab_kind = match kind {
9402 Some(GotoDefinitionKind::Implementation) => "Implementations",
9403 _ => "Definitions",
9404 };
9405 let title = definitions
9406 .iter()
9407 .find_map(|definition| match definition {
9408 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9409 let buffer = origin.buffer.read(cx);
9410 format!(
9411 "{} for {}",
9412 tab_kind,
9413 buffer
9414 .text_for_range(origin.range.clone())
9415 .collect::<String>()
9416 )
9417 }),
9418 HoverLink::InlayHint(_, _) => None,
9419 HoverLink::Url(_) => None,
9420 HoverLink::File(_) => None,
9421 })
9422 .unwrap_or(tab_kind.to_string());
9423 let location_tasks = definitions
9424 .into_iter()
9425 .map(|definition| match definition {
9426 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9427 HoverLink::InlayHint(lsp_location, server_id) => {
9428 editor.compute_target_location(lsp_location, server_id, cx)
9429 }
9430 HoverLink::Url(_) => Task::ready(Ok(None)),
9431 HoverLink::File(_) => Task::ready(Ok(None)),
9432 })
9433 .collect::<Vec<_>>();
9434 (title, location_tasks, editor.workspace().clone())
9435 })
9436 .context("location tasks preparation")?;
9437
9438 let locations = futures::future::join_all(location_tasks)
9439 .await
9440 .into_iter()
9441 .filter_map(|location| location.transpose())
9442 .collect::<Result<_>>()
9443 .context("location tasks")?;
9444
9445 let Some(workspace) = workspace else {
9446 return Ok(Navigated::No);
9447 };
9448 let opened = workspace
9449 .update(&mut cx, |workspace, cx| {
9450 Self::open_locations_in_multibuffer(
9451 workspace, locations, replica_id, title, split, cx,
9452 )
9453 })
9454 .ok();
9455
9456 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9457 })
9458 } else {
9459 Task::ready(Ok(Navigated::No))
9460 }
9461 }
9462
9463 fn compute_target_location(
9464 &self,
9465 lsp_location: lsp::Location,
9466 server_id: LanguageServerId,
9467 cx: &mut ViewContext<Editor>,
9468 ) -> Task<anyhow::Result<Option<Location>>> {
9469 let Some(project) = self.project.clone() else {
9470 return Task::Ready(Some(Ok(None)));
9471 };
9472
9473 cx.spawn(move |editor, mut cx| async move {
9474 let location_task = editor.update(&mut cx, |editor, cx| {
9475 project.update(cx, |project, cx| {
9476 let language_server_name =
9477 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9478 project
9479 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9480 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9481 });
9482 language_server_name.map(|language_server_name| {
9483 project.open_local_buffer_via_lsp(
9484 lsp_location.uri.clone(),
9485 server_id,
9486 language_server_name,
9487 cx,
9488 )
9489 })
9490 })
9491 })?;
9492 let location = match location_task {
9493 Some(task) => Some({
9494 let target_buffer_handle = task.await.context("open local buffer")?;
9495 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9496 let target_start = target_buffer
9497 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9498 let target_end = target_buffer
9499 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9500 target_buffer.anchor_after(target_start)
9501 ..target_buffer.anchor_before(target_end)
9502 })?;
9503 Location {
9504 buffer: target_buffer_handle,
9505 range,
9506 }
9507 }),
9508 None => None,
9509 };
9510 Ok(location)
9511 })
9512 }
9513
9514 pub fn find_all_references(
9515 &mut self,
9516 _: &FindAllReferences,
9517 cx: &mut ViewContext<Self>,
9518 ) -> Option<Task<Result<Navigated>>> {
9519 let multi_buffer = self.buffer.read(cx);
9520 let selection = self.selections.newest::<usize>(cx);
9521 let head = selection.head();
9522
9523 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9524 let head_anchor = multi_buffer_snapshot.anchor_at(
9525 head,
9526 if head < selection.tail() {
9527 Bias::Right
9528 } else {
9529 Bias::Left
9530 },
9531 );
9532
9533 match self
9534 .find_all_references_task_sources
9535 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9536 {
9537 Ok(_) => {
9538 log::info!(
9539 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9540 );
9541 return None;
9542 }
9543 Err(i) => {
9544 self.find_all_references_task_sources.insert(i, head_anchor);
9545 }
9546 }
9547
9548 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9549 let replica_id = self.replica_id(cx);
9550 let workspace = self.workspace()?;
9551 let project = workspace.read(cx).project().clone();
9552 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9553 Some(cx.spawn(|editor, mut cx| async move {
9554 let _cleanup = defer({
9555 let mut cx = cx.clone();
9556 move || {
9557 let _ = editor.update(&mut cx, |editor, _| {
9558 if let Ok(i) =
9559 editor
9560 .find_all_references_task_sources
9561 .binary_search_by(|anchor| {
9562 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9563 })
9564 {
9565 editor.find_all_references_task_sources.remove(i);
9566 }
9567 });
9568 }
9569 });
9570
9571 let locations = references.await?;
9572 if locations.is_empty() {
9573 return anyhow::Ok(Navigated::No);
9574 }
9575
9576 workspace.update(&mut cx, |workspace, cx| {
9577 let title = locations
9578 .first()
9579 .as_ref()
9580 .map(|location| {
9581 let buffer = location.buffer.read(cx);
9582 format!(
9583 "References to `{}`",
9584 buffer
9585 .text_for_range(location.range.clone())
9586 .collect::<String>()
9587 )
9588 })
9589 .unwrap();
9590 Self::open_locations_in_multibuffer(
9591 workspace, locations, replica_id, title, false, cx,
9592 );
9593 Navigated::Yes
9594 })
9595 }))
9596 }
9597
9598 /// Opens a multibuffer with the given project locations in it
9599 pub fn open_locations_in_multibuffer(
9600 workspace: &mut Workspace,
9601 mut locations: Vec<Location>,
9602 replica_id: ReplicaId,
9603 title: String,
9604 split: bool,
9605 cx: &mut ViewContext<Workspace>,
9606 ) {
9607 // If there are multiple definitions, open them in a multibuffer
9608 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9609 let mut locations = locations.into_iter().peekable();
9610 let mut ranges_to_highlight = Vec::new();
9611 let capability = workspace.project().read(cx).capability();
9612
9613 let excerpt_buffer = cx.new_model(|cx| {
9614 let mut multibuffer = MultiBuffer::new(replica_id, capability);
9615 while let Some(location) = locations.next() {
9616 let buffer = location.buffer.read(cx);
9617 let mut ranges_for_buffer = Vec::new();
9618 let range = location.range.to_offset(buffer);
9619 ranges_for_buffer.push(range.clone());
9620
9621 while let Some(next_location) = locations.peek() {
9622 if next_location.buffer == location.buffer {
9623 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9624 locations.next();
9625 } else {
9626 break;
9627 }
9628 }
9629
9630 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9631 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9632 location.buffer.clone(),
9633 ranges_for_buffer,
9634 DEFAULT_MULTIBUFFER_CONTEXT,
9635 cx,
9636 ))
9637 }
9638
9639 multibuffer.with_title(title)
9640 });
9641
9642 let editor = cx.new_view(|cx| {
9643 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9644 });
9645 editor.update(cx, |editor, cx| {
9646 if let Some(first_range) = ranges_to_highlight.first() {
9647 editor.change_selections(None, cx, |selections| {
9648 selections.clear_disjoint();
9649 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9650 });
9651 }
9652 editor.highlight_background::<Self>(
9653 &ranges_to_highlight,
9654 |theme| theme.editor_highlighted_line_background,
9655 cx,
9656 );
9657 });
9658
9659 let item = Box::new(editor);
9660 let item_id = item.item_id();
9661
9662 if split {
9663 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9664 } else {
9665 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9666 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9667 pane.close_current_preview_item(cx)
9668 } else {
9669 None
9670 }
9671 });
9672 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9673 }
9674 workspace.active_pane().update(cx, |pane, cx| {
9675 pane.set_preview_item_id(Some(item_id), cx);
9676 });
9677 }
9678
9679 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9680 use language::ToOffset as _;
9681
9682 let project = self.project.clone()?;
9683 let selection = self.selections.newest_anchor().clone();
9684 let (cursor_buffer, cursor_buffer_position) = self
9685 .buffer
9686 .read(cx)
9687 .text_anchor_for_position(selection.head(), cx)?;
9688 let (tail_buffer, cursor_buffer_position_end) = self
9689 .buffer
9690 .read(cx)
9691 .text_anchor_for_position(selection.tail(), cx)?;
9692 if tail_buffer != cursor_buffer {
9693 return None;
9694 }
9695
9696 let snapshot = cursor_buffer.read(cx).snapshot();
9697 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9698 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9699 let prepare_rename = project.update(cx, |project, cx| {
9700 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
9701 });
9702 drop(snapshot);
9703
9704 Some(cx.spawn(|this, mut cx| async move {
9705 let rename_range = if let Some(range) = prepare_rename.await? {
9706 Some(range)
9707 } else {
9708 this.update(&mut cx, |this, cx| {
9709 let buffer = this.buffer.read(cx).snapshot(cx);
9710 let mut buffer_highlights = this
9711 .document_highlights_for_position(selection.head(), &buffer)
9712 .filter(|highlight| {
9713 highlight.start.excerpt_id == selection.head().excerpt_id
9714 && highlight.end.excerpt_id == selection.head().excerpt_id
9715 });
9716 buffer_highlights
9717 .next()
9718 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9719 })?
9720 };
9721 if let Some(rename_range) = rename_range {
9722 this.update(&mut cx, |this, cx| {
9723 let snapshot = cursor_buffer.read(cx).snapshot();
9724 let rename_buffer_range = rename_range.to_offset(&snapshot);
9725 let cursor_offset_in_rename_range =
9726 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9727 let cursor_offset_in_rename_range_end =
9728 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9729
9730 this.take_rename(false, cx);
9731 let buffer = this.buffer.read(cx).read(cx);
9732 let cursor_offset = selection.head().to_offset(&buffer);
9733 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9734 let rename_end = rename_start + rename_buffer_range.len();
9735 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9736 let mut old_highlight_id = None;
9737 let old_name: Arc<str> = buffer
9738 .chunks(rename_start..rename_end, true)
9739 .map(|chunk| {
9740 if old_highlight_id.is_none() {
9741 old_highlight_id = chunk.syntax_highlight_id;
9742 }
9743 chunk.text
9744 })
9745 .collect::<String>()
9746 .into();
9747
9748 drop(buffer);
9749
9750 // Position the selection in the rename editor so that it matches the current selection.
9751 this.show_local_selections = false;
9752 let rename_editor = cx.new_view(|cx| {
9753 let mut editor = Editor::single_line(cx);
9754 editor.buffer.update(cx, |buffer, cx| {
9755 buffer.edit([(0..0, old_name.clone())], None, cx)
9756 });
9757 let rename_selection_range = match cursor_offset_in_rename_range
9758 .cmp(&cursor_offset_in_rename_range_end)
9759 {
9760 Ordering::Equal => {
9761 editor.select_all(&SelectAll, cx);
9762 return editor;
9763 }
9764 Ordering::Less => {
9765 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9766 }
9767 Ordering::Greater => {
9768 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9769 }
9770 };
9771 if rename_selection_range.end > old_name.len() {
9772 editor.select_all(&SelectAll, cx);
9773 } else {
9774 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9775 s.select_ranges([rename_selection_range]);
9776 });
9777 }
9778 editor
9779 });
9780 cx.subscribe(&rename_editor, |_, _, e, cx| match e {
9781 EditorEvent::Focused => cx.emit(EditorEvent::FocusedIn),
9782 _ => {}
9783 })
9784 .detach();
9785
9786 let write_highlights =
9787 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
9788 let read_highlights =
9789 this.clear_background_highlights::<DocumentHighlightRead>(cx);
9790 let ranges = write_highlights
9791 .iter()
9792 .flat_map(|(_, ranges)| ranges.iter())
9793 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
9794 .cloned()
9795 .collect();
9796
9797 this.highlight_text::<Rename>(
9798 ranges,
9799 HighlightStyle {
9800 fade_out: Some(0.6),
9801 ..Default::default()
9802 },
9803 cx,
9804 );
9805 let rename_focus_handle = rename_editor.focus_handle(cx);
9806 cx.focus(&rename_focus_handle);
9807 let block_id = this.insert_blocks(
9808 [BlockProperties {
9809 style: BlockStyle::Flex,
9810 position: range.start,
9811 height: 1,
9812 render: Box::new({
9813 let rename_editor = rename_editor.clone();
9814 move |cx: &mut BlockContext| {
9815 let mut text_style = cx.editor_style.text.clone();
9816 if let Some(highlight_style) = old_highlight_id
9817 .and_then(|h| h.style(&cx.editor_style.syntax))
9818 {
9819 text_style = text_style.highlight(highlight_style);
9820 }
9821 div()
9822 .pl(cx.anchor_x)
9823 .child(EditorElement::new(
9824 &rename_editor,
9825 EditorStyle {
9826 background: cx.theme().system().transparent,
9827 local_player: cx.editor_style.local_player,
9828 text: text_style,
9829 scrollbar_width: cx.editor_style.scrollbar_width,
9830 syntax: cx.editor_style.syntax.clone(),
9831 status: cx.editor_style.status.clone(),
9832 inlay_hints_style: HighlightStyle {
9833 color: Some(cx.theme().status().hint),
9834 font_weight: Some(FontWeight::BOLD),
9835 ..HighlightStyle::default()
9836 },
9837 suggestions_style: HighlightStyle {
9838 color: Some(cx.theme().status().predictive),
9839 ..HighlightStyle::default()
9840 },
9841 ..EditorStyle::default()
9842 },
9843 ))
9844 .into_any_element()
9845 }
9846 }),
9847 disposition: BlockDisposition::Below,
9848 priority: 0,
9849 }],
9850 Some(Autoscroll::fit()),
9851 cx,
9852 )[0];
9853 this.pending_rename = Some(RenameState {
9854 range,
9855 old_name,
9856 editor: rename_editor,
9857 block_id,
9858 });
9859 })?;
9860 }
9861
9862 Ok(())
9863 }))
9864 }
9865
9866 pub fn confirm_rename(
9867 &mut self,
9868 _: &ConfirmRename,
9869 cx: &mut ViewContext<Self>,
9870 ) -> Option<Task<Result<()>>> {
9871 let rename = self.take_rename(false, cx)?;
9872 let workspace = self.workspace()?;
9873 let (start_buffer, start) = self
9874 .buffer
9875 .read(cx)
9876 .text_anchor_for_position(rename.range.start, cx)?;
9877 let (end_buffer, end) = self
9878 .buffer
9879 .read(cx)
9880 .text_anchor_for_position(rename.range.end, cx)?;
9881 if start_buffer != end_buffer {
9882 return None;
9883 }
9884
9885 let buffer = start_buffer;
9886 let range = start..end;
9887 let old_name = rename.old_name;
9888 let new_name = rename.editor.read(cx).text(cx);
9889
9890 let rename = workspace
9891 .read(cx)
9892 .project()
9893 .clone()
9894 .update(cx, |project, cx| {
9895 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
9896 });
9897 let workspace = workspace.downgrade();
9898
9899 Some(cx.spawn(|editor, mut cx| async move {
9900 let project_transaction = rename.await?;
9901 Self::open_project_transaction(
9902 &editor,
9903 workspace,
9904 project_transaction,
9905 format!("Rename: {} → {}", old_name, new_name),
9906 cx.clone(),
9907 )
9908 .await?;
9909
9910 editor.update(&mut cx, |editor, cx| {
9911 editor.refresh_document_highlights(cx);
9912 })?;
9913 Ok(())
9914 }))
9915 }
9916
9917 fn take_rename(
9918 &mut self,
9919 moving_cursor: bool,
9920 cx: &mut ViewContext<Self>,
9921 ) -> Option<RenameState> {
9922 let rename = self.pending_rename.take()?;
9923 if rename.editor.focus_handle(cx).is_focused(cx) {
9924 cx.focus(&self.focus_handle);
9925 }
9926
9927 self.remove_blocks(
9928 [rename.block_id].into_iter().collect(),
9929 Some(Autoscroll::fit()),
9930 cx,
9931 );
9932 self.clear_highlights::<Rename>(cx);
9933 self.show_local_selections = true;
9934
9935 if moving_cursor {
9936 let rename_editor = rename.editor.read(cx);
9937 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
9938
9939 // Update the selection to match the position of the selection inside
9940 // the rename editor.
9941 let snapshot = self.buffer.read(cx).read(cx);
9942 let rename_range = rename.range.to_offset(&snapshot);
9943 let cursor_in_editor = snapshot
9944 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
9945 .min(rename_range.end);
9946 drop(snapshot);
9947
9948 self.change_selections(None, cx, |s| {
9949 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
9950 });
9951 } else {
9952 self.refresh_document_highlights(cx);
9953 }
9954
9955 Some(rename)
9956 }
9957
9958 pub fn pending_rename(&self) -> Option<&RenameState> {
9959 self.pending_rename.as_ref()
9960 }
9961
9962 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9963 let project = match &self.project {
9964 Some(project) => project.clone(),
9965 None => return None,
9966 };
9967
9968 Some(self.perform_format(project, FormatTrigger::Manual, cx))
9969 }
9970
9971 fn perform_format(
9972 &mut self,
9973 project: Model<Project>,
9974 trigger: FormatTrigger,
9975 cx: &mut ViewContext<Self>,
9976 ) -> Task<Result<()>> {
9977 let buffer = self.buffer().clone();
9978 let mut buffers = buffer.read(cx).all_buffers();
9979 if trigger == FormatTrigger::Save {
9980 buffers.retain(|buffer| buffer.read(cx).is_dirty());
9981 }
9982
9983 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
9984 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
9985
9986 cx.spawn(|_, mut cx| async move {
9987 let transaction = futures::select_biased! {
9988 () = timeout => {
9989 log::warn!("timed out waiting for formatting");
9990 None
9991 }
9992 transaction = format.log_err().fuse() => transaction,
9993 };
9994
9995 buffer
9996 .update(&mut cx, |buffer, cx| {
9997 if let Some(transaction) = transaction {
9998 if !buffer.is_singleton() {
9999 buffer.push_transaction(&transaction.0, cx);
10000 }
10001 }
10002
10003 cx.notify();
10004 })
10005 .ok();
10006
10007 Ok(())
10008 })
10009 }
10010
10011 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10012 if let Some(project) = self.project.clone() {
10013 self.buffer.update(cx, |multi_buffer, cx| {
10014 project.update(cx, |project, cx| {
10015 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10016 });
10017 })
10018 }
10019 }
10020
10021 fn cancel_language_server_work(
10022 &mut self,
10023 _: &CancelLanguageServerWork,
10024 cx: &mut ViewContext<Self>,
10025 ) {
10026 if let Some(project) = self.project.clone() {
10027 self.buffer.update(cx, |multi_buffer, cx| {
10028 project.update(cx, |project, cx| {
10029 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10030 });
10031 })
10032 }
10033 }
10034
10035 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10036 cx.show_character_palette();
10037 }
10038
10039 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10040 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10041 let buffer = self.buffer.read(cx).snapshot(cx);
10042 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10043 let is_valid = buffer
10044 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10045 .any(|entry| {
10046 entry.diagnostic.is_primary
10047 && !entry.range.is_empty()
10048 && entry.range.start == primary_range_start
10049 && entry.diagnostic.message == active_diagnostics.primary_message
10050 });
10051
10052 if is_valid != active_diagnostics.is_valid {
10053 active_diagnostics.is_valid = is_valid;
10054 let mut new_styles = HashMap::default();
10055 for (block_id, diagnostic) in &active_diagnostics.blocks {
10056 new_styles.insert(
10057 *block_id,
10058 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10059 );
10060 }
10061 self.display_map.update(cx, |display_map, _cx| {
10062 display_map.replace_blocks(new_styles)
10063 });
10064 }
10065 }
10066 }
10067
10068 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10069 self.dismiss_diagnostics(cx);
10070 let snapshot = self.snapshot(cx);
10071 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10072 let buffer = self.buffer.read(cx).snapshot(cx);
10073
10074 let mut primary_range = None;
10075 let mut primary_message = None;
10076 let mut group_end = Point::zero();
10077 let diagnostic_group = buffer
10078 .diagnostic_group::<MultiBufferPoint>(group_id)
10079 .filter_map(|entry| {
10080 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10081 && (entry.range.start.row == entry.range.end.row
10082 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10083 {
10084 return None;
10085 }
10086 if entry.range.end > group_end {
10087 group_end = entry.range.end;
10088 }
10089 if entry.diagnostic.is_primary {
10090 primary_range = Some(entry.range.clone());
10091 primary_message = Some(entry.diagnostic.message.clone());
10092 }
10093 Some(entry)
10094 })
10095 .collect::<Vec<_>>();
10096 let primary_range = primary_range?;
10097 let primary_message = primary_message?;
10098 let primary_range =
10099 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10100
10101 let blocks = display_map
10102 .insert_blocks(
10103 diagnostic_group.iter().map(|entry| {
10104 let diagnostic = entry.diagnostic.clone();
10105 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10106 BlockProperties {
10107 style: BlockStyle::Fixed,
10108 position: buffer.anchor_after(entry.range.start),
10109 height: message_height,
10110 render: diagnostic_block_renderer(diagnostic, None, true, true),
10111 disposition: BlockDisposition::Below,
10112 priority: 0,
10113 }
10114 }),
10115 cx,
10116 )
10117 .into_iter()
10118 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10119 .collect();
10120
10121 Some(ActiveDiagnosticGroup {
10122 primary_range,
10123 primary_message,
10124 group_id,
10125 blocks,
10126 is_valid: true,
10127 })
10128 });
10129 self.active_diagnostics.is_some()
10130 }
10131
10132 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10133 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10134 self.display_map.update(cx, |display_map, cx| {
10135 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10136 });
10137 cx.notify();
10138 }
10139 }
10140
10141 pub fn set_selections_from_remote(
10142 &mut self,
10143 selections: Vec<Selection<Anchor>>,
10144 pending_selection: Option<Selection<Anchor>>,
10145 cx: &mut ViewContext<Self>,
10146 ) {
10147 let old_cursor_position = self.selections.newest_anchor().head();
10148 self.selections.change_with(cx, |s| {
10149 s.select_anchors(selections);
10150 if let Some(pending_selection) = pending_selection {
10151 s.set_pending(pending_selection, SelectMode::Character);
10152 } else {
10153 s.clear_pending();
10154 }
10155 });
10156 self.selections_did_change(false, &old_cursor_position, true, cx);
10157 }
10158
10159 fn push_to_selection_history(&mut self) {
10160 self.selection_history.push(SelectionHistoryEntry {
10161 selections: self.selections.disjoint_anchors(),
10162 select_next_state: self.select_next_state.clone(),
10163 select_prev_state: self.select_prev_state.clone(),
10164 add_selections_state: self.add_selections_state.clone(),
10165 });
10166 }
10167
10168 pub fn transact(
10169 &mut self,
10170 cx: &mut ViewContext<Self>,
10171 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10172 ) -> Option<TransactionId> {
10173 self.start_transaction_at(Instant::now(), cx);
10174 update(self, cx);
10175 self.end_transaction_at(Instant::now(), cx)
10176 }
10177
10178 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10179 self.end_selection(cx);
10180 if let Some(tx_id) = self
10181 .buffer
10182 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10183 {
10184 self.selection_history
10185 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10186 cx.emit(EditorEvent::TransactionBegun {
10187 transaction_id: tx_id,
10188 })
10189 }
10190 }
10191
10192 fn end_transaction_at(
10193 &mut self,
10194 now: Instant,
10195 cx: &mut ViewContext<Self>,
10196 ) -> Option<TransactionId> {
10197 if let Some(transaction_id) = self
10198 .buffer
10199 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10200 {
10201 if let Some((_, end_selections)) =
10202 self.selection_history.transaction_mut(transaction_id)
10203 {
10204 *end_selections = Some(self.selections.disjoint_anchors());
10205 } else {
10206 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10207 }
10208
10209 cx.emit(EditorEvent::Edited { transaction_id });
10210 Some(transaction_id)
10211 } else {
10212 None
10213 }
10214 }
10215
10216 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10217 let mut fold_ranges = Vec::new();
10218
10219 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10220
10221 let selections = self.selections.all_adjusted(cx);
10222 for selection in selections {
10223 let range = selection.range().sorted();
10224 let buffer_start_row = range.start.row;
10225
10226 for row in (0..=range.end.row).rev() {
10227 if let Some((foldable_range, fold_text)) =
10228 display_map.foldable_range(MultiBufferRow(row))
10229 {
10230 if foldable_range.end.row >= buffer_start_row {
10231 fold_ranges.push((foldable_range, fold_text));
10232 if row <= range.start.row {
10233 break;
10234 }
10235 }
10236 }
10237 }
10238 }
10239
10240 self.fold_ranges(fold_ranges, true, cx);
10241 }
10242
10243 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10244 let buffer_row = fold_at.buffer_row;
10245 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10246
10247 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10248 let autoscroll = self
10249 .selections
10250 .all::<Point>(cx)
10251 .iter()
10252 .any(|selection| fold_range.overlaps(&selection.range()));
10253
10254 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10255 }
10256 }
10257
10258 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10259 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10260 let buffer = &display_map.buffer_snapshot;
10261 let selections = self.selections.all::<Point>(cx);
10262 let ranges = selections
10263 .iter()
10264 .map(|s| {
10265 let range = s.display_range(&display_map).sorted();
10266 let mut start = range.start.to_point(&display_map);
10267 let mut end = range.end.to_point(&display_map);
10268 start.column = 0;
10269 end.column = buffer.line_len(MultiBufferRow(end.row));
10270 start..end
10271 })
10272 .collect::<Vec<_>>();
10273
10274 self.unfold_ranges(ranges, true, true, cx);
10275 }
10276
10277 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10278 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10279
10280 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10281 ..Point::new(
10282 unfold_at.buffer_row.0,
10283 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10284 );
10285
10286 let autoscroll = self
10287 .selections
10288 .all::<Point>(cx)
10289 .iter()
10290 .any(|selection| selection.range().overlaps(&intersection_range));
10291
10292 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10293 }
10294
10295 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10296 let selections = self.selections.all::<Point>(cx);
10297 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10298 let line_mode = self.selections.line_mode;
10299 let ranges = selections.into_iter().map(|s| {
10300 if line_mode {
10301 let start = Point::new(s.start.row, 0);
10302 let end = Point::new(
10303 s.end.row,
10304 display_map
10305 .buffer_snapshot
10306 .line_len(MultiBufferRow(s.end.row)),
10307 );
10308 (start..end, display_map.fold_placeholder.clone())
10309 } else {
10310 (s.start..s.end, display_map.fold_placeholder.clone())
10311 }
10312 });
10313 self.fold_ranges(ranges, true, cx);
10314 }
10315
10316 pub fn fold_ranges<T: ToOffset + Clone>(
10317 &mut self,
10318 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10319 auto_scroll: bool,
10320 cx: &mut ViewContext<Self>,
10321 ) {
10322 let mut fold_ranges = Vec::new();
10323 let mut buffers_affected = HashMap::default();
10324 let multi_buffer = self.buffer().read(cx);
10325 for (fold_range, fold_text) in ranges {
10326 if let Some((_, buffer, _)) =
10327 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10328 {
10329 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10330 };
10331 fold_ranges.push((fold_range, fold_text));
10332 }
10333
10334 let mut ranges = fold_ranges.into_iter().peekable();
10335 if ranges.peek().is_some() {
10336 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10337
10338 if auto_scroll {
10339 self.request_autoscroll(Autoscroll::fit(), cx);
10340 }
10341
10342 for buffer in buffers_affected.into_values() {
10343 self.sync_expanded_diff_hunks(buffer, cx);
10344 }
10345
10346 cx.notify();
10347
10348 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10349 // Clear diagnostics block when folding a range that contains it.
10350 let snapshot = self.snapshot(cx);
10351 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10352 drop(snapshot);
10353 self.active_diagnostics = Some(active_diagnostics);
10354 self.dismiss_diagnostics(cx);
10355 } else {
10356 self.active_diagnostics = Some(active_diagnostics);
10357 }
10358 }
10359
10360 self.scrollbar_marker_state.dirty = true;
10361 }
10362 }
10363
10364 pub fn unfold_ranges<T: ToOffset + Clone>(
10365 &mut self,
10366 ranges: impl IntoIterator<Item = Range<T>>,
10367 inclusive: bool,
10368 auto_scroll: bool,
10369 cx: &mut ViewContext<Self>,
10370 ) {
10371 let mut unfold_ranges = Vec::new();
10372 let mut buffers_affected = HashMap::default();
10373 let multi_buffer = self.buffer().read(cx);
10374 for range in ranges {
10375 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10376 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10377 };
10378 unfold_ranges.push(range);
10379 }
10380
10381 let mut ranges = unfold_ranges.into_iter().peekable();
10382 if ranges.peek().is_some() {
10383 self.display_map
10384 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10385 if auto_scroll {
10386 self.request_autoscroll(Autoscroll::fit(), cx);
10387 }
10388
10389 for buffer in buffers_affected.into_values() {
10390 self.sync_expanded_diff_hunks(buffer, cx);
10391 }
10392
10393 cx.notify();
10394 self.scrollbar_marker_state.dirty = true;
10395 self.active_indent_guides_state.dirty = true;
10396 }
10397 }
10398
10399 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10400 self.display_map.read(cx).fold_placeholder.clone()
10401 }
10402
10403 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10404 if hovered != self.gutter_hovered {
10405 self.gutter_hovered = hovered;
10406 cx.notify();
10407 }
10408 }
10409
10410 pub fn insert_blocks(
10411 &mut self,
10412 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10413 autoscroll: Option<Autoscroll>,
10414 cx: &mut ViewContext<Self>,
10415 ) -> Vec<CustomBlockId> {
10416 let blocks = self
10417 .display_map
10418 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10419 if let Some(autoscroll) = autoscroll {
10420 self.request_autoscroll(autoscroll, cx);
10421 }
10422 cx.notify();
10423 blocks
10424 }
10425
10426 pub fn resize_blocks(
10427 &mut self,
10428 heights: HashMap<CustomBlockId, u32>,
10429 autoscroll: Option<Autoscroll>,
10430 cx: &mut ViewContext<Self>,
10431 ) {
10432 self.display_map
10433 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10434 if let Some(autoscroll) = autoscroll {
10435 self.request_autoscroll(autoscroll, cx);
10436 }
10437 cx.notify();
10438 }
10439
10440 pub fn replace_blocks(
10441 &mut self,
10442 renderers: HashMap<CustomBlockId, RenderBlock>,
10443 autoscroll: Option<Autoscroll>,
10444 cx: &mut ViewContext<Self>,
10445 ) {
10446 self.display_map
10447 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10448 if let Some(autoscroll) = autoscroll {
10449 self.request_autoscroll(autoscroll, cx);
10450 }
10451 cx.notify();
10452 }
10453
10454 pub fn remove_blocks(
10455 &mut self,
10456 block_ids: HashSet<CustomBlockId>,
10457 autoscroll: Option<Autoscroll>,
10458 cx: &mut ViewContext<Self>,
10459 ) {
10460 self.display_map.update(cx, |display_map, cx| {
10461 display_map.remove_blocks(block_ids, cx)
10462 });
10463 if let Some(autoscroll) = autoscroll {
10464 self.request_autoscroll(autoscroll, cx);
10465 }
10466 cx.notify();
10467 }
10468
10469 pub fn row_for_block(
10470 &self,
10471 block_id: CustomBlockId,
10472 cx: &mut ViewContext<Self>,
10473 ) -> Option<DisplayRow> {
10474 self.display_map
10475 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10476 }
10477
10478 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10479 self.focused_block = Some(focused_block);
10480 }
10481
10482 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10483 self.focused_block.take()
10484 }
10485
10486 pub fn insert_creases(
10487 &mut self,
10488 creases: impl IntoIterator<Item = Crease>,
10489 cx: &mut ViewContext<Self>,
10490 ) -> Vec<CreaseId> {
10491 self.display_map
10492 .update(cx, |map, cx| map.insert_creases(creases, cx))
10493 }
10494
10495 pub fn remove_creases(
10496 &mut self,
10497 ids: impl IntoIterator<Item = CreaseId>,
10498 cx: &mut ViewContext<Self>,
10499 ) {
10500 self.display_map
10501 .update(cx, |map, cx| map.remove_creases(ids, cx));
10502 }
10503
10504 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10505 self.display_map
10506 .update(cx, |map, cx| map.snapshot(cx))
10507 .longest_row()
10508 }
10509
10510 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10511 self.display_map
10512 .update(cx, |map, cx| map.snapshot(cx))
10513 .max_point()
10514 }
10515
10516 pub fn text(&self, cx: &AppContext) -> String {
10517 self.buffer.read(cx).read(cx).text()
10518 }
10519
10520 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10521 let text = self.text(cx);
10522 let text = text.trim();
10523
10524 if text.is_empty() {
10525 return None;
10526 }
10527
10528 Some(text.to_string())
10529 }
10530
10531 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10532 self.transact(cx, |this, cx| {
10533 this.buffer
10534 .read(cx)
10535 .as_singleton()
10536 .expect("you can only call set_text on editors for singleton buffers")
10537 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10538 });
10539 }
10540
10541 pub fn display_text(&self, cx: &mut AppContext) -> String {
10542 self.display_map
10543 .update(cx, |map, cx| map.snapshot(cx))
10544 .text()
10545 }
10546
10547 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10548 let mut wrap_guides = smallvec::smallvec![];
10549
10550 if self.show_wrap_guides == Some(false) {
10551 return wrap_guides;
10552 }
10553
10554 let settings = self.buffer.read(cx).settings_at(0, cx);
10555 if settings.show_wrap_guides {
10556 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10557 wrap_guides.push((soft_wrap as usize, true));
10558 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
10559 wrap_guides.push((soft_wrap as usize, true));
10560 }
10561 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10562 }
10563
10564 wrap_guides
10565 }
10566
10567 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10568 let settings = self.buffer.read(cx).settings_at(0, cx);
10569 let mode = self
10570 .soft_wrap_mode_override
10571 .unwrap_or_else(|| settings.soft_wrap);
10572 match mode {
10573 language_settings::SoftWrap::None => SoftWrap::None,
10574 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10575 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10576 language_settings::SoftWrap::PreferredLineLength => {
10577 SoftWrap::Column(settings.preferred_line_length)
10578 }
10579 language_settings::SoftWrap::Bounded => {
10580 SoftWrap::Bounded(settings.preferred_line_length)
10581 }
10582 }
10583 }
10584
10585 pub fn set_soft_wrap_mode(
10586 &mut self,
10587 mode: language_settings::SoftWrap,
10588 cx: &mut ViewContext<Self>,
10589 ) {
10590 self.soft_wrap_mode_override = Some(mode);
10591 cx.notify();
10592 }
10593
10594 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10595 let rem_size = cx.rem_size();
10596 self.display_map.update(cx, |map, cx| {
10597 map.set_font(
10598 style.text.font(),
10599 style.text.font_size.to_pixels(rem_size),
10600 cx,
10601 )
10602 });
10603 self.style = Some(style);
10604 }
10605
10606 pub fn style(&self) -> Option<&EditorStyle> {
10607 self.style.as_ref()
10608 }
10609
10610 // Called by the element. This method is not designed to be called outside of the editor
10611 // element's layout code because it does not notify when rewrapping is computed synchronously.
10612 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10613 self.display_map
10614 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10615 }
10616
10617 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10618 if self.soft_wrap_mode_override.is_some() {
10619 self.soft_wrap_mode_override.take();
10620 } else {
10621 let soft_wrap = match self.soft_wrap_mode(cx) {
10622 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10623 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
10624 language_settings::SoftWrap::PreferLine
10625 }
10626 };
10627 self.soft_wrap_mode_override = Some(soft_wrap);
10628 }
10629 cx.notify();
10630 }
10631
10632 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10633 let Some(workspace) = self.workspace() else {
10634 return;
10635 };
10636 let fs = workspace.read(cx).app_state().fs.clone();
10637 let current_show = TabBarSettings::get_global(cx).show;
10638 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10639 setting.show = Some(!current_show);
10640 });
10641 }
10642
10643 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10644 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10645 self.buffer
10646 .read(cx)
10647 .settings_at(0, cx)
10648 .indent_guides
10649 .enabled
10650 });
10651 self.show_indent_guides = Some(!currently_enabled);
10652 cx.notify();
10653 }
10654
10655 fn should_show_indent_guides(&self) -> Option<bool> {
10656 self.show_indent_guides
10657 }
10658
10659 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10660 let mut editor_settings = EditorSettings::get_global(cx).clone();
10661 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10662 EditorSettings::override_global(editor_settings, cx);
10663 }
10664
10665 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
10666 self.use_relative_line_numbers
10667 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
10668 }
10669
10670 pub fn toggle_relative_line_numbers(
10671 &mut self,
10672 _: &ToggleRelativeLineNumbers,
10673 cx: &mut ViewContext<Self>,
10674 ) {
10675 let is_relative = self.should_use_relative_line_numbers(cx);
10676 self.set_relative_line_number(Some(!is_relative), cx)
10677 }
10678
10679 pub fn set_relative_line_number(
10680 &mut self,
10681 is_relative: Option<bool>,
10682 cx: &mut ViewContext<Self>,
10683 ) {
10684 self.use_relative_line_numbers = is_relative;
10685 cx.notify();
10686 }
10687
10688 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10689 self.show_gutter = show_gutter;
10690 cx.notify();
10691 }
10692
10693 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10694 self.show_line_numbers = Some(show_line_numbers);
10695 cx.notify();
10696 }
10697
10698 pub fn set_show_git_diff_gutter(
10699 &mut self,
10700 show_git_diff_gutter: bool,
10701 cx: &mut ViewContext<Self>,
10702 ) {
10703 self.show_git_diff_gutter = Some(show_git_diff_gutter);
10704 cx.notify();
10705 }
10706
10707 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10708 self.show_code_actions = Some(show_code_actions);
10709 cx.notify();
10710 }
10711
10712 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10713 self.show_runnables = Some(show_runnables);
10714 cx.notify();
10715 }
10716
10717 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
10718 if self.display_map.read(cx).masked != masked {
10719 self.display_map.update(cx, |map, _| map.masked = masked);
10720 }
10721 cx.notify()
10722 }
10723
10724 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10725 self.show_wrap_guides = Some(show_wrap_guides);
10726 cx.notify();
10727 }
10728
10729 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10730 self.show_indent_guides = Some(show_indent_guides);
10731 cx.notify();
10732 }
10733
10734 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10735 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10736 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10737 if let Some(dir) = file.abs_path(cx).parent() {
10738 return Some(dir.to_owned());
10739 }
10740 }
10741
10742 if let Some(project_path) = buffer.read(cx).project_path(cx) {
10743 return Some(project_path.path.to_path_buf());
10744 }
10745 }
10746
10747 None
10748 }
10749
10750 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10751 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10752 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10753 cx.reveal_path(&file.abs_path(cx));
10754 }
10755 }
10756 }
10757
10758 pub fn copy_path(&mut self, _: &CopyPath, 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 if let Some(path) = file.abs_path(cx).to_str() {
10762 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10763 }
10764 }
10765 }
10766 }
10767
10768 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10769 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10770 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10771 if let Some(path) = file.path().to_str() {
10772 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10773 }
10774 }
10775 }
10776 }
10777
10778 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10779 self.show_git_blame_gutter = !self.show_git_blame_gutter;
10780
10781 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10782 self.start_git_blame(true, cx);
10783 }
10784
10785 cx.notify();
10786 }
10787
10788 pub fn toggle_git_blame_inline(
10789 &mut self,
10790 _: &ToggleGitBlameInline,
10791 cx: &mut ViewContext<Self>,
10792 ) {
10793 self.toggle_git_blame_inline_internal(true, cx);
10794 cx.notify();
10795 }
10796
10797 pub fn git_blame_inline_enabled(&self) -> bool {
10798 self.git_blame_inline_enabled
10799 }
10800
10801 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10802 self.show_selection_menu = self
10803 .show_selection_menu
10804 .map(|show_selections_menu| !show_selections_menu)
10805 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10806
10807 cx.notify();
10808 }
10809
10810 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10811 self.show_selection_menu
10812 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10813 }
10814
10815 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10816 if let Some(project) = self.project.as_ref() {
10817 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10818 return;
10819 };
10820
10821 if buffer.read(cx).file().is_none() {
10822 return;
10823 }
10824
10825 let focused = self.focus_handle(cx).contains_focused(cx);
10826
10827 let project = project.clone();
10828 let blame =
10829 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10830 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10831 self.blame = Some(blame);
10832 }
10833 }
10834
10835 fn toggle_git_blame_inline_internal(
10836 &mut self,
10837 user_triggered: bool,
10838 cx: &mut ViewContext<Self>,
10839 ) {
10840 if self.git_blame_inline_enabled {
10841 self.git_blame_inline_enabled = false;
10842 self.show_git_blame_inline = false;
10843 self.show_git_blame_inline_delay_task.take();
10844 } else {
10845 self.git_blame_inline_enabled = true;
10846 self.start_git_blame_inline(user_triggered, cx);
10847 }
10848
10849 cx.notify();
10850 }
10851
10852 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10853 self.start_git_blame(user_triggered, cx);
10854
10855 if ProjectSettings::get_global(cx)
10856 .git
10857 .inline_blame_delay()
10858 .is_some()
10859 {
10860 self.start_inline_blame_timer(cx);
10861 } else {
10862 self.show_git_blame_inline = true
10863 }
10864 }
10865
10866 pub fn blame(&self) -> Option<&Model<GitBlame>> {
10867 self.blame.as_ref()
10868 }
10869
10870 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10871 self.show_git_blame_gutter && self.has_blame_entries(cx)
10872 }
10873
10874 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10875 self.show_git_blame_inline
10876 && self.focus_handle.is_focused(cx)
10877 && !self.newest_selection_head_on_empty_line(cx)
10878 && self.has_blame_entries(cx)
10879 }
10880
10881 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10882 self.blame()
10883 .map_or(false, |blame| blame.read(cx).has_generated_entries())
10884 }
10885
10886 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10887 let cursor_anchor = self.selections.newest_anchor().head();
10888
10889 let snapshot = self.buffer.read(cx).snapshot(cx);
10890 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10891
10892 snapshot.line_len(buffer_row) == 0
10893 }
10894
10895 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10896 let (path, selection, repo) = maybe!({
10897 let project_handle = self.project.as_ref()?.clone();
10898 let project = project_handle.read(cx);
10899
10900 let selection = self.selections.newest::<Point>(cx);
10901 let selection_range = selection.range();
10902
10903 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10904 (buffer, selection_range.start.row..selection_range.end.row)
10905 } else {
10906 let buffer_ranges = self
10907 .buffer()
10908 .read(cx)
10909 .range_to_buffer_ranges(selection_range, cx);
10910
10911 let (buffer, range, _) = if selection.reversed {
10912 buffer_ranges.first()
10913 } else {
10914 buffer_ranges.last()
10915 }?;
10916
10917 let snapshot = buffer.read(cx).snapshot();
10918 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10919 ..text::ToPoint::to_point(&range.end, &snapshot).row;
10920 (buffer.clone(), selection)
10921 };
10922
10923 let path = buffer
10924 .read(cx)
10925 .file()?
10926 .as_local()?
10927 .path()
10928 .to_str()?
10929 .to_string();
10930 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10931 Some((path, selection, repo))
10932 })
10933 .ok_or_else(|| anyhow!("unable to open git repository"))?;
10934
10935 const REMOTE_NAME: &str = "origin";
10936 let origin_url = repo
10937 .remote_url(REMOTE_NAME)
10938 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10939 let sha = repo
10940 .head_sha()
10941 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10942
10943 let (provider, remote) =
10944 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10945 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10946
10947 Ok(provider.build_permalink(
10948 remote,
10949 BuildPermalinkParams {
10950 sha: &sha,
10951 path: &path,
10952 selection: Some(selection),
10953 },
10954 ))
10955 }
10956
10957 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10958 let permalink = self.get_permalink_to_line(cx);
10959
10960 match permalink {
10961 Ok(permalink) => {
10962 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
10963 }
10964 Err(err) => {
10965 let message = format!("Failed to copy permalink: {err}");
10966
10967 Err::<(), anyhow::Error>(err).log_err();
10968
10969 if let Some(workspace) = self.workspace() {
10970 workspace.update(cx, |workspace, cx| {
10971 struct CopyPermalinkToLine;
10972
10973 workspace.show_toast(
10974 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10975 cx,
10976 )
10977 })
10978 }
10979 }
10980 }
10981 }
10982
10983 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
10984 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10985 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10986 if let Some(path) = file.path().to_str() {
10987 let selection = self.selections.newest::<Point>(cx).start.row + 1;
10988 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
10989 }
10990 }
10991 }
10992 }
10993
10994 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10995 let permalink = self.get_permalink_to_line(cx);
10996
10997 match permalink {
10998 Ok(permalink) => {
10999 cx.open_url(permalink.as_ref());
11000 }
11001 Err(err) => {
11002 let message = format!("Failed to open permalink: {err}");
11003
11004 Err::<(), anyhow::Error>(err).log_err();
11005
11006 if let Some(workspace) = self.workspace() {
11007 workspace.update(cx, |workspace, cx| {
11008 struct OpenPermalinkToLine;
11009
11010 workspace.show_toast(
11011 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11012 cx,
11013 )
11014 })
11015 }
11016 }
11017 }
11018 }
11019
11020 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
11021 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
11022 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
11023 pub fn highlight_rows<T: 'static>(
11024 &mut self,
11025 rows: RangeInclusive<Anchor>,
11026 color: Option<Hsla>,
11027 should_autoscroll: bool,
11028 cx: &mut ViewContext<Self>,
11029 ) {
11030 let snapshot = self.buffer().read(cx).snapshot(cx);
11031 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11032 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
11033 highlight
11034 .range
11035 .start()
11036 .cmp(&rows.start(), &snapshot)
11037 .then(highlight.range.end().cmp(&rows.end(), &snapshot))
11038 });
11039 match (color, existing_highlight_index) {
11040 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
11041 ix,
11042 RowHighlight {
11043 index: post_inc(&mut self.highlight_order),
11044 range: rows,
11045 should_autoscroll,
11046 color,
11047 },
11048 ),
11049 (None, Ok(i)) => {
11050 row_highlights.remove(i);
11051 }
11052 }
11053 }
11054
11055 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11056 pub fn clear_row_highlights<T: 'static>(&mut self) {
11057 self.highlighted_rows.remove(&TypeId::of::<T>());
11058 }
11059
11060 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11061 pub fn highlighted_rows<T: 'static>(
11062 &self,
11063 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
11064 Some(
11065 self.highlighted_rows
11066 .get(&TypeId::of::<T>())?
11067 .iter()
11068 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
11069 )
11070 }
11071
11072 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11073 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11074 /// Allows to ignore certain kinds of highlights.
11075 pub fn highlighted_display_rows(
11076 &mut self,
11077 cx: &mut WindowContext,
11078 ) -> BTreeMap<DisplayRow, Hsla> {
11079 let snapshot = self.snapshot(cx);
11080 let mut used_highlight_orders = HashMap::default();
11081 self.highlighted_rows
11082 .iter()
11083 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11084 .fold(
11085 BTreeMap::<DisplayRow, Hsla>::new(),
11086 |mut unique_rows, highlight| {
11087 let start_row = highlight.range.start().to_display_point(&snapshot).row();
11088 let end_row = highlight.range.end().to_display_point(&snapshot).row();
11089 for row in start_row.0..=end_row.0 {
11090 let used_index =
11091 used_highlight_orders.entry(row).or_insert(highlight.index);
11092 if highlight.index >= *used_index {
11093 *used_index = highlight.index;
11094 match highlight.color {
11095 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
11096 None => unique_rows.remove(&DisplayRow(row)),
11097 };
11098 }
11099 }
11100 unique_rows
11101 },
11102 )
11103 }
11104
11105 pub fn highlighted_display_row_for_autoscroll(
11106 &self,
11107 snapshot: &DisplaySnapshot,
11108 ) -> Option<DisplayRow> {
11109 self.highlighted_rows
11110 .values()
11111 .flat_map(|highlighted_rows| highlighted_rows.iter())
11112 .filter_map(|highlight| {
11113 if highlight.color.is_none() || !highlight.should_autoscroll {
11114 return None;
11115 }
11116 Some(highlight.range.start().to_display_point(&snapshot).row())
11117 })
11118 .min()
11119 }
11120
11121 pub fn set_search_within_ranges(
11122 &mut self,
11123 ranges: &[Range<Anchor>],
11124 cx: &mut ViewContext<Self>,
11125 ) {
11126 self.highlight_background::<SearchWithinRange>(
11127 ranges,
11128 |colors| colors.editor_document_highlight_read_background,
11129 cx,
11130 )
11131 }
11132
11133 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11134 self.breadcrumb_header = Some(new_header);
11135 }
11136
11137 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11138 self.clear_background_highlights::<SearchWithinRange>(cx);
11139 }
11140
11141 pub fn highlight_background<T: 'static>(
11142 &mut self,
11143 ranges: &[Range<Anchor>],
11144 color_fetcher: fn(&ThemeColors) -> Hsla,
11145 cx: &mut ViewContext<Self>,
11146 ) {
11147 self.background_highlights
11148 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11149 self.scrollbar_marker_state.dirty = true;
11150 cx.notify();
11151 }
11152
11153 pub fn clear_background_highlights<T: 'static>(
11154 &mut self,
11155 cx: &mut ViewContext<Self>,
11156 ) -> Option<BackgroundHighlight> {
11157 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11158 if !text_highlights.1.is_empty() {
11159 self.scrollbar_marker_state.dirty = true;
11160 cx.notify();
11161 }
11162 Some(text_highlights)
11163 }
11164
11165 pub fn highlight_gutter<T: 'static>(
11166 &mut self,
11167 ranges: &[Range<Anchor>],
11168 color_fetcher: fn(&AppContext) -> Hsla,
11169 cx: &mut ViewContext<Self>,
11170 ) {
11171 self.gutter_highlights
11172 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11173 cx.notify();
11174 }
11175
11176 pub fn clear_gutter_highlights<T: 'static>(
11177 &mut self,
11178 cx: &mut ViewContext<Self>,
11179 ) -> Option<GutterHighlight> {
11180 cx.notify();
11181 self.gutter_highlights.remove(&TypeId::of::<T>())
11182 }
11183
11184 #[cfg(feature = "test-support")]
11185 pub fn all_text_background_highlights(
11186 &mut self,
11187 cx: &mut ViewContext<Self>,
11188 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11189 let snapshot = self.snapshot(cx);
11190 let buffer = &snapshot.buffer_snapshot;
11191 let start = buffer.anchor_before(0);
11192 let end = buffer.anchor_after(buffer.len());
11193 let theme = cx.theme().colors();
11194 self.background_highlights_in_range(start..end, &snapshot, theme)
11195 }
11196
11197 #[cfg(feature = "test-support")]
11198 pub fn search_background_highlights(
11199 &mut self,
11200 cx: &mut ViewContext<Self>,
11201 ) -> Vec<Range<Point>> {
11202 let snapshot = self.buffer().read(cx).snapshot(cx);
11203
11204 let highlights = self
11205 .background_highlights
11206 .get(&TypeId::of::<items::BufferSearchHighlights>());
11207
11208 if let Some((_color, ranges)) = highlights {
11209 ranges
11210 .iter()
11211 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11212 .collect_vec()
11213 } else {
11214 vec![]
11215 }
11216 }
11217
11218 fn document_highlights_for_position<'a>(
11219 &'a self,
11220 position: Anchor,
11221 buffer: &'a MultiBufferSnapshot,
11222 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
11223 let read_highlights = self
11224 .background_highlights
11225 .get(&TypeId::of::<DocumentHighlightRead>())
11226 .map(|h| &h.1);
11227 let write_highlights = self
11228 .background_highlights
11229 .get(&TypeId::of::<DocumentHighlightWrite>())
11230 .map(|h| &h.1);
11231 let left_position = position.bias_left(buffer);
11232 let right_position = position.bias_right(buffer);
11233 read_highlights
11234 .into_iter()
11235 .chain(write_highlights)
11236 .flat_map(move |ranges| {
11237 let start_ix = match ranges.binary_search_by(|probe| {
11238 let cmp = probe.end.cmp(&left_position, buffer);
11239 if cmp.is_ge() {
11240 Ordering::Greater
11241 } else {
11242 Ordering::Less
11243 }
11244 }) {
11245 Ok(i) | Err(i) => i,
11246 };
11247
11248 ranges[start_ix..]
11249 .iter()
11250 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11251 })
11252 }
11253
11254 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11255 self.background_highlights
11256 .get(&TypeId::of::<T>())
11257 .map_or(false, |(_, highlights)| !highlights.is_empty())
11258 }
11259
11260 pub fn background_highlights_in_range(
11261 &self,
11262 search_range: Range<Anchor>,
11263 display_snapshot: &DisplaySnapshot,
11264 theme: &ThemeColors,
11265 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11266 let mut results = Vec::new();
11267 for (color_fetcher, ranges) in self.background_highlights.values() {
11268 let color = color_fetcher(theme);
11269 let start_ix = match ranges.binary_search_by(|probe| {
11270 let cmp = probe
11271 .end
11272 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11273 if cmp.is_gt() {
11274 Ordering::Greater
11275 } else {
11276 Ordering::Less
11277 }
11278 }) {
11279 Ok(i) | Err(i) => i,
11280 };
11281 for range in &ranges[start_ix..] {
11282 if range
11283 .start
11284 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11285 .is_ge()
11286 {
11287 break;
11288 }
11289
11290 let start = range.start.to_display_point(&display_snapshot);
11291 let end = range.end.to_display_point(&display_snapshot);
11292 results.push((start..end, color))
11293 }
11294 }
11295 results
11296 }
11297
11298 pub fn background_highlight_row_ranges<T: 'static>(
11299 &self,
11300 search_range: Range<Anchor>,
11301 display_snapshot: &DisplaySnapshot,
11302 count: usize,
11303 ) -> Vec<RangeInclusive<DisplayPoint>> {
11304 let mut results = Vec::new();
11305 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11306 return vec![];
11307 };
11308
11309 let start_ix = match ranges.binary_search_by(|probe| {
11310 let cmp = probe
11311 .end
11312 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11313 if cmp.is_gt() {
11314 Ordering::Greater
11315 } else {
11316 Ordering::Less
11317 }
11318 }) {
11319 Ok(i) | Err(i) => i,
11320 };
11321 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11322 if let (Some(start_display), Some(end_display)) = (start, end) {
11323 results.push(
11324 start_display.to_display_point(display_snapshot)
11325 ..=end_display.to_display_point(display_snapshot),
11326 );
11327 }
11328 };
11329 let mut start_row: Option<Point> = None;
11330 let mut end_row: Option<Point> = None;
11331 if ranges.len() > count {
11332 return Vec::new();
11333 }
11334 for range in &ranges[start_ix..] {
11335 if range
11336 .start
11337 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11338 .is_ge()
11339 {
11340 break;
11341 }
11342 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11343 if let Some(current_row) = &end_row {
11344 if end.row == current_row.row {
11345 continue;
11346 }
11347 }
11348 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11349 if start_row.is_none() {
11350 assert_eq!(end_row, None);
11351 start_row = Some(start);
11352 end_row = Some(end);
11353 continue;
11354 }
11355 if let Some(current_end) = end_row.as_mut() {
11356 if start.row > current_end.row + 1 {
11357 push_region(start_row, end_row);
11358 start_row = Some(start);
11359 end_row = Some(end);
11360 } else {
11361 // Merge two hunks.
11362 *current_end = end;
11363 }
11364 } else {
11365 unreachable!();
11366 }
11367 }
11368 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11369 push_region(start_row, end_row);
11370 results
11371 }
11372
11373 pub fn gutter_highlights_in_range(
11374 &self,
11375 search_range: Range<Anchor>,
11376 display_snapshot: &DisplaySnapshot,
11377 cx: &AppContext,
11378 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11379 let mut results = Vec::new();
11380 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11381 let color = color_fetcher(cx);
11382 let start_ix = match ranges.binary_search_by(|probe| {
11383 let cmp = probe
11384 .end
11385 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11386 if cmp.is_gt() {
11387 Ordering::Greater
11388 } else {
11389 Ordering::Less
11390 }
11391 }) {
11392 Ok(i) | Err(i) => i,
11393 };
11394 for range in &ranges[start_ix..] {
11395 if range
11396 .start
11397 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11398 .is_ge()
11399 {
11400 break;
11401 }
11402
11403 let start = range.start.to_display_point(&display_snapshot);
11404 let end = range.end.to_display_point(&display_snapshot);
11405 results.push((start..end, color))
11406 }
11407 }
11408 results
11409 }
11410
11411 /// Get the text ranges corresponding to the redaction query
11412 pub fn redacted_ranges(
11413 &self,
11414 search_range: Range<Anchor>,
11415 display_snapshot: &DisplaySnapshot,
11416 cx: &WindowContext,
11417 ) -> Vec<Range<DisplayPoint>> {
11418 display_snapshot
11419 .buffer_snapshot
11420 .redacted_ranges(search_range, |file| {
11421 if let Some(file) = file {
11422 file.is_private()
11423 && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
11424 } else {
11425 false
11426 }
11427 })
11428 .map(|range| {
11429 range.start.to_display_point(display_snapshot)
11430 ..range.end.to_display_point(display_snapshot)
11431 })
11432 .collect()
11433 }
11434
11435 pub fn highlight_text<T: 'static>(
11436 &mut self,
11437 ranges: Vec<Range<Anchor>>,
11438 style: HighlightStyle,
11439 cx: &mut ViewContext<Self>,
11440 ) {
11441 self.display_map.update(cx, |map, _| {
11442 map.highlight_text(TypeId::of::<T>(), ranges, style)
11443 });
11444 cx.notify();
11445 }
11446
11447 pub(crate) fn highlight_inlays<T: 'static>(
11448 &mut self,
11449 highlights: Vec<InlayHighlight>,
11450 style: HighlightStyle,
11451 cx: &mut ViewContext<Self>,
11452 ) {
11453 self.display_map.update(cx, |map, _| {
11454 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11455 });
11456 cx.notify();
11457 }
11458
11459 pub fn text_highlights<'a, T: 'static>(
11460 &'a self,
11461 cx: &'a AppContext,
11462 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11463 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11464 }
11465
11466 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11467 let cleared = self
11468 .display_map
11469 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11470 if cleared {
11471 cx.notify();
11472 }
11473 }
11474
11475 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11476 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11477 && self.focus_handle.is_focused(cx)
11478 }
11479
11480 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11481 self.show_cursor_when_unfocused = is_enabled;
11482 cx.notify();
11483 }
11484
11485 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11486 cx.notify();
11487 }
11488
11489 fn on_buffer_event(
11490 &mut self,
11491 multibuffer: Model<MultiBuffer>,
11492 event: &multi_buffer::Event,
11493 cx: &mut ViewContext<Self>,
11494 ) {
11495 match event {
11496 multi_buffer::Event::Edited {
11497 singleton_buffer_edited,
11498 } => {
11499 self.scrollbar_marker_state.dirty = true;
11500 self.active_indent_guides_state.dirty = true;
11501 self.refresh_active_diagnostics(cx);
11502 self.refresh_code_actions(cx);
11503 if self.has_active_inline_completion(cx) {
11504 self.update_visible_inline_completion(cx);
11505 }
11506 cx.emit(EditorEvent::BufferEdited);
11507 cx.emit(SearchEvent::MatchesInvalidated);
11508 if *singleton_buffer_edited {
11509 if let Some(project) = &self.project {
11510 let project = project.read(cx);
11511 #[allow(clippy::mutable_key_type)]
11512 let languages_affected = multibuffer
11513 .read(cx)
11514 .all_buffers()
11515 .into_iter()
11516 .filter_map(|buffer| {
11517 let buffer = buffer.read(cx);
11518 let language = buffer.language()?;
11519 if project.is_local_or_ssh()
11520 && project.language_servers_for_buffer(buffer, cx).count() == 0
11521 {
11522 None
11523 } else {
11524 Some(language)
11525 }
11526 })
11527 .cloned()
11528 .collect::<HashSet<_>>();
11529 if !languages_affected.is_empty() {
11530 self.refresh_inlay_hints(
11531 InlayHintRefreshReason::BufferEdited(languages_affected),
11532 cx,
11533 );
11534 }
11535 }
11536 }
11537
11538 let Some(project) = &self.project else { return };
11539 let telemetry = project.read(cx).client().telemetry().clone();
11540 refresh_linked_ranges(self, cx);
11541 telemetry.log_edit_event("editor");
11542 }
11543 multi_buffer::Event::ExcerptsAdded {
11544 buffer,
11545 predecessor,
11546 excerpts,
11547 } => {
11548 self.tasks_update_task = Some(self.refresh_runnables(cx));
11549 cx.emit(EditorEvent::ExcerptsAdded {
11550 buffer: buffer.clone(),
11551 predecessor: *predecessor,
11552 excerpts: excerpts.clone(),
11553 });
11554 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11555 }
11556 multi_buffer::Event::ExcerptsRemoved { ids } => {
11557 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11558 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11559 }
11560 multi_buffer::Event::ExcerptsEdited { ids } => {
11561 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11562 }
11563 multi_buffer::Event::ExcerptsExpanded { ids } => {
11564 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11565 }
11566 multi_buffer::Event::Reparsed(buffer_id) => {
11567 self.tasks_update_task = Some(self.refresh_runnables(cx));
11568
11569 cx.emit(EditorEvent::Reparsed(*buffer_id));
11570 }
11571 multi_buffer::Event::LanguageChanged(buffer_id) => {
11572 linked_editing_ranges::refresh_linked_ranges(self, cx);
11573 cx.emit(EditorEvent::Reparsed(*buffer_id));
11574 cx.notify();
11575 }
11576 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11577 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11578 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11579 cx.emit(EditorEvent::TitleChanged)
11580 }
11581 multi_buffer::Event::DiffBaseChanged => {
11582 self.scrollbar_marker_state.dirty = true;
11583 cx.emit(EditorEvent::DiffBaseChanged);
11584 cx.notify();
11585 }
11586 multi_buffer::Event::DiffUpdated { buffer } => {
11587 self.sync_expanded_diff_hunks(buffer.clone(), cx);
11588 cx.notify();
11589 }
11590 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11591 multi_buffer::Event::DiagnosticsUpdated => {
11592 self.refresh_active_diagnostics(cx);
11593 self.scrollbar_marker_state.dirty = true;
11594 cx.notify();
11595 }
11596 _ => {}
11597 };
11598 }
11599
11600 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11601 cx.notify();
11602 }
11603
11604 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11605 self.tasks_update_task = Some(self.refresh_runnables(cx));
11606 self.refresh_inline_completion(true, false, cx);
11607 self.refresh_inlay_hints(
11608 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11609 self.selections.newest_anchor().head(),
11610 &self.buffer.read(cx).snapshot(cx),
11611 cx,
11612 )),
11613 cx,
11614 );
11615 let editor_settings = EditorSettings::get_global(cx);
11616 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11617 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11618
11619 let project_settings = ProjectSettings::get_global(cx);
11620 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11621
11622 if self.mode == EditorMode::Full {
11623 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11624 if self.git_blame_inline_enabled != inline_blame_enabled {
11625 self.toggle_git_blame_inline_internal(false, cx);
11626 }
11627 }
11628
11629 cx.notify();
11630 }
11631
11632 pub fn set_searchable(&mut self, searchable: bool) {
11633 self.searchable = searchable;
11634 }
11635
11636 pub fn searchable(&self) -> bool {
11637 self.searchable
11638 }
11639
11640 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11641 self.open_excerpts_common(true, cx)
11642 }
11643
11644 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11645 self.open_excerpts_common(false, cx)
11646 }
11647
11648 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11649 let buffer = self.buffer.read(cx);
11650 if buffer.is_singleton() {
11651 cx.propagate();
11652 return;
11653 }
11654
11655 let Some(workspace) = self.workspace() else {
11656 cx.propagate();
11657 return;
11658 };
11659
11660 let mut new_selections_by_buffer = HashMap::default();
11661 for selection in self.selections.all::<usize>(cx) {
11662 for (buffer, mut range, _) in
11663 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11664 {
11665 if selection.reversed {
11666 mem::swap(&mut range.start, &mut range.end);
11667 }
11668 new_selections_by_buffer
11669 .entry(buffer)
11670 .or_insert(Vec::new())
11671 .push(range)
11672 }
11673 }
11674
11675 // We defer the pane interaction because we ourselves are a workspace item
11676 // and activating a new item causes the pane to call a method on us reentrantly,
11677 // which panics if we're on the stack.
11678 cx.window_context().defer(move |cx| {
11679 workspace.update(cx, |workspace, cx| {
11680 let pane = if split {
11681 workspace.adjacent_pane(cx)
11682 } else {
11683 workspace.active_pane().clone()
11684 };
11685
11686 for (buffer, ranges) in new_selections_by_buffer {
11687 let editor =
11688 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
11689 editor.update(cx, |editor, cx| {
11690 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11691 s.select_ranges(ranges);
11692 });
11693 });
11694 }
11695 })
11696 });
11697 }
11698
11699 fn jump(
11700 &mut self,
11701 path: ProjectPath,
11702 position: Point,
11703 anchor: language::Anchor,
11704 offset_from_top: u32,
11705 cx: &mut ViewContext<Self>,
11706 ) {
11707 let workspace = self.workspace();
11708 cx.spawn(|_, mut cx| async move {
11709 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11710 let editor = workspace.update(&mut cx, |workspace, cx| {
11711 // Reset the preview item id before opening the new item
11712 workspace.active_pane().update(cx, |pane, cx| {
11713 pane.set_preview_item_id(None, cx);
11714 });
11715 workspace.open_path_preview(path, None, true, true, cx)
11716 })?;
11717 let editor = editor
11718 .await?
11719 .downcast::<Editor>()
11720 .ok_or_else(|| anyhow!("opened item was not an editor"))?
11721 .downgrade();
11722 editor.update(&mut cx, |editor, cx| {
11723 let buffer = editor
11724 .buffer()
11725 .read(cx)
11726 .as_singleton()
11727 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11728 let buffer = buffer.read(cx);
11729 let cursor = if buffer.can_resolve(&anchor) {
11730 language::ToPoint::to_point(&anchor, buffer)
11731 } else {
11732 buffer.clip_point(position, Bias::Left)
11733 };
11734
11735 let nav_history = editor.nav_history.take();
11736 editor.change_selections(
11737 Some(Autoscroll::top_relative(offset_from_top as usize)),
11738 cx,
11739 |s| {
11740 s.select_ranges([cursor..cursor]);
11741 },
11742 );
11743 editor.nav_history = nav_history;
11744
11745 anyhow::Ok(())
11746 })??;
11747
11748 anyhow::Ok(())
11749 })
11750 .detach_and_log_err(cx);
11751 }
11752
11753 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11754 let snapshot = self.buffer.read(cx).read(cx);
11755 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11756 Some(
11757 ranges
11758 .iter()
11759 .map(move |range| {
11760 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11761 })
11762 .collect(),
11763 )
11764 }
11765
11766 fn selection_replacement_ranges(
11767 &self,
11768 range: Range<OffsetUtf16>,
11769 cx: &AppContext,
11770 ) -> Vec<Range<OffsetUtf16>> {
11771 let selections = self.selections.all::<OffsetUtf16>(cx);
11772 let newest_selection = selections
11773 .iter()
11774 .max_by_key(|selection| selection.id)
11775 .unwrap();
11776 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11777 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11778 let snapshot = self.buffer.read(cx).read(cx);
11779 selections
11780 .into_iter()
11781 .map(|mut selection| {
11782 selection.start.0 =
11783 (selection.start.0 as isize).saturating_add(start_delta) as usize;
11784 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11785 snapshot.clip_offset_utf16(selection.start, Bias::Left)
11786 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11787 })
11788 .collect()
11789 }
11790
11791 fn report_editor_event(
11792 &self,
11793 operation: &'static str,
11794 file_extension: Option<String>,
11795 cx: &AppContext,
11796 ) {
11797 if cfg!(any(test, feature = "test-support")) {
11798 return;
11799 }
11800
11801 let Some(project) = &self.project else { return };
11802
11803 // If None, we are in a file without an extension
11804 let file = self
11805 .buffer
11806 .read(cx)
11807 .as_singleton()
11808 .and_then(|b| b.read(cx).file());
11809 let file_extension = file_extension.or(file
11810 .as_ref()
11811 .and_then(|file| Path::new(file.file_name(cx)).extension())
11812 .and_then(|e| e.to_str())
11813 .map(|a| a.to_string()));
11814
11815 let vim_mode = cx
11816 .global::<SettingsStore>()
11817 .raw_user_settings()
11818 .get("vim_mode")
11819 == Some(&serde_json::Value::Bool(true));
11820
11821 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11822 == language::language_settings::InlineCompletionProvider::Copilot;
11823 let copilot_enabled_for_language = self
11824 .buffer
11825 .read(cx)
11826 .settings_at(0, cx)
11827 .show_inline_completions;
11828
11829 let telemetry = project.read(cx).client().telemetry().clone();
11830 telemetry.report_editor_event(
11831 file_extension,
11832 vim_mode,
11833 operation,
11834 copilot_enabled,
11835 copilot_enabled_for_language,
11836 )
11837 }
11838
11839 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11840 /// with each line being an array of {text, highlight} objects.
11841 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11842 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11843 return;
11844 };
11845
11846 #[derive(Serialize)]
11847 struct Chunk<'a> {
11848 text: String,
11849 highlight: Option<&'a str>,
11850 }
11851
11852 let snapshot = buffer.read(cx).snapshot();
11853 let range = self
11854 .selected_text_range(false, cx)
11855 .and_then(|selection| {
11856 if selection.range.is_empty() {
11857 None
11858 } else {
11859 Some(selection.range)
11860 }
11861 })
11862 .unwrap_or_else(|| 0..snapshot.len());
11863
11864 let chunks = snapshot.chunks(range, true);
11865 let mut lines = Vec::new();
11866 let mut line: VecDeque<Chunk> = VecDeque::new();
11867
11868 let Some(style) = self.style.as_ref() else {
11869 return;
11870 };
11871
11872 for chunk in chunks {
11873 let highlight = chunk
11874 .syntax_highlight_id
11875 .and_then(|id| id.name(&style.syntax));
11876 let mut chunk_lines = chunk.text.split('\n').peekable();
11877 while let Some(text) = chunk_lines.next() {
11878 let mut merged_with_last_token = false;
11879 if let Some(last_token) = line.back_mut() {
11880 if last_token.highlight == highlight {
11881 last_token.text.push_str(text);
11882 merged_with_last_token = true;
11883 }
11884 }
11885
11886 if !merged_with_last_token {
11887 line.push_back(Chunk {
11888 text: text.into(),
11889 highlight,
11890 });
11891 }
11892
11893 if chunk_lines.peek().is_some() {
11894 if line.len() > 1 && line.front().unwrap().text.is_empty() {
11895 line.pop_front();
11896 }
11897 if line.len() > 1 && line.back().unwrap().text.is_empty() {
11898 line.pop_back();
11899 }
11900
11901 lines.push(mem::take(&mut line));
11902 }
11903 }
11904 }
11905
11906 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11907 return;
11908 };
11909 cx.write_to_clipboard(ClipboardItem::new_string(lines));
11910 }
11911
11912 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11913 &self.inlay_hint_cache
11914 }
11915
11916 pub fn replay_insert_event(
11917 &mut self,
11918 text: &str,
11919 relative_utf16_range: Option<Range<isize>>,
11920 cx: &mut ViewContext<Self>,
11921 ) {
11922 if !self.input_enabled {
11923 cx.emit(EditorEvent::InputIgnored { text: text.into() });
11924 return;
11925 }
11926 if let Some(relative_utf16_range) = relative_utf16_range {
11927 let selections = self.selections.all::<OffsetUtf16>(cx);
11928 self.change_selections(None, cx, |s| {
11929 let new_ranges = selections.into_iter().map(|range| {
11930 let start = OffsetUtf16(
11931 range
11932 .head()
11933 .0
11934 .saturating_add_signed(relative_utf16_range.start),
11935 );
11936 let end = OffsetUtf16(
11937 range
11938 .head()
11939 .0
11940 .saturating_add_signed(relative_utf16_range.end),
11941 );
11942 start..end
11943 });
11944 s.select_ranges(new_ranges);
11945 });
11946 }
11947
11948 self.handle_input(text, cx);
11949 }
11950
11951 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11952 let Some(project) = self.project.as_ref() else {
11953 return false;
11954 };
11955 let project = project.read(cx);
11956
11957 let mut supports = false;
11958 self.buffer().read(cx).for_each_buffer(|buffer| {
11959 if !supports {
11960 supports = project
11961 .language_servers_for_buffer(buffer.read(cx), cx)
11962 .any(
11963 |(_, server)| match server.capabilities().inlay_hint_provider {
11964 Some(lsp::OneOf::Left(enabled)) => enabled,
11965 Some(lsp::OneOf::Right(_)) => true,
11966 None => false,
11967 },
11968 )
11969 }
11970 });
11971 supports
11972 }
11973
11974 pub fn focus(&self, cx: &mut WindowContext) {
11975 cx.focus(&self.focus_handle)
11976 }
11977
11978 pub fn is_focused(&self, cx: &WindowContext) -> bool {
11979 self.focus_handle.is_focused(cx)
11980 }
11981
11982 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11983 cx.emit(EditorEvent::Focused);
11984
11985 if let Some(descendant) = self
11986 .last_focused_descendant
11987 .take()
11988 .and_then(|descendant| descendant.upgrade())
11989 {
11990 cx.focus(&descendant);
11991 } else {
11992 if let Some(blame) = self.blame.as_ref() {
11993 blame.update(cx, GitBlame::focus)
11994 }
11995
11996 self.blink_manager.update(cx, BlinkManager::enable);
11997 self.show_cursor_names(cx);
11998 self.buffer.update(cx, |buffer, cx| {
11999 buffer.finalize_last_transaction(cx);
12000 if self.leader_peer_id.is_none() {
12001 buffer.set_active_selections(
12002 &self.selections.disjoint_anchors(),
12003 self.selections.line_mode,
12004 self.cursor_shape,
12005 cx,
12006 );
12007 }
12008 });
12009 }
12010 }
12011
12012 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12013 cx.emit(EditorEvent::FocusedIn)
12014 }
12015
12016 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12017 if event.blurred != self.focus_handle {
12018 self.last_focused_descendant = Some(event.blurred);
12019 }
12020 }
12021
12022 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12023 self.blink_manager.update(cx, BlinkManager::disable);
12024 self.buffer
12025 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12026
12027 if let Some(blame) = self.blame.as_ref() {
12028 blame.update(cx, GitBlame::blur)
12029 }
12030 if !self.hover_state.focused(cx) {
12031 hide_hover(self, cx);
12032 }
12033
12034 self.hide_context_menu(cx);
12035 cx.emit(EditorEvent::Blurred);
12036 cx.notify();
12037 }
12038
12039 pub fn register_action<A: Action>(
12040 &mut self,
12041 listener: impl Fn(&A, &mut WindowContext) + 'static,
12042 ) -> Subscription {
12043 let id = self.next_editor_action_id.post_inc();
12044 let listener = Arc::new(listener);
12045 self.editor_actions.borrow_mut().insert(
12046 id,
12047 Box::new(move |cx| {
12048 let cx = cx.window_context();
12049 let listener = listener.clone();
12050 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12051 let action = action.downcast_ref().unwrap();
12052 if phase == DispatchPhase::Bubble {
12053 listener(action, cx)
12054 }
12055 })
12056 }),
12057 );
12058
12059 let editor_actions = self.editor_actions.clone();
12060 Subscription::new(move || {
12061 editor_actions.borrow_mut().remove(&id);
12062 })
12063 }
12064
12065 pub fn file_header_size(&self) -> u32 {
12066 self.file_header_size
12067 }
12068
12069 pub fn revert(
12070 &mut self,
12071 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12072 cx: &mut ViewContext<Self>,
12073 ) {
12074 self.buffer().update(cx, |multi_buffer, cx| {
12075 for (buffer_id, changes) in revert_changes {
12076 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12077 buffer.update(cx, |buffer, cx| {
12078 buffer.edit(
12079 changes.into_iter().map(|(range, text)| {
12080 (range, text.to_string().map(Arc::<str>::from))
12081 }),
12082 None,
12083 cx,
12084 );
12085 });
12086 }
12087 }
12088 });
12089 self.change_selections(None, cx, |selections| selections.refresh());
12090 }
12091
12092 pub fn to_pixel_point(
12093 &mut self,
12094 source: multi_buffer::Anchor,
12095 editor_snapshot: &EditorSnapshot,
12096 cx: &mut ViewContext<Self>,
12097 ) -> Option<gpui::Point<Pixels>> {
12098 let source_point = source.to_display_point(editor_snapshot);
12099 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12100 }
12101
12102 pub fn display_to_pixel_point(
12103 &mut self,
12104 source: DisplayPoint,
12105 editor_snapshot: &EditorSnapshot,
12106 cx: &mut ViewContext<Self>,
12107 ) -> Option<gpui::Point<Pixels>> {
12108 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12109 let text_layout_details = self.text_layout_details(cx);
12110 let scroll_top = text_layout_details
12111 .scroll_anchor
12112 .scroll_position(editor_snapshot)
12113 .y;
12114
12115 if source.row().as_f32() < scroll_top.floor() {
12116 return None;
12117 }
12118 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12119 let source_y = line_height * (source.row().as_f32() - scroll_top);
12120 Some(gpui::Point::new(source_x, source_y))
12121 }
12122
12123 fn gutter_bounds(&self) -> Option<Bounds<Pixels>> {
12124 let bounds = self.last_bounds?;
12125 Some(element::gutter_bounds(bounds, self.gutter_dimensions))
12126 }
12127
12128 pub fn has_active_completions_menu(&self) -> bool {
12129 self.context_menu.read().as_ref().map_or(false, |menu| {
12130 menu.visible() && matches!(menu, ContextMenu::Completions(_))
12131 })
12132 }
12133
12134 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12135 self.addons
12136 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12137 }
12138
12139 pub fn unregister_addon<T: Addon>(&mut self) {
12140 self.addons.remove(&std::any::TypeId::of::<T>());
12141 }
12142
12143 pub fn addon<T: Addon>(&self) -> Option<&T> {
12144 let type_id = std::any::TypeId::of::<T>();
12145 self.addons
12146 .get(&type_id)
12147 .and_then(|item| item.to_any().downcast_ref::<T>())
12148 }
12149}
12150
12151fn hunks_for_selections(
12152 multi_buffer_snapshot: &MultiBufferSnapshot,
12153 selections: &[Selection<Anchor>],
12154) -> Vec<DiffHunk<MultiBufferRow>> {
12155 let buffer_rows_for_selections = selections.iter().map(|selection| {
12156 let head = selection.head();
12157 let tail = selection.tail();
12158 let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
12159 let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
12160 if start > end {
12161 end..start
12162 } else {
12163 start..end
12164 }
12165 });
12166
12167 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12168}
12169
12170pub fn hunks_for_rows(
12171 rows: impl Iterator<Item = Range<MultiBufferRow>>,
12172 multi_buffer_snapshot: &MultiBufferSnapshot,
12173) -> Vec<DiffHunk<MultiBufferRow>> {
12174 let mut hunks = Vec::new();
12175 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12176 HashMap::default();
12177 for selected_multi_buffer_rows in rows {
12178 let query_rows =
12179 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12180 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12181 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12182 // when the caret is just above or just below the deleted hunk.
12183 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12184 let related_to_selection = if allow_adjacent {
12185 hunk.associated_range.overlaps(&query_rows)
12186 || hunk.associated_range.start == query_rows.end
12187 || hunk.associated_range.end == query_rows.start
12188 } else {
12189 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12190 // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12191 hunk.associated_range.overlaps(&selected_multi_buffer_rows)
12192 || selected_multi_buffer_rows.end == hunk.associated_range.start
12193 };
12194 if related_to_selection {
12195 if !processed_buffer_rows
12196 .entry(hunk.buffer_id)
12197 .or_default()
12198 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12199 {
12200 continue;
12201 }
12202 hunks.push(hunk);
12203 }
12204 }
12205 }
12206
12207 hunks
12208}
12209
12210pub trait CollaborationHub {
12211 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12212 fn user_participant_indices<'a>(
12213 &self,
12214 cx: &'a AppContext,
12215 ) -> &'a HashMap<u64, ParticipantIndex>;
12216 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12217}
12218
12219impl CollaborationHub for Model<Project> {
12220 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12221 self.read(cx).collaborators()
12222 }
12223
12224 fn user_participant_indices<'a>(
12225 &self,
12226 cx: &'a AppContext,
12227 ) -> &'a HashMap<u64, ParticipantIndex> {
12228 self.read(cx).user_store().read(cx).participant_indices()
12229 }
12230
12231 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12232 let this = self.read(cx);
12233 let user_ids = this.collaborators().values().map(|c| c.user_id);
12234 this.user_store().read_with(cx, |user_store, cx| {
12235 user_store.participant_names(user_ids, cx)
12236 })
12237 }
12238}
12239
12240pub trait CompletionProvider {
12241 fn completions(
12242 &self,
12243 buffer: &Model<Buffer>,
12244 buffer_position: text::Anchor,
12245 trigger: CompletionContext,
12246 cx: &mut ViewContext<Editor>,
12247 ) -> Task<Result<Vec<Completion>>>;
12248
12249 fn resolve_completions(
12250 &self,
12251 buffer: Model<Buffer>,
12252 completion_indices: Vec<usize>,
12253 completions: Arc<RwLock<Box<[Completion]>>>,
12254 cx: &mut ViewContext<Editor>,
12255 ) -> Task<Result<bool>>;
12256
12257 fn apply_additional_edits_for_completion(
12258 &self,
12259 buffer: Model<Buffer>,
12260 completion: Completion,
12261 push_to_history: bool,
12262 cx: &mut ViewContext<Editor>,
12263 ) -> Task<Result<Option<language::Transaction>>>;
12264
12265 fn is_completion_trigger(
12266 &self,
12267 buffer: &Model<Buffer>,
12268 position: language::Anchor,
12269 text: &str,
12270 trigger_in_words: bool,
12271 cx: &mut ViewContext<Editor>,
12272 ) -> bool;
12273
12274 fn sort_completions(&self) -> bool {
12275 true
12276 }
12277}
12278
12279fn snippet_completions(
12280 project: &Project,
12281 buffer: &Model<Buffer>,
12282 buffer_position: text::Anchor,
12283 cx: &mut AppContext,
12284) -> Vec<Completion> {
12285 let language = buffer.read(cx).language_at(buffer_position);
12286 let language_name = language.as_ref().map(|language| language.lsp_id());
12287 let snippet_store = project.snippets().read(cx);
12288 let snippets = snippet_store.snippets_for(language_name, cx);
12289
12290 if snippets.is_empty() {
12291 return vec![];
12292 }
12293 let snapshot = buffer.read(cx).text_snapshot();
12294 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12295
12296 let mut lines = chunks.lines();
12297 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12298 return vec![];
12299 };
12300
12301 let scope = language.map(|language| language.default_scope());
12302 let mut last_word = line_at
12303 .chars()
12304 .rev()
12305 .take_while(|c| char_kind(&scope, *c) == CharKind::Word)
12306 .collect::<String>();
12307 last_word = last_word.chars().rev().collect();
12308 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12309 let to_lsp = |point: &text::Anchor| {
12310 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12311 point_to_lsp(end)
12312 };
12313 let lsp_end = to_lsp(&buffer_position);
12314 snippets
12315 .into_iter()
12316 .filter_map(|snippet| {
12317 let matching_prefix = snippet
12318 .prefix
12319 .iter()
12320 .find(|prefix| prefix.starts_with(&last_word))?;
12321 let start = as_offset - last_word.len();
12322 let start = snapshot.anchor_before(start);
12323 let range = start..buffer_position;
12324 let lsp_start = to_lsp(&start);
12325 let lsp_range = lsp::Range {
12326 start: lsp_start,
12327 end: lsp_end,
12328 };
12329 Some(Completion {
12330 old_range: range,
12331 new_text: snippet.body.clone(),
12332 label: CodeLabel {
12333 text: matching_prefix.clone(),
12334 runs: vec![],
12335 filter_range: 0..matching_prefix.len(),
12336 },
12337 server_id: LanguageServerId(usize::MAX),
12338 documentation: snippet
12339 .description
12340 .clone()
12341 .map(|description| Documentation::SingleLine(description)),
12342 lsp_completion: lsp::CompletionItem {
12343 label: snippet.prefix.first().unwrap().clone(),
12344 kind: Some(CompletionItemKind::SNIPPET),
12345 label_details: snippet.description.as_ref().map(|description| {
12346 lsp::CompletionItemLabelDetails {
12347 detail: Some(description.clone()),
12348 description: None,
12349 }
12350 }),
12351 insert_text_format: Some(InsertTextFormat::SNIPPET),
12352 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12353 lsp::InsertReplaceEdit {
12354 new_text: snippet.body.clone(),
12355 insert: lsp_range,
12356 replace: lsp_range,
12357 },
12358 )),
12359 filter_text: Some(snippet.body.clone()),
12360 sort_text: Some(char::MAX.to_string()),
12361 ..Default::default()
12362 },
12363 confirm: None,
12364 })
12365 })
12366 .collect()
12367}
12368
12369impl CompletionProvider for Model<Project> {
12370 fn completions(
12371 &self,
12372 buffer: &Model<Buffer>,
12373 buffer_position: text::Anchor,
12374 options: CompletionContext,
12375 cx: &mut ViewContext<Editor>,
12376 ) -> Task<Result<Vec<Completion>>> {
12377 self.update(cx, |project, cx| {
12378 let snippets = snippet_completions(project, buffer, buffer_position, cx);
12379 let project_completions = project.completions(&buffer, buffer_position, options, cx);
12380 cx.background_executor().spawn(async move {
12381 let mut completions = project_completions.await?;
12382 //let snippets = snippets.into_iter().;
12383 completions.extend(snippets);
12384 Ok(completions)
12385 })
12386 })
12387 }
12388
12389 fn resolve_completions(
12390 &self,
12391 buffer: Model<Buffer>,
12392 completion_indices: Vec<usize>,
12393 completions: Arc<RwLock<Box<[Completion]>>>,
12394 cx: &mut ViewContext<Editor>,
12395 ) -> Task<Result<bool>> {
12396 self.update(cx, |project, cx| {
12397 project.resolve_completions(buffer, completion_indices, completions, cx)
12398 })
12399 }
12400
12401 fn apply_additional_edits_for_completion(
12402 &self,
12403 buffer: Model<Buffer>,
12404 completion: Completion,
12405 push_to_history: bool,
12406 cx: &mut ViewContext<Editor>,
12407 ) -> Task<Result<Option<language::Transaction>>> {
12408 self.update(cx, |project, cx| {
12409 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12410 })
12411 }
12412
12413 fn is_completion_trigger(
12414 &self,
12415 buffer: &Model<Buffer>,
12416 position: language::Anchor,
12417 text: &str,
12418 trigger_in_words: bool,
12419 cx: &mut ViewContext<Editor>,
12420 ) -> bool {
12421 if !EditorSettings::get_global(cx).show_completions_on_input {
12422 return false;
12423 }
12424
12425 let mut chars = text.chars();
12426 let char = if let Some(char) = chars.next() {
12427 char
12428 } else {
12429 return false;
12430 };
12431 if chars.next().is_some() {
12432 return false;
12433 }
12434
12435 let buffer = buffer.read(cx);
12436 let scope = buffer.snapshot().language_scope_at(position);
12437 if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
12438 return true;
12439 }
12440
12441 buffer
12442 .completion_triggers()
12443 .iter()
12444 .any(|string| string == text)
12445 }
12446}
12447
12448fn inlay_hint_settings(
12449 location: Anchor,
12450 snapshot: &MultiBufferSnapshot,
12451 cx: &mut ViewContext<'_, Editor>,
12452) -> InlayHintSettings {
12453 let file = snapshot.file_at(location);
12454 let language = snapshot.language_at(location);
12455 let settings = all_language_settings(file, cx);
12456 settings
12457 .language(language.map(|l| l.name()).as_deref())
12458 .inlay_hints
12459}
12460
12461fn consume_contiguous_rows(
12462 contiguous_row_selections: &mut Vec<Selection<Point>>,
12463 selection: &Selection<Point>,
12464 display_map: &DisplaySnapshot,
12465 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12466) -> (MultiBufferRow, MultiBufferRow) {
12467 contiguous_row_selections.push(selection.clone());
12468 let start_row = MultiBufferRow(selection.start.row);
12469 let mut end_row = ending_row(selection, display_map);
12470
12471 while let Some(next_selection) = selections.peek() {
12472 if next_selection.start.row <= end_row.0 {
12473 end_row = ending_row(next_selection, display_map);
12474 contiguous_row_selections.push(selections.next().unwrap().clone());
12475 } else {
12476 break;
12477 }
12478 }
12479 (start_row, end_row)
12480}
12481
12482fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12483 if next_selection.end.column > 0 || next_selection.is_empty() {
12484 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12485 } else {
12486 MultiBufferRow(next_selection.end.row)
12487 }
12488}
12489
12490impl EditorSnapshot {
12491 pub fn remote_selections_in_range<'a>(
12492 &'a self,
12493 range: &'a Range<Anchor>,
12494 collaboration_hub: &dyn CollaborationHub,
12495 cx: &'a AppContext,
12496 ) -> impl 'a + Iterator<Item = RemoteSelection> {
12497 let participant_names = collaboration_hub.user_names(cx);
12498 let participant_indices = collaboration_hub.user_participant_indices(cx);
12499 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12500 let collaborators_by_replica_id = collaborators_by_peer_id
12501 .iter()
12502 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12503 .collect::<HashMap<_, _>>();
12504 self.buffer_snapshot
12505 .selections_in_range(range, false)
12506 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12507 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12508 let participant_index = participant_indices.get(&collaborator.user_id).copied();
12509 let user_name = participant_names.get(&collaborator.user_id).cloned();
12510 Some(RemoteSelection {
12511 replica_id,
12512 selection,
12513 cursor_shape,
12514 line_mode,
12515 participant_index,
12516 peer_id: collaborator.peer_id,
12517 user_name,
12518 })
12519 })
12520 }
12521
12522 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12523 self.display_snapshot.buffer_snapshot.language_at(position)
12524 }
12525
12526 pub fn is_focused(&self) -> bool {
12527 self.is_focused
12528 }
12529
12530 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12531 self.placeholder_text.as_ref()
12532 }
12533
12534 pub fn scroll_position(&self) -> gpui::Point<f32> {
12535 self.scroll_anchor.scroll_position(&self.display_snapshot)
12536 }
12537
12538 fn gutter_dimensions(
12539 &self,
12540 font_id: FontId,
12541 font_size: Pixels,
12542 em_width: Pixels,
12543 max_line_number_width: Pixels,
12544 cx: &AppContext,
12545 ) -> GutterDimensions {
12546 if !self.show_gutter {
12547 return GutterDimensions::default();
12548 }
12549 let descent = cx.text_system().descent(font_id, font_size);
12550
12551 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12552 matches!(
12553 ProjectSettings::get_global(cx).git.git_gutter,
12554 Some(GitGutterSetting::TrackedFiles)
12555 )
12556 });
12557 let gutter_settings = EditorSettings::get_global(cx).gutter;
12558 let show_line_numbers = self
12559 .show_line_numbers
12560 .unwrap_or(gutter_settings.line_numbers);
12561 let line_gutter_width = if show_line_numbers {
12562 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12563 let min_width_for_number_on_gutter = em_width * 4.0;
12564 max_line_number_width.max(min_width_for_number_on_gutter)
12565 } else {
12566 0.0.into()
12567 };
12568
12569 let show_code_actions = self
12570 .show_code_actions
12571 .unwrap_or(gutter_settings.code_actions);
12572
12573 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12574
12575 let git_blame_entries_width = self
12576 .render_git_blame_gutter
12577 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12578
12579 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12580 left_padding += if show_code_actions || show_runnables {
12581 em_width * 3.0
12582 } else if show_git_gutter && show_line_numbers {
12583 em_width * 2.0
12584 } else if show_git_gutter || show_line_numbers {
12585 em_width
12586 } else {
12587 px(0.)
12588 };
12589
12590 let right_padding = if gutter_settings.folds && show_line_numbers {
12591 em_width * 4.0
12592 } else if gutter_settings.folds {
12593 em_width * 3.0
12594 } else if show_line_numbers {
12595 em_width
12596 } else {
12597 px(0.)
12598 };
12599
12600 GutterDimensions {
12601 left_padding,
12602 right_padding,
12603 width: line_gutter_width + left_padding + right_padding,
12604 margin: -descent,
12605 git_blame_entries_width,
12606 }
12607 }
12608
12609 pub fn render_fold_toggle(
12610 &self,
12611 buffer_row: MultiBufferRow,
12612 row_contains_cursor: bool,
12613 editor: View<Editor>,
12614 cx: &mut WindowContext,
12615 ) -> Option<AnyElement> {
12616 let folded = self.is_line_folded(buffer_row);
12617
12618 if let Some(crease) = self
12619 .crease_snapshot
12620 .query_row(buffer_row, &self.buffer_snapshot)
12621 {
12622 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12623 if folded {
12624 editor.update(cx, |editor, cx| {
12625 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12626 });
12627 } else {
12628 editor.update(cx, |editor, cx| {
12629 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12630 });
12631 }
12632 });
12633
12634 Some((crease.render_toggle)(
12635 buffer_row,
12636 folded,
12637 toggle_callback,
12638 cx,
12639 ))
12640 } else if folded
12641 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12642 {
12643 Some(
12644 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12645 .selected(folded)
12646 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12647 if folded {
12648 this.unfold_at(&UnfoldAt { buffer_row }, cx);
12649 } else {
12650 this.fold_at(&FoldAt { buffer_row }, cx);
12651 }
12652 }))
12653 .into_any_element(),
12654 )
12655 } else {
12656 None
12657 }
12658 }
12659
12660 pub fn render_crease_trailer(
12661 &self,
12662 buffer_row: MultiBufferRow,
12663 cx: &mut WindowContext,
12664 ) -> Option<AnyElement> {
12665 let folded = self.is_line_folded(buffer_row);
12666 let crease = self
12667 .crease_snapshot
12668 .query_row(buffer_row, &self.buffer_snapshot)?;
12669 Some((crease.render_trailer)(buffer_row, folded, cx))
12670 }
12671}
12672
12673impl Deref for EditorSnapshot {
12674 type Target = DisplaySnapshot;
12675
12676 fn deref(&self) -> &Self::Target {
12677 &self.display_snapshot
12678 }
12679}
12680
12681#[derive(Clone, Debug, PartialEq, Eq)]
12682pub enum EditorEvent {
12683 InputIgnored {
12684 text: Arc<str>,
12685 },
12686 InputHandled {
12687 utf16_range_to_replace: Option<Range<isize>>,
12688 text: Arc<str>,
12689 },
12690 ExcerptsAdded {
12691 buffer: Model<Buffer>,
12692 predecessor: ExcerptId,
12693 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12694 },
12695 ExcerptsRemoved {
12696 ids: Vec<ExcerptId>,
12697 },
12698 ExcerptsEdited {
12699 ids: Vec<ExcerptId>,
12700 },
12701 ExcerptsExpanded {
12702 ids: Vec<ExcerptId>,
12703 },
12704 BufferEdited,
12705 Edited {
12706 transaction_id: clock::Lamport,
12707 },
12708 Reparsed(BufferId),
12709 Focused,
12710 FocusedIn,
12711 Blurred,
12712 DirtyChanged,
12713 Saved,
12714 TitleChanged,
12715 DiffBaseChanged,
12716 SelectionsChanged {
12717 local: bool,
12718 },
12719 ScrollPositionChanged {
12720 local: bool,
12721 autoscroll: bool,
12722 },
12723 Closed,
12724 TransactionUndone {
12725 transaction_id: clock::Lamport,
12726 },
12727 TransactionBegun {
12728 transaction_id: clock::Lamport,
12729 },
12730}
12731
12732impl EventEmitter<EditorEvent> for Editor {}
12733
12734impl FocusableView for Editor {
12735 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12736 self.focus_handle.clone()
12737 }
12738}
12739
12740impl Render for Editor {
12741 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12742 let settings = ThemeSettings::get_global(cx);
12743
12744 let text_style = match self.mode {
12745 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12746 color: cx.theme().colors().editor_foreground,
12747 font_family: settings.ui_font.family.clone(),
12748 font_features: settings.ui_font.features.clone(),
12749 font_fallbacks: settings.ui_font.fallbacks.clone(),
12750 font_size: rems(0.875).into(),
12751 font_weight: settings.ui_font.weight,
12752 line_height: relative(settings.buffer_line_height.value()),
12753 ..Default::default()
12754 },
12755 EditorMode::Full => TextStyle {
12756 color: cx.theme().colors().editor_foreground,
12757 font_family: settings.buffer_font.family.clone(),
12758 font_features: settings.buffer_font.features.clone(),
12759 font_fallbacks: settings.buffer_font.fallbacks.clone(),
12760 font_size: settings.buffer_font_size(cx).into(),
12761 font_weight: settings.buffer_font.weight,
12762 line_height: relative(settings.buffer_line_height.value()),
12763 ..Default::default()
12764 },
12765 };
12766
12767 let background = match self.mode {
12768 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12769 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12770 EditorMode::Full => cx.theme().colors().editor_background,
12771 };
12772
12773 EditorElement::new(
12774 cx.view(),
12775 EditorStyle {
12776 background,
12777 local_player: cx.theme().players().local(),
12778 text: text_style,
12779 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12780 syntax: cx.theme().syntax().clone(),
12781 status: cx.theme().status().clone(),
12782 inlay_hints_style: HighlightStyle {
12783 color: Some(cx.theme().status().hint),
12784 ..HighlightStyle::default()
12785 },
12786 suggestions_style: HighlightStyle {
12787 color: Some(cx.theme().status().predictive),
12788 ..HighlightStyle::default()
12789 },
12790 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
12791 },
12792 )
12793 }
12794}
12795
12796impl ViewInputHandler for Editor {
12797 fn text_for_range(
12798 &mut self,
12799 range_utf16: Range<usize>,
12800 cx: &mut ViewContext<Self>,
12801 ) -> Option<String> {
12802 Some(
12803 self.buffer
12804 .read(cx)
12805 .read(cx)
12806 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12807 .collect(),
12808 )
12809 }
12810
12811 fn selected_text_range(
12812 &mut self,
12813 ignore_disabled_input: bool,
12814 cx: &mut ViewContext<Self>,
12815 ) -> Option<UTF16Selection> {
12816 // Prevent the IME menu from appearing when holding down an alphabetic key
12817 // while input is disabled.
12818 if !ignore_disabled_input && !self.input_enabled {
12819 return None;
12820 }
12821
12822 let selection = self.selections.newest::<OffsetUtf16>(cx);
12823 let range = selection.range();
12824
12825 Some(UTF16Selection {
12826 range: range.start.0..range.end.0,
12827 reversed: selection.reversed,
12828 })
12829 }
12830
12831 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12832 let snapshot = self.buffer.read(cx).read(cx);
12833 let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
12834 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12835 }
12836
12837 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12838 self.clear_highlights::<InputComposition>(cx);
12839 self.ime_transaction.take();
12840 }
12841
12842 fn replace_text_in_range(
12843 &mut self,
12844 range_utf16: Option<Range<usize>>,
12845 text: &str,
12846 cx: &mut ViewContext<Self>,
12847 ) {
12848 if !self.input_enabled {
12849 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12850 return;
12851 }
12852
12853 self.transact(cx, |this, cx| {
12854 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12855 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12856 Some(this.selection_replacement_ranges(range_utf16, cx))
12857 } else {
12858 this.marked_text_ranges(cx)
12859 };
12860
12861 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12862 let newest_selection_id = this.selections.newest_anchor().id;
12863 this.selections
12864 .all::<OffsetUtf16>(cx)
12865 .iter()
12866 .zip(ranges_to_replace.iter())
12867 .find_map(|(selection, range)| {
12868 if selection.id == newest_selection_id {
12869 Some(
12870 (range.start.0 as isize - selection.head().0 as isize)
12871 ..(range.end.0 as isize - selection.head().0 as isize),
12872 )
12873 } else {
12874 None
12875 }
12876 })
12877 });
12878
12879 cx.emit(EditorEvent::InputHandled {
12880 utf16_range_to_replace: range_to_replace,
12881 text: text.into(),
12882 });
12883
12884 if let Some(new_selected_ranges) = new_selected_ranges {
12885 this.change_selections(None, cx, |selections| {
12886 selections.select_ranges(new_selected_ranges)
12887 });
12888 this.backspace(&Default::default(), cx);
12889 }
12890
12891 this.handle_input(text, cx);
12892 });
12893
12894 if let Some(transaction) = self.ime_transaction {
12895 self.buffer.update(cx, |buffer, cx| {
12896 buffer.group_until_transaction(transaction, cx);
12897 });
12898 }
12899
12900 self.unmark_text(cx);
12901 }
12902
12903 fn replace_and_mark_text_in_range(
12904 &mut self,
12905 range_utf16: Option<Range<usize>>,
12906 text: &str,
12907 new_selected_range_utf16: Option<Range<usize>>,
12908 cx: &mut ViewContext<Self>,
12909 ) {
12910 if !self.input_enabled {
12911 return;
12912 }
12913
12914 let transaction = self.transact(cx, |this, cx| {
12915 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12916 let snapshot = this.buffer.read(cx).read(cx);
12917 if let Some(relative_range_utf16) = range_utf16.as_ref() {
12918 for marked_range in &mut marked_ranges {
12919 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12920 marked_range.start.0 += relative_range_utf16.start;
12921 marked_range.start =
12922 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12923 marked_range.end =
12924 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12925 }
12926 }
12927 Some(marked_ranges)
12928 } else if let Some(range_utf16) = range_utf16 {
12929 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12930 Some(this.selection_replacement_ranges(range_utf16, cx))
12931 } else {
12932 None
12933 };
12934
12935 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12936 let newest_selection_id = this.selections.newest_anchor().id;
12937 this.selections
12938 .all::<OffsetUtf16>(cx)
12939 .iter()
12940 .zip(ranges_to_replace.iter())
12941 .find_map(|(selection, range)| {
12942 if selection.id == newest_selection_id {
12943 Some(
12944 (range.start.0 as isize - selection.head().0 as isize)
12945 ..(range.end.0 as isize - selection.head().0 as isize),
12946 )
12947 } else {
12948 None
12949 }
12950 })
12951 });
12952
12953 cx.emit(EditorEvent::InputHandled {
12954 utf16_range_to_replace: range_to_replace,
12955 text: text.into(),
12956 });
12957
12958 if let Some(ranges) = ranges_to_replace {
12959 this.change_selections(None, cx, |s| s.select_ranges(ranges));
12960 }
12961
12962 let marked_ranges = {
12963 let snapshot = this.buffer.read(cx).read(cx);
12964 this.selections
12965 .disjoint_anchors()
12966 .iter()
12967 .map(|selection| {
12968 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12969 })
12970 .collect::<Vec<_>>()
12971 };
12972
12973 if text.is_empty() {
12974 this.unmark_text(cx);
12975 } else {
12976 this.highlight_text::<InputComposition>(
12977 marked_ranges.clone(),
12978 HighlightStyle {
12979 underline: Some(UnderlineStyle {
12980 thickness: px(1.),
12981 color: None,
12982 wavy: false,
12983 }),
12984 ..Default::default()
12985 },
12986 cx,
12987 );
12988 }
12989
12990 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12991 let use_autoclose = this.use_autoclose;
12992 let use_auto_surround = this.use_auto_surround;
12993 this.set_use_autoclose(false);
12994 this.set_use_auto_surround(false);
12995 this.handle_input(text, cx);
12996 this.set_use_autoclose(use_autoclose);
12997 this.set_use_auto_surround(use_auto_surround);
12998
12999 if let Some(new_selected_range) = new_selected_range_utf16 {
13000 let snapshot = this.buffer.read(cx).read(cx);
13001 let new_selected_ranges = marked_ranges
13002 .into_iter()
13003 .map(|marked_range| {
13004 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13005 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13006 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13007 snapshot.clip_offset_utf16(new_start, Bias::Left)
13008 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13009 })
13010 .collect::<Vec<_>>();
13011
13012 drop(snapshot);
13013 this.change_selections(None, cx, |selections| {
13014 selections.select_ranges(new_selected_ranges)
13015 });
13016 }
13017 });
13018
13019 self.ime_transaction = self.ime_transaction.or(transaction);
13020 if let Some(transaction) = self.ime_transaction {
13021 self.buffer.update(cx, |buffer, cx| {
13022 buffer.group_until_transaction(transaction, cx);
13023 });
13024 }
13025
13026 if self.text_highlights::<InputComposition>(cx).is_none() {
13027 self.ime_transaction.take();
13028 }
13029 }
13030
13031 fn bounds_for_range(
13032 &mut self,
13033 range_utf16: Range<usize>,
13034 element_bounds: gpui::Bounds<Pixels>,
13035 cx: &mut ViewContext<Self>,
13036 ) -> Option<gpui::Bounds<Pixels>> {
13037 let text_layout_details = self.text_layout_details(cx);
13038 let style = &text_layout_details.editor_style;
13039 let font_id = cx.text_system().resolve_font(&style.text.font());
13040 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13041 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13042
13043 let em_width = cx
13044 .text_system()
13045 .typographic_bounds(font_id, font_size, 'm')
13046 .unwrap()
13047 .size
13048 .width;
13049
13050 let snapshot = self.snapshot(cx);
13051 let scroll_position = snapshot.scroll_position();
13052 let scroll_left = scroll_position.x * em_width;
13053
13054 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13055 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13056 + self.gutter_dimensions.width;
13057 let y = line_height * (start.row().as_f32() - scroll_position.y);
13058
13059 Some(Bounds {
13060 origin: element_bounds.origin + point(x, y),
13061 size: size(em_width, line_height),
13062 })
13063 }
13064}
13065
13066trait SelectionExt {
13067 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13068 fn spanned_rows(
13069 &self,
13070 include_end_if_at_line_start: bool,
13071 map: &DisplaySnapshot,
13072 ) -> Range<MultiBufferRow>;
13073}
13074
13075impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
13076 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
13077 let start = self
13078 .start
13079 .to_point(&map.buffer_snapshot)
13080 .to_display_point(map);
13081 let end = self
13082 .end
13083 .to_point(&map.buffer_snapshot)
13084 .to_display_point(map);
13085 if self.reversed {
13086 end..start
13087 } else {
13088 start..end
13089 }
13090 }
13091
13092 fn spanned_rows(
13093 &self,
13094 include_end_if_at_line_start: bool,
13095 map: &DisplaySnapshot,
13096 ) -> Range<MultiBufferRow> {
13097 let start = self.start.to_point(&map.buffer_snapshot);
13098 let mut end = self.end.to_point(&map.buffer_snapshot);
13099 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
13100 end.row -= 1;
13101 }
13102
13103 let buffer_start = map.prev_line_boundary(start).0;
13104 let buffer_end = map.next_line_boundary(end).0;
13105 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
13106 }
13107}
13108
13109impl<T: InvalidationRegion> InvalidationStack<T> {
13110 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
13111 where
13112 S: Clone + ToOffset,
13113 {
13114 while let Some(region) = self.last() {
13115 let all_selections_inside_invalidation_ranges =
13116 if selections.len() == region.ranges().len() {
13117 selections
13118 .iter()
13119 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
13120 .all(|(selection, invalidation_range)| {
13121 let head = selection.head().to_offset(buffer);
13122 invalidation_range.start <= head && invalidation_range.end >= head
13123 })
13124 } else {
13125 false
13126 };
13127
13128 if all_selections_inside_invalidation_ranges {
13129 break;
13130 } else {
13131 self.pop();
13132 }
13133 }
13134 }
13135}
13136
13137impl<T> Default for InvalidationStack<T> {
13138 fn default() -> Self {
13139 Self(Default::default())
13140 }
13141}
13142
13143impl<T> Deref for InvalidationStack<T> {
13144 type Target = Vec<T>;
13145
13146 fn deref(&self) -> &Self::Target {
13147 &self.0
13148 }
13149}
13150
13151impl<T> DerefMut for InvalidationStack<T> {
13152 fn deref_mut(&mut self) -> &mut Self::Target {
13153 &mut self.0
13154 }
13155}
13156
13157impl InvalidationRegion for SnippetState {
13158 fn ranges(&self) -> &[Range<Anchor>] {
13159 &self.ranges[self.active_index]
13160 }
13161}
13162
13163pub fn diagnostic_block_renderer(
13164 diagnostic: Diagnostic,
13165 max_message_rows: Option<u8>,
13166 allow_closing: bool,
13167 _is_valid: bool,
13168) -> RenderBlock {
13169 let (text_without_backticks, code_ranges) =
13170 highlight_diagnostic_message(&diagnostic, max_message_rows);
13171
13172 Box::new(move |cx: &mut BlockContext| {
13173 let group_id: SharedString = cx.block_id.to_string().into();
13174
13175 let mut text_style = cx.text_style().clone();
13176 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13177 let theme_settings = ThemeSettings::get_global(cx);
13178 text_style.font_family = theme_settings.buffer_font.family.clone();
13179 text_style.font_style = theme_settings.buffer_font.style;
13180 text_style.font_features = theme_settings.buffer_font.features.clone();
13181 text_style.font_weight = theme_settings.buffer_font.weight;
13182
13183 let multi_line_diagnostic = diagnostic.message.contains('\n');
13184
13185 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13186 if multi_line_diagnostic {
13187 v_flex()
13188 } else {
13189 h_flex()
13190 }
13191 .when(allow_closing, |div| {
13192 div.children(diagnostic.is_primary.then(|| {
13193 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13194 .icon_color(Color::Muted)
13195 .size(ButtonSize::Compact)
13196 .style(ButtonStyle::Transparent)
13197 .visible_on_hover(group_id.clone())
13198 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13199 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13200 }))
13201 })
13202 .child(
13203 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13204 .icon_color(Color::Muted)
13205 .size(ButtonSize::Compact)
13206 .style(ButtonStyle::Transparent)
13207 .visible_on_hover(group_id.clone())
13208 .on_click({
13209 let message = diagnostic.message.clone();
13210 move |_click, cx| {
13211 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13212 }
13213 })
13214 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13215 )
13216 };
13217
13218 let icon_size = buttons(&diagnostic, cx.block_id)
13219 .into_any_element()
13220 .layout_as_root(AvailableSpace::min_size(), cx);
13221
13222 h_flex()
13223 .id(cx.block_id)
13224 .group(group_id.clone())
13225 .relative()
13226 .size_full()
13227 .pl(cx.gutter_dimensions.width)
13228 .w(cx.max_width + cx.gutter_dimensions.width)
13229 .child(
13230 div()
13231 .flex()
13232 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13233 .flex_shrink(),
13234 )
13235 .child(buttons(&diagnostic, cx.block_id))
13236 .child(div().flex().flex_shrink_0().child(
13237 StyledText::new(text_without_backticks.clone()).with_highlights(
13238 &text_style,
13239 code_ranges.iter().map(|range| {
13240 (
13241 range.clone(),
13242 HighlightStyle {
13243 font_weight: Some(FontWeight::BOLD),
13244 ..Default::default()
13245 },
13246 )
13247 }),
13248 ),
13249 ))
13250 .into_any_element()
13251 })
13252}
13253
13254pub fn highlight_diagnostic_message(
13255 diagnostic: &Diagnostic,
13256 mut max_message_rows: Option<u8>,
13257) -> (SharedString, Vec<Range<usize>>) {
13258 let mut text_without_backticks = String::new();
13259 let mut code_ranges = Vec::new();
13260
13261 if let Some(source) = &diagnostic.source {
13262 text_without_backticks.push_str(&source);
13263 code_ranges.push(0..source.len());
13264 text_without_backticks.push_str(": ");
13265 }
13266
13267 let mut prev_offset = 0;
13268 let mut in_code_block = false;
13269 let has_row_limit = max_message_rows.is_some();
13270 let mut newline_indices = diagnostic
13271 .message
13272 .match_indices('\n')
13273 .filter(|_| has_row_limit)
13274 .map(|(ix, _)| ix)
13275 .fuse()
13276 .peekable();
13277
13278 for (quote_ix, _) in diagnostic
13279 .message
13280 .match_indices('`')
13281 .chain([(diagnostic.message.len(), "")])
13282 {
13283 let mut first_newline_ix = None;
13284 let mut last_newline_ix = None;
13285 while let Some(newline_ix) = newline_indices.peek() {
13286 if *newline_ix < quote_ix {
13287 if first_newline_ix.is_none() {
13288 first_newline_ix = Some(*newline_ix);
13289 }
13290 last_newline_ix = Some(*newline_ix);
13291
13292 if let Some(rows_left) = &mut max_message_rows {
13293 if *rows_left == 0 {
13294 break;
13295 } else {
13296 *rows_left -= 1;
13297 }
13298 }
13299 let _ = newline_indices.next();
13300 } else {
13301 break;
13302 }
13303 }
13304 let prev_len = text_without_backticks.len();
13305 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
13306 text_without_backticks.push_str(new_text);
13307 if in_code_block {
13308 code_ranges.push(prev_len..text_without_backticks.len());
13309 }
13310 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13311 in_code_block = !in_code_block;
13312 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13313 text_without_backticks.push_str("...");
13314 break;
13315 }
13316 }
13317
13318 (text_without_backticks.into(), code_ranges)
13319}
13320
13321fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13322 match severity {
13323 DiagnosticSeverity::ERROR => colors.error,
13324 DiagnosticSeverity::WARNING => colors.warning,
13325 DiagnosticSeverity::INFORMATION => colors.info,
13326 DiagnosticSeverity::HINT => colors.info,
13327 _ => colors.ignored,
13328 }
13329}
13330
13331pub fn styled_runs_for_code_label<'a>(
13332 label: &'a CodeLabel,
13333 syntax_theme: &'a theme::SyntaxTheme,
13334) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13335 let fade_out = HighlightStyle {
13336 fade_out: Some(0.35),
13337 ..Default::default()
13338 };
13339
13340 let mut prev_end = label.filter_range.end;
13341 label
13342 .runs
13343 .iter()
13344 .enumerate()
13345 .flat_map(move |(ix, (range, highlight_id))| {
13346 let style = if let Some(style) = highlight_id.style(syntax_theme) {
13347 style
13348 } else {
13349 return Default::default();
13350 };
13351 let mut muted_style = style;
13352 muted_style.highlight(fade_out);
13353
13354 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13355 if range.start >= label.filter_range.end {
13356 if range.start > prev_end {
13357 runs.push((prev_end..range.start, fade_out));
13358 }
13359 runs.push((range.clone(), muted_style));
13360 } else if range.end <= label.filter_range.end {
13361 runs.push((range.clone(), style));
13362 } else {
13363 runs.push((range.start..label.filter_range.end, style));
13364 runs.push((label.filter_range.end..range.end, muted_style));
13365 }
13366 prev_end = cmp::max(prev_end, range.end);
13367
13368 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13369 runs.push((prev_end..label.text.len(), fade_out));
13370 }
13371
13372 runs
13373 })
13374}
13375
13376pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13377 let mut prev_index = 0;
13378 let mut prev_codepoint: Option<char> = None;
13379 text.char_indices()
13380 .chain([(text.len(), '\0')])
13381 .filter_map(move |(index, codepoint)| {
13382 let prev_codepoint = prev_codepoint.replace(codepoint)?;
13383 let is_boundary = index == text.len()
13384 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13385 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13386 if is_boundary {
13387 let chunk = &text[prev_index..index];
13388 prev_index = index;
13389 Some(chunk)
13390 } else {
13391 None
13392 }
13393 })
13394}
13395
13396pub trait RangeToAnchorExt: Sized {
13397 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13398
13399 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13400 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13401 anchor_range.start.to_display_point(&snapshot)..anchor_range.end.to_display_point(&snapshot)
13402 }
13403}
13404
13405impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13406 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13407 let start_offset = self.start.to_offset(snapshot);
13408 let end_offset = self.end.to_offset(snapshot);
13409 if start_offset == end_offset {
13410 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13411 } else {
13412 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13413 }
13414 }
13415}
13416
13417pub trait RowExt {
13418 fn as_f32(&self) -> f32;
13419
13420 fn next_row(&self) -> Self;
13421
13422 fn previous_row(&self) -> Self;
13423
13424 fn minus(&self, other: Self) -> u32;
13425}
13426
13427impl RowExt for DisplayRow {
13428 fn as_f32(&self) -> f32 {
13429 self.0 as f32
13430 }
13431
13432 fn next_row(&self) -> Self {
13433 Self(self.0 + 1)
13434 }
13435
13436 fn previous_row(&self) -> Self {
13437 Self(self.0.saturating_sub(1))
13438 }
13439
13440 fn minus(&self, other: Self) -> u32 {
13441 self.0 - other.0
13442 }
13443}
13444
13445impl RowExt for MultiBufferRow {
13446 fn as_f32(&self) -> f32 {
13447 self.0 as f32
13448 }
13449
13450 fn next_row(&self) -> Self {
13451 Self(self.0 + 1)
13452 }
13453
13454 fn previous_row(&self) -> Self {
13455 Self(self.0.saturating_sub(1))
13456 }
13457
13458 fn minus(&self, other: Self) -> u32 {
13459 self.0 - other.0
13460 }
13461}
13462
13463trait RowRangeExt {
13464 type Row;
13465
13466 fn len(&self) -> usize;
13467
13468 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13469}
13470
13471impl RowRangeExt for Range<MultiBufferRow> {
13472 type Row = MultiBufferRow;
13473
13474 fn len(&self) -> usize {
13475 (self.end.0 - self.start.0) as usize
13476 }
13477
13478 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13479 (self.start.0..self.end.0).map(MultiBufferRow)
13480 }
13481}
13482
13483impl RowRangeExt for Range<DisplayRow> {
13484 type Row = DisplayRow;
13485
13486 fn len(&self) -> usize {
13487 (self.end.0 - self.start.0) as usize
13488 }
13489
13490 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13491 (self.start.0..self.end.0).map(DisplayRow)
13492 }
13493}
13494
13495fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13496 if hunk.diff_base_byte_range.is_empty() {
13497 DiffHunkStatus::Added
13498 } else if hunk.associated_range.is_empty() {
13499 DiffHunkStatus::Removed
13500 } else {
13501 DiffHunkStatus::Modified
13502 }
13503}
13504
13505/// If select range has more than one line, we
13506/// just point the cursor to range.start.
13507fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
13508 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
13509 range
13510 } else {
13511 range.start..range.start
13512 }
13513}