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 UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext,
80 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(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(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
474 fn to_any(&self) -> &dyn std::any::Any;
475}
476
477/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
478///
479/// See the [module level documentation](self) for more information.
480pub struct Editor {
481 focus_handle: FocusHandle,
482 last_focused_descendant: Option<WeakFocusHandle>,
483 /// The text buffer being edited
484 buffer: Model<MultiBuffer>,
485 /// Map of how text in the buffer should be displayed.
486 /// Handles soft wraps, folds, fake inlay text insertions, etc.
487 pub display_map: Model<DisplayMap>,
488 pub selections: SelectionsCollection,
489 pub scroll_manager: ScrollManager,
490 /// When inline assist editors are linked, they all render cursors because
491 /// typing enters text into each of them, even the ones that aren't focused.
492 pub(crate) show_cursor_when_unfocused: bool,
493 columnar_selection_tail: Option<Anchor>,
494 add_selections_state: Option<AddSelectionsState>,
495 select_next_state: Option<SelectNextState>,
496 select_prev_state: Option<SelectNextState>,
497 selection_history: SelectionHistory,
498 autoclose_regions: Vec<AutocloseRegion>,
499 snippet_stack: InvalidationStack<SnippetState>,
500 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
501 ime_transaction: Option<TransactionId>,
502 active_diagnostics: Option<ActiveDiagnosticGroup>,
503 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
504 project: Option<Model<Project>>,
505 completion_provider: Option<Box<dyn CompletionProvider>>,
506 collaboration_hub: Option<Box<dyn CollaborationHub>>,
507 blink_manager: Model<BlinkManager>,
508 show_cursor_names: bool,
509 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
510 pub show_local_selections: bool,
511 mode: EditorMode,
512 show_breadcrumbs: bool,
513 show_gutter: bool,
514 show_line_numbers: Option<bool>,
515 use_relative_line_numbers: Option<bool>,
516 show_git_diff_gutter: Option<bool>,
517 show_code_actions: Option<bool>,
518 show_runnables: Option<bool>,
519 show_wrap_guides: Option<bool>,
520 show_indent_guides: Option<bool>,
521 placeholder_text: Option<Arc<str>>,
522 highlight_order: usize,
523 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
524 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
525 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
526 scrollbar_marker_state: ScrollbarMarkerState,
527 active_indent_guides_state: ActiveIndentGuidesState,
528 nav_history: Option<ItemNavHistory>,
529 context_menu: RwLock<Option<ContextMenu>>,
530 mouse_context_menu: Option<MouseContextMenu>,
531 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
532 signature_help_state: SignatureHelpState,
533 auto_signature_help: Option<bool>,
534 find_all_references_task_sources: Vec<Anchor>,
535 next_completion_id: CompletionId,
536 completion_documentation_pre_resolve_debounce: DebouncedDelay,
537 available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
538 code_actions_task: Option<Task<()>>,
539 document_highlights_task: Option<Task<()>>,
540 linked_editing_range_task: Option<Task<Option<()>>>,
541 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
542 pending_rename: Option<RenameState>,
543 searchable: bool,
544 cursor_shape: CursorShape,
545 current_line_highlight: Option<CurrentLineHighlight>,
546 collapse_matches: bool,
547 autoindent_mode: Option<AutoindentMode>,
548 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
549 input_enabled: bool,
550 use_modal_editing: bool,
551 read_only: bool,
552 leader_peer_id: Option<PeerId>,
553 remote_id: Option<ViewId>,
554 hover_state: HoverState,
555 gutter_hovered: bool,
556 hovered_link_state: Option<HoveredLinkState>,
557 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
558 active_inline_completion: Option<(Inlay, Option<Range<Anchor>>)>,
559 show_inline_completions: bool,
560 inlay_hint_cache: InlayHintCache,
561 expanded_hunks: ExpandedHunks,
562 next_inlay_id: usize,
563 _subscriptions: Vec<Subscription>,
564 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
565 gutter_dimensions: GutterDimensions,
566 style: Option<EditorStyle>,
567 next_editor_action_id: EditorActionId,
568 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
569 use_autoclose: bool,
570 use_auto_surround: bool,
571 auto_replace_emoji_shortcode: bool,
572 show_git_blame_gutter: bool,
573 show_git_blame_inline: bool,
574 show_git_blame_inline_delay_task: Option<Task<()>>,
575 git_blame_inline_enabled: bool,
576 serialize_dirty_buffers: bool,
577 show_selection_menu: Option<bool>,
578 blame: Option<Model<GitBlame>>,
579 blame_subscription: Option<Subscription>,
580 custom_context_menu: Option<
581 Box<
582 dyn 'static
583 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
584 >,
585 >,
586 last_bounds: Option<Bounds<Pixels>>,
587 expect_bounds_change: Option<Bounds<Pixels>>,
588 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
589 tasks_update_task: Option<Task<()>>,
590 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
591 file_header_size: u32,
592 breadcrumb_header: Option<String>,
593 focused_block: Option<FocusedBlock>,
594 next_scroll_position: NextScrollCursorCenterTopBottom,
595 addons: HashMap<TypeId, Box<dyn Addon>>,
596 _scroll_cursor_center_top_bottom_task: Task<()>,
597}
598
599#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
600enum NextScrollCursorCenterTopBottom {
601 #[default]
602 Center,
603 Top,
604 Bottom,
605}
606
607impl NextScrollCursorCenterTopBottom {
608 fn next(&self) -> Self {
609 match self {
610 Self::Center => Self::Top,
611 Self::Top => Self::Bottom,
612 Self::Bottom => Self::Center,
613 }
614 }
615}
616
617#[derive(Clone)]
618pub struct EditorSnapshot {
619 pub mode: EditorMode,
620 show_gutter: bool,
621 show_line_numbers: Option<bool>,
622 show_git_diff_gutter: Option<bool>,
623 show_code_actions: Option<bool>,
624 show_runnables: Option<bool>,
625 render_git_blame_gutter: bool,
626 pub display_snapshot: DisplaySnapshot,
627 pub placeholder_text: Option<Arc<str>>,
628 is_focused: bool,
629 scroll_anchor: ScrollAnchor,
630 ongoing_scroll: OngoingScroll,
631 current_line_highlight: CurrentLineHighlight,
632 gutter_hovered: bool,
633}
634
635const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
636
637#[derive(Default, Debug, Clone, Copy)]
638pub struct GutterDimensions {
639 pub left_padding: Pixels,
640 pub right_padding: Pixels,
641 pub width: Pixels,
642 pub margin: Pixels,
643 pub git_blame_entries_width: Option<Pixels>,
644}
645
646impl GutterDimensions {
647 /// The full width of the space taken up by the gutter.
648 pub fn full_width(&self) -> Pixels {
649 self.margin + self.width
650 }
651
652 /// The width of the space reserved for the fold indicators,
653 /// use alongside 'justify_end' and `gutter_width` to
654 /// right align content with the line numbers
655 pub fn fold_area_width(&self) -> Pixels {
656 self.margin + self.right_padding
657 }
658}
659
660#[derive(Debug)]
661pub struct RemoteSelection {
662 pub replica_id: ReplicaId,
663 pub selection: Selection<Anchor>,
664 pub cursor_shape: CursorShape,
665 pub peer_id: PeerId,
666 pub line_mode: bool,
667 pub participant_index: Option<ParticipantIndex>,
668 pub user_name: Option<SharedString>,
669}
670
671#[derive(Clone, Debug)]
672struct SelectionHistoryEntry {
673 selections: Arc<[Selection<Anchor>]>,
674 select_next_state: Option<SelectNextState>,
675 select_prev_state: Option<SelectNextState>,
676 add_selections_state: Option<AddSelectionsState>,
677}
678
679enum SelectionHistoryMode {
680 Normal,
681 Undoing,
682 Redoing,
683}
684
685#[derive(Clone, PartialEq, Eq, Hash)]
686struct HoveredCursor {
687 replica_id: u16,
688 selection_id: usize,
689}
690
691impl Default for SelectionHistoryMode {
692 fn default() -> Self {
693 Self::Normal
694 }
695}
696
697#[derive(Default)]
698struct SelectionHistory {
699 #[allow(clippy::type_complexity)]
700 selections_by_transaction:
701 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
702 mode: SelectionHistoryMode,
703 undo_stack: VecDeque<SelectionHistoryEntry>,
704 redo_stack: VecDeque<SelectionHistoryEntry>,
705}
706
707impl SelectionHistory {
708 fn insert_transaction(
709 &mut self,
710 transaction_id: TransactionId,
711 selections: Arc<[Selection<Anchor>]>,
712 ) {
713 self.selections_by_transaction
714 .insert(transaction_id, (selections, None));
715 }
716
717 #[allow(clippy::type_complexity)]
718 fn transaction(
719 &self,
720 transaction_id: TransactionId,
721 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
722 self.selections_by_transaction.get(&transaction_id)
723 }
724
725 #[allow(clippy::type_complexity)]
726 fn transaction_mut(
727 &mut self,
728 transaction_id: TransactionId,
729 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
730 self.selections_by_transaction.get_mut(&transaction_id)
731 }
732
733 fn push(&mut self, entry: SelectionHistoryEntry) {
734 if !entry.selections.is_empty() {
735 match self.mode {
736 SelectionHistoryMode::Normal => {
737 self.push_undo(entry);
738 self.redo_stack.clear();
739 }
740 SelectionHistoryMode::Undoing => self.push_redo(entry),
741 SelectionHistoryMode::Redoing => self.push_undo(entry),
742 }
743 }
744 }
745
746 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
747 if self
748 .undo_stack
749 .back()
750 .map_or(true, |e| e.selections != entry.selections)
751 {
752 self.undo_stack.push_back(entry);
753 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
754 self.undo_stack.pop_front();
755 }
756 }
757 }
758
759 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
760 if self
761 .redo_stack
762 .back()
763 .map_or(true, |e| e.selections != entry.selections)
764 {
765 self.redo_stack.push_back(entry);
766 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
767 self.redo_stack.pop_front();
768 }
769 }
770 }
771}
772
773struct RowHighlight {
774 index: usize,
775 range: RangeInclusive<Anchor>,
776 color: Option<Hsla>,
777 should_autoscroll: bool,
778}
779
780#[derive(Clone, Debug)]
781struct AddSelectionsState {
782 above: bool,
783 stack: Vec<usize>,
784}
785
786#[derive(Clone)]
787struct SelectNextState {
788 query: AhoCorasick,
789 wordwise: bool,
790 done: bool,
791}
792
793impl std::fmt::Debug for SelectNextState {
794 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
795 f.debug_struct(std::any::type_name::<Self>())
796 .field("wordwise", &self.wordwise)
797 .field("done", &self.done)
798 .finish()
799 }
800}
801
802#[derive(Debug)]
803struct AutocloseRegion {
804 selection_id: usize,
805 range: Range<Anchor>,
806 pair: BracketPair,
807}
808
809#[derive(Debug)]
810struct SnippetState {
811 ranges: Vec<Vec<Range<Anchor>>>,
812 active_index: usize,
813}
814
815#[doc(hidden)]
816pub struct RenameState {
817 pub range: Range<Anchor>,
818 pub old_name: Arc<str>,
819 pub editor: View<Editor>,
820 block_id: CustomBlockId,
821}
822
823struct InvalidationStack<T>(Vec<T>);
824
825struct RegisteredInlineCompletionProvider {
826 provider: Arc<dyn InlineCompletionProviderHandle>,
827 _subscription: Subscription,
828}
829
830enum ContextMenu {
831 Completions(CompletionsMenu),
832 CodeActions(CodeActionsMenu),
833}
834
835impl ContextMenu {
836 fn select_first(
837 &mut self,
838 project: Option<&Model<Project>>,
839 cx: &mut ViewContext<Editor>,
840 ) -> bool {
841 if self.visible() {
842 match self {
843 ContextMenu::Completions(menu) => menu.select_first(project, cx),
844 ContextMenu::CodeActions(menu) => menu.select_first(cx),
845 }
846 true
847 } else {
848 false
849 }
850 }
851
852 fn select_prev(
853 &mut self,
854 project: Option<&Model<Project>>,
855 cx: &mut ViewContext<Editor>,
856 ) -> bool {
857 if self.visible() {
858 match self {
859 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
860 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
861 }
862 true
863 } else {
864 false
865 }
866 }
867
868 fn select_next(
869 &mut self,
870 project: Option<&Model<Project>>,
871 cx: &mut ViewContext<Editor>,
872 ) -> bool {
873 if self.visible() {
874 match self {
875 ContextMenu::Completions(menu) => menu.select_next(project, cx),
876 ContextMenu::CodeActions(menu) => menu.select_next(cx),
877 }
878 true
879 } else {
880 false
881 }
882 }
883
884 fn select_last(
885 &mut self,
886 project: Option<&Model<Project>>,
887 cx: &mut ViewContext<Editor>,
888 ) -> bool {
889 if self.visible() {
890 match self {
891 ContextMenu::Completions(menu) => menu.select_last(project, cx),
892 ContextMenu::CodeActions(menu) => menu.select_last(cx),
893 }
894 true
895 } else {
896 false
897 }
898 }
899
900 fn visible(&self) -> bool {
901 match self {
902 ContextMenu::Completions(menu) => menu.visible(),
903 ContextMenu::CodeActions(menu) => menu.visible(),
904 }
905 }
906
907 fn render(
908 &self,
909 cursor_position: DisplayPoint,
910 style: &EditorStyle,
911 max_height: Pixels,
912 workspace: Option<WeakView<Workspace>>,
913 cx: &mut ViewContext<Editor>,
914 ) -> (ContextMenuOrigin, AnyElement) {
915 match self {
916 ContextMenu::Completions(menu) => (
917 ContextMenuOrigin::EditorPoint(cursor_position),
918 menu.render(style, max_height, workspace, cx),
919 ),
920 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
921 }
922 }
923}
924
925enum ContextMenuOrigin {
926 EditorPoint(DisplayPoint),
927 GutterIndicator(DisplayRow),
928}
929
930#[derive(Clone)]
931struct CompletionsMenu {
932 id: CompletionId,
933 sort_completions: bool,
934 initial_position: Anchor,
935 buffer: Model<Buffer>,
936 completions: Arc<RwLock<Box<[Completion]>>>,
937 match_candidates: Arc<[StringMatchCandidate]>,
938 matches: Arc<[StringMatch]>,
939 selected_item: usize,
940 scroll_handle: UniformListScrollHandle,
941 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
942}
943
944impl CompletionsMenu {
945 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
946 self.selected_item = 0;
947 self.scroll_handle.scroll_to_item(self.selected_item);
948 self.attempt_resolve_selected_completion_documentation(project, cx);
949 cx.notify();
950 }
951
952 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
953 if self.selected_item > 0 {
954 self.selected_item -= 1;
955 } else {
956 self.selected_item = self.matches.len() - 1;
957 }
958 self.scroll_handle.scroll_to_item(self.selected_item);
959 self.attempt_resolve_selected_completion_documentation(project, cx);
960 cx.notify();
961 }
962
963 fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
964 if self.selected_item + 1 < self.matches.len() {
965 self.selected_item += 1;
966 } else {
967 self.selected_item = 0;
968 }
969 self.scroll_handle.scroll_to_item(self.selected_item);
970 self.attempt_resolve_selected_completion_documentation(project, cx);
971 cx.notify();
972 }
973
974 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
975 self.selected_item = self.matches.len() - 1;
976 self.scroll_handle.scroll_to_item(self.selected_item);
977 self.attempt_resolve_selected_completion_documentation(project, cx);
978 cx.notify();
979 }
980
981 fn pre_resolve_completion_documentation(
982 buffer: Model<Buffer>,
983 completions: Arc<RwLock<Box<[Completion]>>>,
984 matches: Arc<[StringMatch]>,
985 editor: &Editor,
986 cx: &mut ViewContext<Editor>,
987 ) -> Task<()> {
988 let settings = EditorSettings::get_global(cx);
989 if !settings.show_completion_documentation {
990 return Task::ready(());
991 }
992
993 let Some(provider) = editor.completion_provider.as_ref() else {
994 return Task::ready(());
995 };
996
997 let resolve_task = provider.resolve_completions(
998 buffer,
999 matches.iter().map(|m| m.candidate_id).collect(),
1000 completions.clone(),
1001 cx,
1002 );
1003
1004 return cx.spawn(move |this, mut cx| async move {
1005 if let Some(true) = resolve_task.await.log_err() {
1006 this.update(&mut cx, |_, cx| cx.notify()).ok();
1007 }
1008 });
1009 }
1010
1011 fn attempt_resolve_selected_completion_documentation(
1012 &mut self,
1013 project: Option<&Model<Project>>,
1014 cx: &mut ViewContext<Editor>,
1015 ) {
1016 let settings = EditorSettings::get_global(cx);
1017 if !settings.show_completion_documentation {
1018 return;
1019 }
1020
1021 let completion_index = self.matches[self.selected_item].candidate_id;
1022 let Some(project) = project else {
1023 return;
1024 };
1025
1026 let resolve_task = project.update(cx, |project, cx| {
1027 project.resolve_completions(
1028 self.buffer.clone(),
1029 vec![completion_index],
1030 self.completions.clone(),
1031 cx,
1032 )
1033 });
1034
1035 let delay_ms =
1036 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1037 let delay = Duration::from_millis(delay_ms);
1038
1039 self.selected_completion_documentation_resolve_debounce
1040 .lock()
1041 .fire_new(delay, cx, |_, cx| {
1042 cx.spawn(move |this, mut cx| async move {
1043 if let Some(true) = resolve_task.await.log_err() {
1044 this.update(&mut cx, |_, cx| cx.notify()).ok();
1045 }
1046 })
1047 });
1048 }
1049
1050 fn visible(&self) -> bool {
1051 !self.matches.is_empty()
1052 }
1053
1054 fn render(
1055 &self,
1056 style: &EditorStyle,
1057 max_height: Pixels,
1058 workspace: Option<WeakView<Workspace>>,
1059 cx: &mut ViewContext<Editor>,
1060 ) -> AnyElement {
1061 let settings = EditorSettings::get_global(cx);
1062 let show_completion_documentation = settings.show_completion_documentation;
1063
1064 let widest_completion_ix = self
1065 .matches
1066 .iter()
1067 .enumerate()
1068 .max_by_key(|(_, mat)| {
1069 let completions = self.completions.read();
1070 let completion = &completions[mat.candidate_id];
1071 let documentation = &completion.documentation;
1072
1073 let mut len = completion.label.text.chars().count();
1074 if let Some(Documentation::SingleLine(text)) = documentation {
1075 if show_completion_documentation {
1076 len += text.chars().count();
1077 }
1078 }
1079
1080 len
1081 })
1082 .map(|(ix, _)| ix);
1083
1084 let completions = self.completions.clone();
1085 let matches = self.matches.clone();
1086 let selected_item = self.selected_item;
1087 let style = style.clone();
1088
1089 let multiline_docs = if show_completion_documentation {
1090 let mat = &self.matches[selected_item];
1091 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1092 Some(Documentation::MultiLinePlainText(text)) => {
1093 Some(div().child(SharedString::from(text.clone())))
1094 }
1095 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1096 Some(div().child(render_parsed_markdown(
1097 "completions_markdown",
1098 parsed,
1099 &style,
1100 workspace,
1101 cx,
1102 )))
1103 }
1104 _ => None,
1105 };
1106 multiline_docs.map(|div| {
1107 div.id("multiline_docs")
1108 .max_h(max_height)
1109 .flex_1()
1110 .px_1p5()
1111 .py_1()
1112 .min_w(px(260.))
1113 .max_w(px(640.))
1114 .w(px(500.))
1115 .overflow_y_scroll()
1116 .occlude()
1117 })
1118 } else {
1119 None
1120 };
1121
1122 let list = uniform_list(
1123 cx.view().clone(),
1124 "completions",
1125 matches.len(),
1126 move |_editor, range, cx| {
1127 let start_ix = range.start;
1128 let completions_guard = completions.read();
1129
1130 matches[range]
1131 .iter()
1132 .enumerate()
1133 .map(|(ix, mat)| {
1134 let item_ix = start_ix + ix;
1135 let candidate_id = mat.candidate_id;
1136 let completion = &completions_guard[candidate_id];
1137
1138 let documentation = if show_completion_documentation {
1139 &completion.documentation
1140 } else {
1141 &None
1142 };
1143
1144 let highlights = gpui::combine_highlights(
1145 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1146 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1147 |(range, mut highlight)| {
1148 // Ignore font weight for syntax highlighting, as we'll use it
1149 // for fuzzy matches.
1150 highlight.font_weight = None;
1151
1152 if completion.lsp_completion.deprecated.unwrap_or(false) {
1153 highlight.strikethrough = Some(StrikethroughStyle {
1154 thickness: 1.0.into(),
1155 ..Default::default()
1156 });
1157 highlight.color = Some(cx.theme().colors().text_muted);
1158 }
1159
1160 (range, highlight)
1161 },
1162 ),
1163 );
1164 let completion_label = StyledText::new(completion.label.text.clone())
1165 .with_highlights(&style.text, highlights);
1166 let documentation_label =
1167 if let Some(Documentation::SingleLine(text)) = documentation {
1168 if text.trim().is_empty() {
1169 None
1170 } else {
1171 Some(
1172 Label::new(text.clone())
1173 .ml_4()
1174 .size(LabelSize::Small)
1175 .color(Color::Muted),
1176 )
1177 }
1178 } else {
1179 None
1180 };
1181
1182 div().min_w(px(220.)).max_w(px(540.)).child(
1183 ListItem::new(mat.candidate_id)
1184 .inset(true)
1185 .selected(item_ix == selected_item)
1186 .on_click(cx.listener(move |editor, _event, cx| {
1187 cx.stop_propagation();
1188 if let Some(task) = editor.confirm_completion(
1189 &ConfirmCompletion {
1190 item_ix: Some(item_ix),
1191 },
1192 cx,
1193 ) {
1194 task.detach_and_log_err(cx)
1195 }
1196 }))
1197 .child(h_flex().overflow_hidden().child(completion_label))
1198 .end_slot::<Label>(documentation_label),
1199 )
1200 })
1201 .collect()
1202 },
1203 )
1204 .occlude()
1205 .max_h(max_height)
1206 .track_scroll(self.scroll_handle.clone())
1207 .with_width_from_item(widest_completion_ix)
1208 .with_sizing_behavior(ListSizingBehavior::Infer);
1209
1210 Popover::new()
1211 .child(list)
1212 .when_some(multiline_docs, |popover, multiline_docs| {
1213 popover.aside(multiline_docs)
1214 })
1215 .into_any_element()
1216 }
1217
1218 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1219 let mut matches = if let Some(query) = query {
1220 fuzzy::match_strings(
1221 &self.match_candidates,
1222 query,
1223 query.chars().any(|c| c.is_uppercase()),
1224 100,
1225 &Default::default(),
1226 executor,
1227 )
1228 .await
1229 } else {
1230 self.match_candidates
1231 .iter()
1232 .enumerate()
1233 .map(|(candidate_id, candidate)| StringMatch {
1234 candidate_id,
1235 score: Default::default(),
1236 positions: Default::default(),
1237 string: candidate.string.clone(),
1238 })
1239 .collect()
1240 };
1241
1242 // Remove all candidates where the query's start does not match the start of any word in the candidate
1243 if let Some(query) = query {
1244 if let Some(query_start) = query.chars().next() {
1245 matches.retain(|string_match| {
1246 split_words(&string_match.string).any(|word| {
1247 // Check that the first codepoint of the word as lowercase matches the first
1248 // codepoint of the query as lowercase
1249 word.chars()
1250 .flat_map(|codepoint| codepoint.to_lowercase())
1251 .zip(query_start.to_lowercase())
1252 .all(|(word_cp, query_cp)| word_cp == query_cp)
1253 })
1254 });
1255 }
1256 }
1257
1258 let completions = self.completions.read();
1259 if self.sort_completions {
1260 matches.sort_unstable_by_key(|mat| {
1261 // We do want to strike a balance here between what the language server tells us
1262 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1263 // `Creat` and there is a local variable called `CreateComponent`).
1264 // So what we do is: we bucket all matches into two buckets
1265 // - Strong matches
1266 // - Weak matches
1267 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1268 // and the Weak matches are the rest.
1269 //
1270 // For the strong matches, we sort by the language-servers score first and for the weak
1271 // matches, we prefer our fuzzy finder first.
1272 //
1273 // The thinking behind that: it's useless to take the sort_text the language-server gives
1274 // us into account when it's obviously a bad match.
1275
1276 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1277 enum MatchScore<'a> {
1278 Strong {
1279 sort_text: Option<&'a str>,
1280 score: Reverse<OrderedFloat<f64>>,
1281 sort_key: (usize, &'a str),
1282 },
1283 Weak {
1284 score: Reverse<OrderedFloat<f64>>,
1285 sort_text: Option<&'a str>,
1286 sort_key: (usize, &'a str),
1287 },
1288 }
1289
1290 let completion = &completions[mat.candidate_id];
1291 let sort_key = completion.sort_key();
1292 let sort_text = completion.lsp_completion.sort_text.as_deref();
1293 let score = Reverse(OrderedFloat(mat.score));
1294
1295 if mat.score >= 0.2 {
1296 MatchScore::Strong {
1297 sort_text,
1298 score,
1299 sort_key,
1300 }
1301 } else {
1302 MatchScore::Weak {
1303 score,
1304 sort_text,
1305 sort_key,
1306 }
1307 }
1308 });
1309 }
1310
1311 for mat in &mut matches {
1312 let completion = &completions[mat.candidate_id];
1313 mat.string.clone_from(&completion.label.text);
1314 for position in &mut mat.positions {
1315 *position += completion.label.filter_range.start;
1316 }
1317 }
1318 drop(completions);
1319
1320 self.matches = matches.into();
1321 self.selected_item = 0;
1322 }
1323}
1324
1325#[derive(Clone)]
1326struct CodeActionContents {
1327 tasks: Option<Arc<ResolvedTasks>>,
1328 actions: Option<Arc<[CodeAction]>>,
1329}
1330
1331impl CodeActionContents {
1332 fn len(&self) -> usize {
1333 match (&self.tasks, &self.actions) {
1334 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1335 (Some(tasks), None) => tasks.templates.len(),
1336 (None, Some(actions)) => actions.len(),
1337 (None, None) => 0,
1338 }
1339 }
1340
1341 fn is_empty(&self) -> bool {
1342 match (&self.tasks, &self.actions) {
1343 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1344 (Some(tasks), None) => tasks.templates.is_empty(),
1345 (None, Some(actions)) => actions.is_empty(),
1346 (None, None) => true,
1347 }
1348 }
1349
1350 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1351 self.tasks
1352 .iter()
1353 .flat_map(|tasks| {
1354 tasks
1355 .templates
1356 .iter()
1357 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1358 })
1359 .chain(self.actions.iter().flat_map(|actions| {
1360 actions
1361 .iter()
1362 .map(|action| CodeActionsItem::CodeAction(action.clone()))
1363 }))
1364 }
1365 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1366 match (&self.tasks, &self.actions) {
1367 (Some(tasks), Some(actions)) => {
1368 if index < tasks.templates.len() {
1369 tasks
1370 .templates
1371 .get(index)
1372 .cloned()
1373 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1374 } else {
1375 actions
1376 .get(index - tasks.templates.len())
1377 .cloned()
1378 .map(CodeActionsItem::CodeAction)
1379 }
1380 }
1381 (Some(tasks), None) => tasks
1382 .templates
1383 .get(index)
1384 .cloned()
1385 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1386 (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
1387 (None, None) => None,
1388 }
1389 }
1390}
1391
1392#[allow(clippy::large_enum_variant)]
1393#[derive(Clone)]
1394enum CodeActionsItem {
1395 Task(TaskSourceKind, ResolvedTask),
1396 CodeAction(CodeAction),
1397}
1398
1399impl CodeActionsItem {
1400 fn as_task(&self) -> Option<&ResolvedTask> {
1401 let Self::Task(_, task) = self else {
1402 return None;
1403 };
1404 Some(task)
1405 }
1406 fn as_code_action(&self) -> Option<&CodeAction> {
1407 let Self::CodeAction(action) = self else {
1408 return None;
1409 };
1410 Some(action)
1411 }
1412 fn label(&self) -> String {
1413 match self {
1414 Self::CodeAction(action) => action.lsp_action.title.clone(),
1415 Self::Task(_, task) => task.resolved_label.clone(),
1416 }
1417 }
1418}
1419
1420struct CodeActionsMenu {
1421 actions: CodeActionContents,
1422 buffer: Model<Buffer>,
1423 selected_item: usize,
1424 scroll_handle: UniformListScrollHandle,
1425 deployed_from_indicator: Option<DisplayRow>,
1426}
1427
1428impl CodeActionsMenu {
1429 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1430 self.selected_item = 0;
1431 self.scroll_handle.scroll_to_item(self.selected_item);
1432 cx.notify()
1433 }
1434
1435 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1436 if self.selected_item > 0 {
1437 self.selected_item -= 1;
1438 } else {
1439 self.selected_item = self.actions.len() - 1;
1440 }
1441 self.scroll_handle.scroll_to_item(self.selected_item);
1442 cx.notify();
1443 }
1444
1445 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1446 if self.selected_item + 1 < self.actions.len() {
1447 self.selected_item += 1;
1448 } else {
1449 self.selected_item = 0;
1450 }
1451 self.scroll_handle.scroll_to_item(self.selected_item);
1452 cx.notify();
1453 }
1454
1455 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1456 self.selected_item = self.actions.len() - 1;
1457 self.scroll_handle.scroll_to_item(self.selected_item);
1458 cx.notify()
1459 }
1460
1461 fn visible(&self) -> bool {
1462 !self.actions.is_empty()
1463 }
1464
1465 fn render(
1466 &self,
1467 cursor_position: DisplayPoint,
1468 _style: &EditorStyle,
1469 max_height: Pixels,
1470 cx: &mut ViewContext<Editor>,
1471 ) -> (ContextMenuOrigin, AnyElement) {
1472 let actions = self.actions.clone();
1473 let selected_item = self.selected_item;
1474 let element = uniform_list(
1475 cx.view().clone(),
1476 "code_actions_menu",
1477 self.actions.len(),
1478 move |_this, range, cx| {
1479 actions
1480 .iter()
1481 .skip(range.start)
1482 .take(range.end - range.start)
1483 .enumerate()
1484 .map(|(ix, action)| {
1485 let item_ix = range.start + ix;
1486 let selected = selected_item == item_ix;
1487 let colors = cx.theme().colors();
1488 div()
1489 .px_2()
1490 .text_color(colors.text)
1491 .when(selected, |style| {
1492 style
1493 .bg(colors.element_active)
1494 .text_color(colors.text_accent)
1495 })
1496 .hover(|style| {
1497 style
1498 .bg(colors.element_hover)
1499 .text_color(colors.text_accent)
1500 })
1501 .whitespace_nowrap()
1502 .when_some(action.as_code_action(), |this, action| {
1503 this.on_mouse_down(
1504 MouseButton::Left,
1505 cx.listener(move |editor, _, cx| {
1506 cx.stop_propagation();
1507 if let Some(task) = editor.confirm_code_action(
1508 &ConfirmCodeAction {
1509 item_ix: Some(item_ix),
1510 },
1511 cx,
1512 ) {
1513 task.detach_and_log_err(cx)
1514 }
1515 }),
1516 )
1517 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1518 .child(SharedString::from(action.lsp_action.title.clone()))
1519 })
1520 .when_some(action.as_task(), |this, task| {
1521 this.on_mouse_down(
1522 MouseButton::Left,
1523 cx.listener(move |editor, _, cx| {
1524 cx.stop_propagation();
1525 if let Some(task) = editor.confirm_code_action(
1526 &ConfirmCodeAction {
1527 item_ix: Some(item_ix),
1528 },
1529 cx,
1530 ) {
1531 task.detach_and_log_err(cx)
1532 }
1533 }),
1534 )
1535 .child(SharedString::from(task.resolved_label.clone()))
1536 })
1537 })
1538 .collect()
1539 },
1540 )
1541 .elevation_1(cx)
1542 .px_2()
1543 .py_1()
1544 .max_h(max_height)
1545 .occlude()
1546 .track_scroll(self.scroll_handle.clone())
1547 .with_width_from_item(
1548 self.actions
1549 .iter()
1550 .enumerate()
1551 .max_by_key(|(_, action)| match action {
1552 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1553 CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
1554 })
1555 .map(|(ix, _)| ix),
1556 )
1557 .with_sizing_behavior(ListSizingBehavior::Infer)
1558 .into_any_element();
1559
1560 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1561 ContextMenuOrigin::GutterIndicator(row)
1562 } else {
1563 ContextMenuOrigin::EditorPoint(cursor_position)
1564 };
1565
1566 (cursor_position, element)
1567 }
1568}
1569
1570#[derive(Debug)]
1571struct ActiveDiagnosticGroup {
1572 primary_range: Range<Anchor>,
1573 primary_message: String,
1574 group_id: usize,
1575 blocks: HashMap<CustomBlockId, Diagnostic>,
1576 is_valid: bool,
1577}
1578
1579#[derive(Serialize, Deserialize, Clone, Debug)]
1580pub struct ClipboardSelection {
1581 pub len: usize,
1582 pub is_entire_line: bool,
1583 pub first_line_indent: u32,
1584}
1585
1586#[derive(Debug)]
1587pub(crate) struct NavigationData {
1588 cursor_anchor: Anchor,
1589 cursor_position: Point,
1590 scroll_anchor: ScrollAnchor,
1591 scroll_top_row: u32,
1592}
1593
1594#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1595enum GotoDefinitionKind {
1596 Symbol,
1597 Declaration,
1598 Type,
1599 Implementation,
1600}
1601
1602#[derive(Debug, Clone)]
1603enum InlayHintRefreshReason {
1604 Toggle(bool),
1605 SettingsChange(InlayHintSettings),
1606 NewLinesShown,
1607 BufferEdited(HashSet<Arc<Language>>),
1608 RefreshRequested,
1609 ExcerptsRemoved(Vec<ExcerptId>),
1610}
1611
1612impl InlayHintRefreshReason {
1613 fn description(&self) -> &'static str {
1614 match self {
1615 Self::Toggle(_) => "toggle",
1616 Self::SettingsChange(_) => "settings change",
1617 Self::NewLinesShown => "new lines shown",
1618 Self::BufferEdited(_) => "buffer edited",
1619 Self::RefreshRequested => "refresh requested",
1620 Self::ExcerptsRemoved(_) => "excerpts removed",
1621 }
1622 }
1623}
1624
1625pub(crate) struct FocusedBlock {
1626 id: BlockId,
1627 focus_handle: WeakFocusHandle,
1628}
1629
1630impl Editor {
1631 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1632 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1633 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1634 Self::new(
1635 EditorMode::SingleLine { auto_width: false },
1636 buffer,
1637 None,
1638 false,
1639 cx,
1640 )
1641 }
1642
1643 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1644 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1645 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1646 Self::new(EditorMode::Full, buffer, None, false, cx)
1647 }
1648
1649 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1650 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1651 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1652 Self::new(
1653 EditorMode::SingleLine { auto_width: true },
1654 buffer,
1655 None,
1656 false,
1657 cx,
1658 )
1659 }
1660
1661 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1662 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1663 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1664 Self::new(
1665 EditorMode::AutoHeight { max_lines },
1666 buffer,
1667 None,
1668 false,
1669 cx,
1670 )
1671 }
1672
1673 pub fn for_buffer(
1674 buffer: Model<Buffer>,
1675 project: Option<Model<Project>>,
1676 cx: &mut ViewContext<Self>,
1677 ) -> Self {
1678 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1679 Self::new(EditorMode::Full, buffer, project, false, cx)
1680 }
1681
1682 pub fn for_multibuffer(
1683 buffer: Model<MultiBuffer>,
1684 project: Option<Model<Project>>,
1685 show_excerpt_controls: bool,
1686 cx: &mut ViewContext<Self>,
1687 ) -> Self {
1688 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1689 }
1690
1691 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1692 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1693 let mut clone = Self::new(
1694 self.mode,
1695 self.buffer.clone(),
1696 self.project.clone(),
1697 show_excerpt_controls,
1698 cx,
1699 );
1700 self.display_map.update(cx, |display_map, cx| {
1701 let snapshot = display_map.snapshot(cx);
1702 clone.display_map.update(cx, |display_map, cx| {
1703 display_map.set_state(&snapshot, cx);
1704 });
1705 });
1706 clone.selections.clone_state(&self.selections);
1707 clone.scroll_manager.clone_state(&self.scroll_manager);
1708 clone.searchable = self.searchable;
1709 clone
1710 }
1711
1712 pub fn new(
1713 mode: EditorMode,
1714 buffer: Model<MultiBuffer>,
1715 project: Option<Model<Project>>,
1716 show_excerpt_controls: bool,
1717 cx: &mut ViewContext<Self>,
1718 ) -> Self {
1719 let style = cx.text_style();
1720 let font_size = style.font_size.to_pixels(cx.rem_size());
1721 let editor = cx.view().downgrade();
1722 let fold_placeholder = FoldPlaceholder {
1723 constrain_width: true,
1724 render: Arc::new(move |fold_id, fold_range, cx| {
1725 let editor = editor.clone();
1726 div()
1727 .id(fold_id)
1728 .bg(cx.theme().colors().ghost_element_background)
1729 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1730 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1731 .rounded_sm()
1732 .size_full()
1733 .cursor_pointer()
1734 .child("⋯")
1735 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1736 .on_click(move |_, cx| {
1737 editor
1738 .update(cx, |editor, cx| {
1739 editor.unfold_ranges(
1740 [fold_range.start..fold_range.end],
1741 true,
1742 false,
1743 cx,
1744 );
1745 cx.stop_propagation();
1746 })
1747 .ok();
1748 })
1749 .into_any()
1750 }),
1751 merge_adjacent: true,
1752 };
1753 let file_header_size = if show_excerpt_controls { 3 } else { 2 };
1754 let display_map = cx.new_model(|cx| {
1755 DisplayMap::new(
1756 buffer.clone(),
1757 style.font(),
1758 font_size,
1759 None,
1760 show_excerpt_controls,
1761 file_header_size,
1762 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1763 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1764 fold_placeholder,
1765 cx,
1766 )
1767 });
1768
1769 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1770
1771 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1772
1773 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1774 .then(|| language_settings::SoftWrap::PreferLine);
1775
1776 let mut project_subscriptions = Vec::new();
1777 if mode == EditorMode::Full {
1778 if let Some(project) = project.as_ref() {
1779 if buffer.read(cx).is_singleton() {
1780 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1781 cx.emit(EditorEvent::TitleChanged);
1782 }));
1783 }
1784 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1785 if let project::Event::RefreshInlayHints = event {
1786 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1787 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1788 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1789 let focus_handle = editor.focus_handle(cx);
1790 if focus_handle.is_focused(cx) {
1791 let snapshot = buffer.read(cx).snapshot();
1792 for (range, snippet) in snippet_edits {
1793 let editor_range =
1794 language::range_from_lsp(*range).to_offset(&snapshot);
1795 editor
1796 .insert_snippet(&[editor_range], snippet.clone(), cx)
1797 .ok();
1798 }
1799 }
1800 }
1801 }
1802 }));
1803 let task_inventory = project.read(cx).task_inventory().clone();
1804 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1805 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1806 }));
1807 }
1808 }
1809
1810 let inlay_hint_settings = inlay_hint_settings(
1811 selections.newest_anchor().head(),
1812 &buffer.read(cx).snapshot(cx),
1813 cx,
1814 );
1815 let focus_handle = cx.focus_handle();
1816 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1817 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1818 .detach();
1819 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1820 .detach();
1821 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1822
1823 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1824 Some(false)
1825 } else {
1826 None
1827 };
1828
1829 let mut this = Self {
1830 focus_handle,
1831 show_cursor_when_unfocused: false,
1832 last_focused_descendant: None,
1833 buffer: buffer.clone(),
1834 display_map: display_map.clone(),
1835 selections,
1836 scroll_manager: ScrollManager::new(cx),
1837 columnar_selection_tail: None,
1838 add_selections_state: None,
1839 select_next_state: None,
1840 select_prev_state: None,
1841 selection_history: Default::default(),
1842 autoclose_regions: Default::default(),
1843 snippet_stack: Default::default(),
1844 select_larger_syntax_node_stack: Vec::new(),
1845 ime_transaction: Default::default(),
1846 active_diagnostics: None,
1847 soft_wrap_mode_override,
1848 completion_provider: project.clone().map(|project| Box::new(project) as _),
1849 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1850 project,
1851 blink_manager: blink_manager.clone(),
1852 show_local_selections: true,
1853 mode,
1854 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1855 show_gutter: mode == EditorMode::Full,
1856 show_line_numbers: None,
1857 use_relative_line_numbers: None,
1858 show_git_diff_gutter: None,
1859 show_code_actions: None,
1860 show_runnables: None,
1861 show_wrap_guides: None,
1862 show_indent_guides,
1863 placeholder_text: None,
1864 highlight_order: 0,
1865 highlighted_rows: HashMap::default(),
1866 background_highlights: Default::default(),
1867 gutter_highlights: TreeMap::default(),
1868 scrollbar_marker_state: ScrollbarMarkerState::default(),
1869 active_indent_guides_state: ActiveIndentGuidesState::default(),
1870 nav_history: None,
1871 context_menu: RwLock::new(None),
1872 mouse_context_menu: None,
1873 completion_tasks: Default::default(),
1874 signature_help_state: SignatureHelpState::default(),
1875 auto_signature_help: None,
1876 find_all_references_task_sources: Vec::new(),
1877 next_completion_id: 0,
1878 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1879 next_inlay_id: 0,
1880 available_code_actions: Default::default(),
1881 code_actions_task: Default::default(),
1882 document_highlights_task: Default::default(),
1883 linked_editing_range_task: Default::default(),
1884 pending_rename: Default::default(),
1885 searchable: true,
1886 cursor_shape: Default::default(),
1887 current_line_highlight: None,
1888 autoindent_mode: Some(AutoindentMode::EachLine),
1889 collapse_matches: false,
1890 workspace: None,
1891 input_enabled: true,
1892 use_modal_editing: mode == EditorMode::Full,
1893 read_only: false,
1894 use_autoclose: true,
1895 use_auto_surround: true,
1896 auto_replace_emoji_shortcode: false,
1897 leader_peer_id: None,
1898 remote_id: None,
1899 hover_state: Default::default(),
1900 hovered_link_state: Default::default(),
1901 inline_completion_provider: None,
1902 active_inline_completion: None,
1903 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1904 expanded_hunks: ExpandedHunks::default(),
1905 gutter_hovered: false,
1906 pixel_position_of_newest_cursor: None,
1907 last_bounds: None,
1908 expect_bounds_change: None,
1909 gutter_dimensions: GutterDimensions::default(),
1910 style: None,
1911 show_cursor_names: false,
1912 hovered_cursors: Default::default(),
1913 next_editor_action_id: EditorActionId::default(),
1914 editor_actions: Rc::default(),
1915 show_inline_completions: mode == EditorMode::Full,
1916 custom_context_menu: None,
1917 show_git_blame_gutter: false,
1918 show_git_blame_inline: false,
1919 show_selection_menu: None,
1920 show_git_blame_inline_delay_task: None,
1921 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1922 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1923 .session
1924 .restore_unsaved_buffers,
1925 blame: None,
1926 blame_subscription: None,
1927 file_header_size,
1928 tasks: Default::default(),
1929 _subscriptions: vec![
1930 cx.observe(&buffer, Self::on_buffer_changed),
1931 cx.subscribe(&buffer, Self::on_buffer_event),
1932 cx.observe(&display_map, Self::on_display_map_changed),
1933 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1934 cx.observe_global::<SettingsStore>(Self::settings_changed),
1935 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1936 cx.observe_window_activation(|editor, cx| {
1937 let active = cx.is_window_active();
1938 editor.blink_manager.update(cx, |blink_manager, cx| {
1939 if active {
1940 blink_manager.enable(cx);
1941 } else {
1942 blink_manager.disable(cx);
1943 }
1944 });
1945 }),
1946 ],
1947 tasks_update_task: None,
1948 linked_edit_ranges: Default::default(),
1949 previous_search_ranges: None,
1950 breadcrumb_header: None,
1951 focused_block: None,
1952 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1953 addons: HashMap::default(),
1954 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1955 };
1956 this.tasks_update_task = Some(this.refresh_runnables(cx));
1957 this._subscriptions.extend(project_subscriptions);
1958
1959 this.end_selection(cx);
1960 this.scroll_manager.show_scrollbar(cx);
1961
1962 if mode == EditorMode::Full {
1963 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1964 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1965
1966 if this.git_blame_inline_enabled {
1967 this.git_blame_inline_enabled = true;
1968 this.start_git_blame_inline(false, cx);
1969 }
1970 }
1971
1972 this.report_editor_event("open", None, cx);
1973 this
1974 }
1975
1976 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
1977 self.mouse_context_menu
1978 .as_ref()
1979 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1980 }
1981
1982 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
1983 let mut key_context = KeyContext::new_with_defaults();
1984 key_context.add("Editor");
1985 let mode = match self.mode {
1986 EditorMode::SingleLine { .. } => "single_line",
1987 EditorMode::AutoHeight { .. } => "auto_height",
1988 EditorMode::Full => "full",
1989 };
1990
1991 if EditorSettings::jupyter_enabled(cx) {
1992 key_context.add("jupyter");
1993 }
1994
1995 key_context.set("mode", mode);
1996 if self.pending_rename.is_some() {
1997 key_context.add("renaming");
1998 }
1999 if self.context_menu_visible() {
2000 match self.context_menu.read().as_ref() {
2001 Some(ContextMenu::Completions(_)) => {
2002 key_context.add("menu");
2003 key_context.add("showing_completions")
2004 }
2005 Some(ContextMenu::CodeActions(_)) => {
2006 key_context.add("menu");
2007 key_context.add("showing_code_actions")
2008 }
2009 None => {}
2010 }
2011 }
2012
2013 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2014 if !self.focus_handle(cx).contains_focused(cx)
2015 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2016 {
2017 for addon in self.addons.values() {
2018 addon.extend_key_context(&mut key_context, cx)
2019 }
2020 }
2021
2022 if let Some(extension) = self
2023 .buffer
2024 .read(cx)
2025 .as_singleton()
2026 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2027 {
2028 key_context.set("extension", extension.to_string());
2029 }
2030
2031 if self.has_active_inline_completion(cx) {
2032 key_context.add("copilot_suggestion");
2033 key_context.add("inline_completion");
2034 }
2035
2036 key_context
2037 }
2038
2039 pub fn new_file(
2040 workspace: &mut Workspace,
2041 _: &workspace::NewFile,
2042 cx: &mut ViewContext<Workspace>,
2043 ) {
2044 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2045 "Failed to create buffer",
2046 cx,
2047 |e, _| match e.error_code() {
2048 ErrorCode::RemoteUpgradeRequired => Some(format!(
2049 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2050 e.error_tag("required").unwrap_or("the latest version")
2051 )),
2052 _ => None,
2053 },
2054 );
2055 }
2056
2057 pub fn new_in_workspace(
2058 workspace: &mut Workspace,
2059 cx: &mut ViewContext<Workspace>,
2060 ) -> Task<Result<View<Editor>>> {
2061 let project = workspace.project().clone();
2062 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2063
2064 cx.spawn(|workspace, mut cx| async move {
2065 let buffer = create.await?;
2066 workspace.update(&mut cx, |workspace, cx| {
2067 let editor =
2068 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2069 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2070 editor
2071 })
2072 })
2073 }
2074
2075 fn new_file_vertical(
2076 workspace: &mut Workspace,
2077 _: &workspace::NewFileSplitVertical,
2078 cx: &mut ViewContext<Workspace>,
2079 ) {
2080 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2081 }
2082
2083 fn new_file_horizontal(
2084 workspace: &mut Workspace,
2085 _: &workspace::NewFileSplitHorizontal,
2086 cx: &mut ViewContext<Workspace>,
2087 ) {
2088 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2089 }
2090
2091 fn new_file_in_direction(
2092 workspace: &mut Workspace,
2093 direction: SplitDirection,
2094 cx: &mut ViewContext<Workspace>,
2095 ) {
2096 let project = workspace.project().clone();
2097 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2098
2099 cx.spawn(|workspace, mut cx| async move {
2100 let buffer = create.await?;
2101 workspace.update(&mut cx, move |workspace, cx| {
2102 workspace.split_item(
2103 direction,
2104 Box::new(
2105 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2106 ),
2107 cx,
2108 )
2109 })?;
2110 anyhow::Ok(())
2111 })
2112 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2113 ErrorCode::RemoteUpgradeRequired => Some(format!(
2114 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2115 e.error_tag("required").unwrap_or("the latest version")
2116 )),
2117 _ => None,
2118 });
2119 }
2120
2121 pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
2122 self.buffer.read(cx).replica_id()
2123 }
2124
2125 pub fn leader_peer_id(&self) -> Option<PeerId> {
2126 self.leader_peer_id
2127 }
2128
2129 pub fn buffer(&self) -> &Model<MultiBuffer> {
2130 &self.buffer
2131 }
2132
2133 pub fn workspace(&self) -> Option<View<Workspace>> {
2134 self.workspace.as_ref()?.0.upgrade()
2135 }
2136
2137 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2138 self.buffer().read(cx).title(cx)
2139 }
2140
2141 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2142 EditorSnapshot {
2143 mode: self.mode,
2144 show_gutter: self.show_gutter,
2145 show_line_numbers: self.show_line_numbers,
2146 show_git_diff_gutter: self.show_git_diff_gutter,
2147 show_code_actions: self.show_code_actions,
2148 show_runnables: self.show_runnables,
2149 render_git_blame_gutter: self.render_git_blame_gutter(cx),
2150 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2151 scroll_anchor: self.scroll_manager.anchor(),
2152 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2153 placeholder_text: self.placeholder_text.clone(),
2154 is_focused: self.focus_handle.is_focused(cx),
2155 current_line_highlight: self
2156 .current_line_highlight
2157 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2158 gutter_hovered: self.gutter_hovered,
2159 }
2160 }
2161
2162 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2163 self.buffer.read(cx).language_at(point, cx)
2164 }
2165
2166 pub fn file_at<T: ToOffset>(
2167 &self,
2168 point: T,
2169 cx: &AppContext,
2170 ) -> Option<Arc<dyn language::File>> {
2171 self.buffer.read(cx).read(cx).file_at(point).cloned()
2172 }
2173
2174 pub fn active_excerpt(
2175 &self,
2176 cx: &AppContext,
2177 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2178 self.buffer
2179 .read(cx)
2180 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2181 }
2182
2183 pub fn mode(&self) -> EditorMode {
2184 self.mode
2185 }
2186
2187 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2188 self.collaboration_hub.as_deref()
2189 }
2190
2191 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2192 self.collaboration_hub = Some(hub);
2193 }
2194
2195 pub fn set_custom_context_menu(
2196 &mut self,
2197 f: impl 'static
2198 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2199 ) {
2200 self.custom_context_menu = Some(Box::new(f))
2201 }
2202
2203 pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
2204 self.completion_provider = Some(provider);
2205 }
2206
2207 pub fn set_inline_completion_provider<T>(
2208 &mut self,
2209 provider: Option<Model<T>>,
2210 cx: &mut ViewContext<Self>,
2211 ) where
2212 T: InlineCompletionProvider,
2213 {
2214 self.inline_completion_provider =
2215 provider.map(|provider| RegisteredInlineCompletionProvider {
2216 _subscription: cx.observe(&provider, |this, _, cx| {
2217 if this.focus_handle.is_focused(cx) {
2218 this.update_visible_inline_completion(cx);
2219 }
2220 }),
2221 provider: Arc::new(provider),
2222 });
2223 self.refresh_inline_completion(false, false, cx);
2224 }
2225
2226 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2227 self.placeholder_text.as_deref()
2228 }
2229
2230 pub fn set_placeholder_text(
2231 &mut self,
2232 placeholder_text: impl Into<Arc<str>>,
2233 cx: &mut ViewContext<Self>,
2234 ) {
2235 let placeholder_text = Some(placeholder_text.into());
2236 if self.placeholder_text != placeholder_text {
2237 self.placeholder_text = placeholder_text;
2238 cx.notify();
2239 }
2240 }
2241
2242 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2243 self.cursor_shape = cursor_shape;
2244
2245 // Disrupt blink for immediate user feedback that the cursor shape has changed
2246 self.blink_manager.update(cx, BlinkManager::show_cursor);
2247
2248 cx.notify();
2249 }
2250
2251 pub fn set_current_line_highlight(
2252 &mut self,
2253 current_line_highlight: Option<CurrentLineHighlight>,
2254 ) {
2255 self.current_line_highlight = current_line_highlight;
2256 }
2257
2258 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2259 self.collapse_matches = collapse_matches;
2260 }
2261
2262 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2263 if self.collapse_matches {
2264 return range.start..range.start;
2265 }
2266 range.clone()
2267 }
2268
2269 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2270 if self.display_map.read(cx).clip_at_line_ends != clip {
2271 self.display_map
2272 .update(cx, |map, _| map.clip_at_line_ends = clip);
2273 }
2274 }
2275
2276 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2277 self.input_enabled = input_enabled;
2278 }
2279
2280 pub fn set_autoindent(&mut self, autoindent: bool) {
2281 if autoindent {
2282 self.autoindent_mode = Some(AutoindentMode::EachLine);
2283 } else {
2284 self.autoindent_mode = None;
2285 }
2286 }
2287
2288 pub fn read_only(&self, cx: &AppContext) -> bool {
2289 self.read_only || self.buffer.read(cx).read_only()
2290 }
2291
2292 pub fn set_read_only(&mut self, read_only: bool) {
2293 self.read_only = read_only;
2294 }
2295
2296 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2297 self.use_autoclose = autoclose;
2298 }
2299
2300 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2301 self.use_auto_surround = auto_surround;
2302 }
2303
2304 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2305 self.auto_replace_emoji_shortcode = auto_replace;
2306 }
2307
2308 pub fn set_show_inline_completions(&mut self, show_inline_completions: bool) {
2309 self.show_inline_completions = show_inline_completions;
2310 }
2311
2312 pub fn set_use_modal_editing(&mut self, to: bool) {
2313 self.use_modal_editing = to;
2314 }
2315
2316 pub fn use_modal_editing(&self) -> bool {
2317 self.use_modal_editing
2318 }
2319
2320 fn selections_did_change(
2321 &mut self,
2322 local: bool,
2323 old_cursor_position: &Anchor,
2324 show_completions: bool,
2325 cx: &mut ViewContext<Self>,
2326 ) {
2327 // Copy selections to primary selection buffer
2328 #[cfg(target_os = "linux")]
2329 if local {
2330 let selections = self.selections.all::<usize>(cx);
2331 let buffer_handle = self.buffer.read(cx).read(cx);
2332
2333 let mut text = String::new();
2334 for (index, selection) in selections.iter().enumerate() {
2335 let text_for_selection = buffer_handle
2336 .text_for_range(selection.start..selection.end)
2337 .collect::<String>();
2338
2339 text.push_str(&text_for_selection);
2340 if index != selections.len() - 1 {
2341 text.push('\n');
2342 }
2343 }
2344
2345 if !text.is_empty() {
2346 cx.write_to_primary(ClipboardItem::new_string(text));
2347 }
2348 }
2349
2350 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2351 self.buffer.update(cx, |buffer, cx| {
2352 buffer.set_active_selections(
2353 &self.selections.disjoint_anchors(),
2354 self.selections.line_mode,
2355 self.cursor_shape,
2356 cx,
2357 )
2358 });
2359 }
2360 let display_map = self
2361 .display_map
2362 .update(cx, |display_map, cx| display_map.snapshot(cx));
2363 let buffer = &display_map.buffer_snapshot;
2364 self.add_selections_state = None;
2365 self.select_next_state = None;
2366 self.select_prev_state = None;
2367 self.select_larger_syntax_node_stack.clear();
2368 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2369 self.snippet_stack
2370 .invalidate(&self.selections.disjoint_anchors(), buffer);
2371 self.take_rename(false, cx);
2372
2373 let new_cursor_position = self.selections.newest_anchor().head();
2374
2375 self.push_to_nav_history(
2376 *old_cursor_position,
2377 Some(new_cursor_position.to_point(buffer)),
2378 cx,
2379 );
2380
2381 if local {
2382 let new_cursor_position = self.selections.newest_anchor().head();
2383 let mut context_menu = self.context_menu.write();
2384 let completion_menu = match context_menu.as_ref() {
2385 Some(ContextMenu::Completions(menu)) => Some(menu),
2386
2387 _ => {
2388 *context_menu = None;
2389 None
2390 }
2391 };
2392
2393 if let Some(completion_menu) = completion_menu {
2394 let cursor_position = new_cursor_position.to_offset(buffer);
2395 let (word_range, kind) = buffer.surrounding_word(completion_menu.initial_position);
2396 if kind == Some(CharKind::Word)
2397 && word_range.to_inclusive().contains(&cursor_position)
2398 {
2399 let mut completion_menu = completion_menu.clone();
2400 drop(context_menu);
2401
2402 let query = Self::completion_query(buffer, cursor_position);
2403 cx.spawn(move |this, mut cx| async move {
2404 completion_menu
2405 .filter(query.as_deref(), cx.background_executor().clone())
2406 .await;
2407
2408 this.update(&mut cx, |this, cx| {
2409 let mut context_menu = this.context_menu.write();
2410 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2411 return;
2412 };
2413
2414 if menu.id > completion_menu.id {
2415 return;
2416 }
2417
2418 *context_menu = Some(ContextMenu::Completions(completion_menu));
2419 drop(context_menu);
2420 cx.notify();
2421 })
2422 })
2423 .detach();
2424
2425 if show_completions {
2426 self.show_completions(&ShowCompletions { trigger: None }, cx);
2427 }
2428 } else {
2429 drop(context_menu);
2430 self.hide_context_menu(cx);
2431 }
2432 } else {
2433 drop(context_menu);
2434 }
2435
2436 hide_hover(self, cx);
2437
2438 if old_cursor_position.to_display_point(&display_map).row()
2439 != new_cursor_position.to_display_point(&display_map).row()
2440 {
2441 self.available_code_actions.take();
2442 }
2443 self.refresh_code_actions(cx);
2444 self.refresh_document_highlights(cx);
2445 refresh_matching_bracket_highlights(self, cx);
2446 self.discard_inline_completion(false, cx);
2447 linked_editing_ranges::refresh_linked_ranges(self, cx);
2448 if self.git_blame_inline_enabled {
2449 self.start_inline_blame_timer(cx);
2450 }
2451 }
2452
2453 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2454 cx.emit(EditorEvent::SelectionsChanged { local });
2455
2456 if self.selections.disjoint_anchors().len() == 1 {
2457 cx.emit(SearchEvent::ActiveMatchChanged)
2458 }
2459 cx.notify();
2460 }
2461
2462 pub fn change_selections<R>(
2463 &mut self,
2464 autoscroll: Option<Autoscroll>,
2465 cx: &mut ViewContext<Self>,
2466 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2467 ) -> R {
2468 self.change_selections_inner(autoscroll, true, cx, change)
2469 }
2470
2471 pub fn change_selections_inner<R>(
2472 &mut self,
2473 autoscroll: Option<Autoscroll>,
2474 request_completions: bool,
2475 cx: &mut ViewContext<Self>,
2476 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2477 ) -> R {
2478 let old_cursor_position = self.selections.newest_anchor().head();
2479 self.push_to_selection_history();
2480
2481 let (changed, result) = self.selections.change_with(cx, change);
2482
2483 if changed {
2484 if let Some(autoscroll) = autoscroll {
2485 self.request_autoscroll(autoscroll, cx);
2486 }
2487 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2488
2489 if self.should_open_signature_help_automatically(
2490 &old_cursor_position,
2491 self.signature_help_state.backspace_pressed(),
2492 cx,
2493 ) {
2494 self.show_signature_help(&ShowSignatureHelp, cx);
2495 }
2496 self.signature_help_state.set_backspace_pressed(false);
2497 }
2498
2499 result
2500 }
2501
2502 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2503 where
2504 I: IntoIterator<Item = (Range<S>, T)>,
2505 S: ToOffset,
2506 T: Into<Arc<str>>,
2507 {
2508 if self.read_only(cx) {
2509 return;
2510 }
2511
2512 self.buffer
2513 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2514 }
2515
2516 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2517 where
2518 I: IntoIterator<Item = (Range<S>, T)>,
2519 S: ToOffset,
2520 T: Into<Arc<str>>,
2521 {
2522 if self.read_only(cx) {
2523 return;
2524 }
2525
2526 self.buffer.update(cx, |buffer, cx| {
2527 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2528 });
2529 }
2530
2531 pub fn edit_with_block_indent<I, S, T>(
2532 &mut self,
2533 edits: I,
2534 original_indent_columns: Vec<u32>,
2535 cx: &mut ViewContext<Self>,
2536 ) where
2537 I: IntoIterator<Item = (Range<S>, T)>,
2538 S: ToOffset,
2539 T: Into<Arc<str>>,
2540 {
2541 if self.read_only(cx) {
2542 return;
2543 }
2544
2545 self.buffer.update(cx, |buffer, cx| {
2546 buffer.edit(
2547 edits,
2548 Some(AutoindentMode::Block {
2549 original_indent_columns,
2550 }),
2551 cx,
2552 )
2553 });
2554 }
2555
2556 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2557 self.hide_context_menu(cx);
2558
2559 match phase {
2560 SelectPhase::Begin {
2561 position,
2562 add,
2563 click_count,
2564 } => self.begin_selection(position, add, click_count, cx),
2565 SelectPhase::BeginColumnar {
2566 position,
2567 goal_column,
2568 reset,
2569 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2570 SelectPhase::Extend {
2571 position,
2572 click_count,
2573 } => self.extend_selection(position, click_count, cx),
2574 SelectPhase::Update {
2575 position,
2576 goal_column,
2577 scroll_delta,
2578 } => self.update_selection(position, goal_column, scroll_delta, cx),
2579 SelectPhase::End => self.end_selection(cx),
2580 }
2581 }
2582
2583 fn extend_selection(
2584 &mut self,
2585 position: DisplayPoint,
2586 click_count: usize,
2587 cx: &mut ViewContext<Self>,
2588 ) {
2589 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2590 let tail = self.selections.newest::<usize>(cx).tail();
2591 self.begin_selection(position, false, click_count, cx);
2592
2593 let position = position.to_offset(&display_map, Bias::Left);
2594 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2595
2596 let mut pending_selection = self
2597 .selections
2598 .pending_anchor()
2599 .expect("extend_selection not called with pending selection");
2600 if position >= tail {
2601 pending_selection.start = tail_anchor;
2602 } else {
2603 pending_selection.end = tail_anchor;
2604 pending_selection.reversed = true;
2605 }
2606
2607 let mut pending_mode = self.selections.pending_mode().unwrap();
2608 match &mut pending_mode {
2609 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2610 _ => {}
2611 }
2612
2613 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2614 s.set_pending(pending_selection, pending_mode)
2615 });
2616 }
2617
2618 fn begin_selection(
2619 &mut self,
2620 position: DisplayPoint,
2621 add: bool,
2622 click_count: usize,
2623 cx: &mut ViewContext<Self>,
2624 ) {
2625 if !self.focus_handle.is_focused(cx) {
2626 self.last_focused_descendant = None;
2627 cx.focus(&self.focus_handle);
2628 }
2629
2630 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2631 let buffer = &display_map.buffer_snapshot;
2632 let newest_selection = self.selections.newest_anchor().clone();
2633 let position = display_map.clip_point(position, Bias::Left);
2634
2635 let start;
2636 let end;
2637 let mode;
2638 let auto_scroll;
2639 match click_count {
2640 1 => {
2641 start = buffer.anchor_before(position.to_point(&display_map));
2642 end = start;
2643 mode = SelectMode::Character;
2644 auto_scroll = true;
2645 }
2646 2 => {
2647 let range = movement::surrounding_word(&display_map, position);
2648 start = buffer.anchor_before(range.start.to_point(&display_map));
2649 end = buffer.anchor_before(range.end.to_point(&display_map));
2650 mode = SelectMode::Word(start..end);
2651 auto_scroll = true;
2652 }
2653 3 => {
2654 let position = display_map
2655 .clip_point(position, Bias::Left)
2656 .to_point(&display_map);
2657 let line_start = display_map.prev_line_boundary(position).0;
2658 let next_line_start = buffer.clip_point(
2659 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2660 Bias::Left,
2661 );
2662 start = buffer.anchor_before(line_start);
2663 end = buffer.anchor_before(next_line_start);
2664 mode = SelectMode::Line(start..end);
2665 auto_scroll = true;
2666 }
2667 _ => {
2668 start = buffer.anchor_before(0);
2669 end = buffer.anchor_before(buffer.len());
2670 mode = SelectMode::All;
2671 auto_scroll = false;
2672 }
2673 }
2674
2675 let point_to_delete: Option<usize> = {
2676 let selected_points: Vec<Selection<Point>> =
2677 self.selections.disjoint_in_range(start..end, cx);
2678
2679 if !add || click_count > 1 {
2680 None
2681 } else if selected_points.len() > 0 {
2682 Some(selected_points[0].id)
2683 } else {
2684 let clicked_point_already_selected =
2685 self.selections.disjoint.iter().find(|selection| {
2686 selection.start.to_point(buffer) == start.to_point(buffer)
2687 || selection.end.to_point(buffer) == end.to_point(buffer)
2688 });
2689
2690 if let Some(selection) = clicked_point_already_selected {
2691 Some(selection.id)
2692 } else {
2693 None
2694 }
2695 }
2696 };
2697
2698 let selections_count = self.selections.count();
2699
2700 self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
2701 if let Some(point_to_delete) = point_to_delete {
2702 s.delete(point_to_delete);
2703
2704 if selections_count == 1 {
2705 s.set_pending_anchor_range(start..end, mode);
2706 }
2707 } else {
2708 if !add {
2709 s.clear_disjoint();
2710 } else if click_count > 1 {
2711 s.delete(newest_selection.id)
2712 }
2713
2714 s.set_pending_anchor_range(start..end, mode);
2715 }
2716 });
2717 }
2718
2719 fn begin_columnar_selection(
2720 &mut self,
2721 position: DisplayPoint,
2722 goal_column: u32,
2723 reset: bool,
2724 cx: &mut ViewContext<Self>,
2725 ) {
2726 if !self.focus_handle.is_focused(cx) {
2727 self.last_focused_descendant = None;
2728 cx.focus(&self.focus_handle);
2729 }
2730
2731 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2732
2733 if reset {
2734 let pointer_position = display_map
2735 .buffer_snapshot
2736 .anchor_before(position.to_point(&display_map));
2737
2738 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2739 s.clear_disjoint();
2740 s.set_pending_anchor_range(
2741 pointer_position..pointer_position,
2742 SelectMode::Character,
2743 );
2744 });
2745 }
2746
2747 let tail = self.selections.newest::<Point>(cx).tail();
2748 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2749
2750 if !reset {
2751 self.select_columns(
2752 tail.to_display_point(&display_map),
2753 position,
2754 goal_column,
2755 &display_map,
2756 cx,
2757 );
2758 }
2759 }
2760
2761 fn update_selection(
2762 &mut self,
2763 position: DisplayPoint,
2764 goal_column: u32,
2765 scroll_delta: gpui::Point<f32>,
2766 cx: &mut ViewContext<Self>,
2767 ) {
2768 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2769
2770 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2771 let tail = tail.to_display_point(&display_map);
2772 self.select_columns(tail, position, goal_column, &display_map, cx);
2773 } else if let Some(mut pending) = self.selections.pending_anchor() {
2774 let buffer = self.buffer.read(cx).snapshot(cx);
2775 let head;
2776 let tail;
2777 let mode = self.selections.pending_mode().unwrap();
2778 match &mode {
2779 SelectMode::Character => {
2780 head = position.to_point(&display_map);
2781 tail = pending.tail().to_point(&buffer);
2782 }
2783 SelectMode::Word(original_range) => {
2784 let original_display_range = original_range.start.to_display_point(&display_map)
2785 ..original_range.end.to_display_point(&display_map);
2786 let original_buffer_range = original_display_range.start.to_point(&display_map)
2787 ..original_display_range.end.to_point(&display_map);
2788 if movement::is_inside_word(&display_map, position)
2789 || original_display_range.contains(&position)
2790 {
2791 let word_range = movement::surrounding_word(&display_map, position);
2792 if word_range.start < original_display_range.start {
2793 head = word_range.start.to_point(&display_map);
2794 } else {
2795 head = word_range.end.to_point(&display_map);
2796 }
2797 } else {
2798 head = position.to_point(&display_map);
2799 }
2800
2801 if head <= original_buffer_range.start {
2802 tail = original_buffer_range.end;
2803 } else {
2804 tail = original_buffer_range.start;
2805 }
2806 }
2807 SelectMode::Line(original_range) => {
2808 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2809
2810 let position = display_map
2811 .clip_point(position, Bias::Left)
2812 .to_point(&display_map);
2813 let line_start = display_map.prev_line_boundary(position).0;
2814 let next_line_start = buffer.clip_point(
2815 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2816 Bias::Left,
2817 );
2818
2819 if line_start < original_range.start {
2820 head = line_start
2821 } else {
2822 head = next_line_start
2823 }
2824
2825 if head <= original_range.start {
2826 tail = original_range.end;
2827 } else {
2828 tail = original_range.start;
2829 }
2830 }
2831 SelectMode::All => {
2832 return;
2833 }
2834 };
2835
2836 if head < tail {
2837 pending.start = buffer.anchor_before(head);
2838 pending.end = buffer.anchor_before(tail);
2839 pending.reversed = true;
2840 } else {
2841 pending.start = buffer.anchor_before(tail);
2842 pending.end = buffer.anchor_before(head);
2843 pending.reversed = false;
2844 }
2845
2846 self.change_selections(None, cx, |s| {
2847 s.set_pending(pending, mode);
2848 });
2849 } else {
2850 log::error!("update_selection dispatched with no pending selection");
2851 return;
2852 }
2853
2854 self.apply_scroll_delta(scroll_delta, cx);
2855 cx.notify();
2856 }
2857
2858 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2859 self.columnar_selection_tail.take();
2860 if self.selections.pending_anchor().is_some() {
2861 let selections = self.selections.all::<usize>(cx);
2862 self.change_selections(None, cx, |s| {
2863 s.select(selections);
2864 s.clear_pending();
2865 });
2866 }
2867 }
2868
2869 fn select_columns(
2870 &mut self,
2871 tail: DisplayPoint,
2872 head: DisplayPoint,
2873 goal_column: u32,
2874 display_map: &DisplaySnapshot,
2875 cx: &mut ViewContext<Self>,
2876 ) {
2877 let start_row = cmp::min(tail.row(), head.row());
2878 let end_row = cmp::max(tail.row(), head.row());
2879 let start_column = cmp::min(tail.column(), goal_column);
2880 let end_column = cmp::max(tail.column(), goal_column);
2881 let reversed = start_column < tail.column();
2882
2883 let selection_ranges = (start_row.0..=end_row.0)
2884 .map(DisplayRow)
2885 .filter_map(|row| {
2886 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2887 let start = display_map
2888 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2889 .to_point(display_map);
2890 let end = display_map
2891 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2892 .to_point(display_map);
2893 if reversed {
2894 Some(end..start)
2895 } else {
2896 Some(start..end)
2897 }
2898 } else {
2899 None
2900 }
2901 })
2902 .collect::<Vec<_>>();
2903
2904 self.change_selections(None, cx, |s| {
2905 s.select_ranges(selection_ranges);
2906 });
2907 cx.notify();
2908 }
2909
2910 pub fn has_pending_nonempty_selection(&self) -> bool {
2911 let pending_nonempty_selection = match self.selections.pending_anchor() {
2912 Some(Selection { start, end, .. }) => start != end,
2913 None => false,
2914 };
2915
2916 pending_nonempty_selection
2917 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2918 }
2919
2920 pub fn has_pending_selection(&self) -> bool {
2921 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2922 }
2923
2924 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2925 if self.clear_clicked_diff_hunks(cx) {
2926 cx.notify();
2927 return;
2928 }
2929 if self.dismiss_menus_and_popups(true, cx) {
2930 return;
2931 }
2932
2933 if self.mode == EditorMode::Full {
2934 if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
2935 return;
2936 }
2937 }
2938
2939 cx.propagate();
2940 }
2941
2942 pub fn dismiss_menus_and_popups(
2943 &mut self,
2944 should_report_inline_completion_event: bool,
2945 cx: &mut ViewContext<Self>,
2946 ) -> bool {
2947 if self.take_rename(false, cx).is_some() {
2948 return true;
2949 }
2950
2951 if hide_hover(self, cx) {
2952 return true;
2953 }
2954
2955 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2956 return true;
2957 }
2958
2959 if self.hide_context_menu(cx).is_some() {
2960 return true;
2961 }
2962
2963 if self.mouse_context_menu.take().is_some() {
2964 return true;
2965 }
2966
2967 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2968 return true;
2969 }
2970
2971 if self.snippet_stack.pop().is_some() {
2972 return true;
2973 }
2974
2975 if self.mode == EditorMode::Full {
2976 if self.active_diagnostics.is_some() {
2977 self.dismiss_diagnostics(cx);
2978 return true;
2979 }
2980 }
2981
2982 false
2983 }
2984
2985 fn linked_editing_ranges_for(
2986 &self,
2987 selection: Range<text::Anchor>,
2988 cx: &AppContext,
2989 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2990 if self.linked_edit_ranges.is_empty() {
2991 return None;
2992 }
2993 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2994 selection.end.buffer_id.and_then(|end_buffer_id| {
2995 if selection.start.buffer_id != Some(end_buffer_id) {
2996 return None;
2997 }
2998 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2999 let snapshot = buffer.read(cx).snapshot();
3000 self.linked_edit_ranges
3001 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3002 .map(|ranges| (ranges, snapshot, buffer))
3003 })?;
3004 use text::ToOffset as TO;
3005 // find offset from the start of current range to current cursor position
3006 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3007
3008 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3009 let start_difference = start_offset - start_byte_offset;
3010 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3011 let end_difference = end_offset - start_byte_offset;
3012 // Current range has associated linked ranges.
3013 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3014 for range in linked_ranges.iter() {
3015 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3016 let end_offset = start_offset + end_difference;
3017 let start_offset = start_offset + start_difference;
3018 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3019 continue;
3020 }
3021 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3022 if s.start.buffer_id != selection.start.buffer_id
3023 || s.end.buffer_id != selection.end.buffer_id
3024 {
3025 return false;
3026 }
3027 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3028 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3029 }) {
3030 continue;
3031 }
3032 let start = buffer_snapshot.anchor_after(start_offset);
3033 let end = buffer_snapshot.anchor_after(end_offset);
3034 linked_edits
3035 .entry(buffer.clone())
3036 .or_default()
3037 .push(start..end);
3038 }
3039 Some(linked_edits)
3040 }
3041
3042 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3043 let text: Arc<str> = text.into();
3044
3045 if self.read_only(cx) {
3046 return;
3047 }
3048
3049 let selections = self.selections.all_adjusted(cx);
3050 let mut bracket_inserted = false;
3051 let mut edits = Vec::new();
3052 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3053 let mut new_selections = Vec::with_capacity(selections.len());
3054 let mut new_autoclose_regions = Vec::new();
3055 let snapshot = self.buffer.read(cx).read(cx);
3056
3057 for (selection, autoclose_region) in
3058 self.selections_with_autoclose_regions(selections, &snapshot)
3059 {
3060 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3061 // Determine if the inserted text matches the opening or closing
3062 // bracket of any of this language's bracket pairs.
3063 let mut bracket_pair = None;
3064 let mut is_bracket_pair_start = false;
3065 let mut is_bracket_pair_end = false;
3066 if !text.is_empty() {
3067 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3068 // and they are removing the character that triggered IME popup.
3069 for (pair, enabled) in scope.brackets() {
3070 if !pair.close && !pair.surround {
3071 continue;
3072 }
3073
3074 if enabled && pair.start.ends_with(text.as_ref()) {
3075 bracket_pair = Some(pair.clone());
3076 is_bracket_pair_start = true;
3077 break;
3078 }
3079 if pair.end.as_str() == text.as_ref() {
3080 bracket_pair = Some(pair.clone());
3081 is_bracket_pair_end = true;
3082 break;
3083 }
3084 }
3085 }
3086
3087 if let Some(bracket_pair) = bracket_pair {
3088 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3089 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3090 let auto_surround =
3091 self.use_auto_surround && snapshot_settings.use_auto_surround;
3092 if selection.is_empty() {
3093 if is_bracket_pair_start {
3094 let prefix_len = bracket_pair.start.len() - text.len();
3095
3096 // If the inserted text is a suffix of an opening bracket and the
3097 // selection is preceded by the rest of the opening bracket, then
3098 // insert the closing bracket.
3099 let following_text_allows_autoclose = snapshot
3100 .chars_at(selection.start)
3101 .next()
3102 .map_or(true, |c| scope.should_autoclose_before(c));
3103 let preceding_text_matches_prefix = prefix_len == 0
3104 || (selection.start.column >= (prefix_len as u32)
3105 && snapshot.contains_str_at(
3106 Point::new(
3107 selection.start.row,
3108 selection.start.column - (prefix_len as u32),
3109 ),
3110 &bracket_pair.start[..prefix_len],
3111 ));
3112
3113 if autoclose
3114 && bracket_pair.close
3115 && following_text_allows_autoclose
3116 && preceding_text_matches_prefix
3117 {
3118 let anchor = snapshot.anchor_before(selection.end);
3119 new_selections.push((selection.map(|_| anchor), text.len()));
3120 new_autoclose_regions.push((
3121 anchor,
3122 text.len(),
3123 selection.id,
3124 bracket_pair.clone(),
3125 ));
3126 edits.push((
3127 selection.range(),
3128 format!("{}{}", text, bracket_pair.end).into(),
3129 ));
3130 bracket_inserted = true;
3131 continue;
3132 }
3133 }
3134
3135 if let Some(region) = autoclose_region {
3136 // If the selection is followed by an auto-inserted closing bracket,
3137 // then don't insert that closing bracket again; just move the selection
3138 // past the closing bracket.
3139 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3140 && text.as_ref() == region.pair.end.as_str();
3141 if should_skip {
3142 let anchor = snapshot.anchor_after(selection.end);
3143 new_selections
3144 .push((selection.map(|_| anchor), region.pair.end.len()));
3145 continue;
3146 }
3147 }
3148
3149 let always_treat_brackets_as_autoclosed = snapshot
3150 .settings_at(selection.start, cx)
3151 .always_treat_brackets_as_autoclosed;
3152 if always_treat_brackets_as_autoclosed
3153 && is_bracket_pair_end
3154 && snapshot.contains_str_at(selection.end, text.as_ref())
3155 {
3156 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3157 // and the inserted text is a closing bracket and the selection is followed
3158 // by the closing bracket then move the selection past the closing bracket.
3159 let anchor = snapshot.anchor_after(selection.end);
3160 new_selections.push((selection.map(|_| anchor), text.len()));
3161 continue;
3162 }
3163 }
3164 // If an opening bracket is 1 character long and is typed while
3165 // text is selected, then surround that text with the bracket pair.
3166 else if auto_surround
3167 && bracket_pair.surround
3168 && is_bracket_pair_start
3169 && bracket_pair.start.chars().count() == 1
3170 {
3171 edits.push((selection.start..selection.start, text.clone()));
3172 edits.push((
3173 selection.end..selection.end,
3174 bracket_pair.end.as_str().into(),
3175 ));
3176 bracket_inserted = true;
3177 new_selections.push((
3178 Selection {
3179 id: selection.id,
3180 start: snapshot.anchor_after(selection.start),
3181 end: snapshot.anchor_before(selection.end),
3182 reversed: selection.reversed,
3183 goal: selection.goal,
3184 },
3185 0,
3186 ));
3187 continue;
3188 }
3189 }
3190 }
3191
3192 if self.auto_replace_emoji_shortcode
3193 && selection.is_empty()
3194 && text.as_ref().ends_with(':')
3195 {
3196 if let Some(possible_emoji_short_code) =
3197 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3198 {
3199 if !possible_emoji_short_code.is_empty() {
3200 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3201 let emoji_shortcode_start = Point::new(
3202 selection.start.row,
3203 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3204 );
3205
3206 // Remove shortcode from buffer
3207 edits.push((
3208 emoji_shortcode_start..selection.start,
3209 "".to_string().into(),
3210 ));
3211 new_selections.push((
3212 Selection {
3213 id: selection.id,
3214 start: snapshot.anchor_after(emoji_shortcode_start),
3215 end: snapshot.anchor_before(selection.start),
3216 reversed: selection.reversed,
3217 goal: selection.goal,
3218 },
3219 0,
3220 ));
3221
3222 // Insert emoji
3223 let selection_start_anchor = snapshot.anchor_after(selection.start);
3224 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3225 edits.push((selection.start..selection.end, emoji.to_string().into()));
3226
3227 continue;
3228 }
3229 }
3230 }
3231 }
3232
3233 // If not handling any auto-close operation, then just replace the selected
3234 // text with the given input and move the selection to the end of the
3235 // newly inserted text.
3236 let anchor = snapshot.anchor_after(selection.end);
3237 if !self.linked_edit_ranges.is_empty() {
3238 let start_anchor = snapshot.anchor_before(selection.start);
3239
3240 let is_word_char = text.chars().next().map_or(true, |char| {
3241 let scope = snapshot.language_scope_at(start_anchor.to_offset(&snapshot));
3242 let kind = char_kind(&scope, char);
3243
3244 kind == CharKind::Word
3245 });
3246
3247 if is_word_char {
3248 if let Some(ranges) = self
3249 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3250 {
3251 for (buffer, edits) in ranges {
3252 linked_edits
3253 .entry(buffer.clone())
3254 .or_default()
3255 .extend(edits.into_iter().map(|range| (range, text.clone())));
3256 }
3257 }
3258 }
3259 }
3260
3261 new_selections.push((selection.map(|_| anchor), 0));
3262 edits.push((selection.start..selection.end, text.clone()));
3263 }
3264
3265 drop(snapshot);
3266
3267 self.transact(cx, |this, cx| {
3268 this.buffer.update(cx, |buffer, cx| {
3269 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3270 });
3271 for (buffer, edits) in linked_edits {
3272 buffer.update(cx, |buffer, cx| {
3273 let snapshot = buffer.snapshot();
3274 let edits = edits
3275 .into_iter()
3276 .map(|(range, text)| {
3277 use text::ToPoint as TP;
3278 let end_point = TP::to_point(&range.end, &snapshot);
3279 let start_point = TP::to_point(&range.start, &snapshot);
3280 (start_point..end_point, text)
3281 })
3282 .sorted_by_key(|(range, _)| range.start)
3283 .collect::<Vec<_>>();
3284 buffer.edit(edits, None, cx);
3285 })
3286 }
3287 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3288 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3289 let snapshot = this.buffer.read(cx).read(cx);
3290 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3291 .zip(new_selection_deltas)
3292 .map(|(selection, delta)| Selection {
3293 id: selection.id,
3294 start: selection.start + delta,
3295 end: selection.end + delta,
3296 reversed: selection.reversed,
3297 goal: SelectionGoal::None,
3298 })
3299 .collect::<Vec<_>>();
3300
3301 let mut i = 0;
3302 for (position, delta, selection_id, pair) in new_autoclose_regions {
3303 let position = position.to_offset(&snapshot) + delta;
3304 let start = snapshot.anchor_before(position);
3305 let end = snapshot.anchor_after(position);
3306 while let Some(existing_state) = this.autoclose_regions.get(i) {
3307 match existing_state.range.start.cmp(&start, &snapshot) {
3308 Ordering::Less => i += 1,
3309 Ordering::Greater => break,
3310 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3311 Ordering::Less => i += 1,
3312 Ordering::Equal => break,
3313 Ordering::Greater => break,
3314 },
3315 }
3316 }
3317 this.autoclose_regions.insert(
3318 i,
3319 AutocloseRegion {
3320 selection_id,
3321 range: start..end,
3322 pair,
3323 },
3324 );
3325 }
3326
3327 drop(snapshot);
3328 let had_active_inline_completion = this.has_active_inline_completion(cx);
3329 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3330 s.select(new_selections)
3331 });
3332
3333 if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
3334 if let Some(on_type_format_task) =
3335 this.trigger_on_type_formatting(text.to_string(), cx)
3336 {
3337 on_type_format_task.detach_and_log_err(cx);
3338 }
3339 }
3340
3341 let editor_settings = EditorSettings::get_global(cx);
3342 if bracket_inserted
3343 && (editor_settings.auto_signature_help
3344 || editor_settings.show_signature_help_after_edits)
3345 {
3346 this.show_signature_help(&ShowSignatureHelp, cx);
3347 }
3348
3349 let trigger_in_words = !had_active_inline_completion;
3350 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3351 linked_editing_ranges::refresh_linked_ranges(this, cx);
3352 this.refresh_inline_completion(true, false, cx);
3353 });
3354 }
3355
3356 fn find_possible_emoji_shortcode_at_position(
3357 snapshot: &MultiBufferSnapshot,
3358 position: Point,
3359 ) -> Option<String> {
3360 let mut chars = Vec::new();
3361 let mut found_colon = false;
3362 for char in snapshot.reversed_chars_at(position).take(100) {
3363 // Found a possible emoji shortcode in the middle of the buffer
3364 if found_colon {
3365 if char.is_whitespace() {
3366 chars.reverse();
3367 return Some(chars.iter().collect());
3368 }
3369 // If the previous character is not a whitespace, we are in the middle of a word
3370 // and we only want to complete the shortcode if the word is made up of other emojis
3371 let mut containing_word = String::new();
3372 for ch in snapshot
3373 .reversed_chars_at(position)
3374 .skip(chars.len() + 1)
3375 .take(100)
3376 {
3377 if ch.is_whitespace() {
3378 break;
3379 }
3380 containing_word.push(ch);
3381 }
3382 let containing_word = containing_word.chars().rev().collect::<String>();
3383 if util::word_consists_of_emojis(containing_word.as_str()) {
3384 chars.reverse();
3385 return Some(chars.iter().collect());
3386 }
3387 }
3388
3389 if char.is_whitespace() || !char.is_ascii() {
3390 return None;
3391 }
3392 if char == ':' {
3393 found_colon = true;
3394 } else {
3395 chars.push(char);
3396 }
3397 }
3398 // Found a possible emoji shortcode at the beginning of the buffer
3399 chars.reverse();
3400 Some(chars.iter().collect())
3401 }
3402
3403 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3404 self.transact(cx, |this, cx| {
3405 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3406 let selections = this.selections.all::<usize>(cx);
3407 let multi_buffer = this.buffer.read(cx);
3408 let buffer = multi_buffer.snapshot(cx);
3409 selections
3410 .iter()
3411 .map(|selection| {
3412 let start_point = selection.start.to_point(&buffer);
3413 let mut indent =
3414 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3415 indent.len = cmp::min(indent.len, start_point.column);
3416 let start = selection.start;
3417 let end = selection.end;
3418 let selection_is_empty = start == end;
3419 let language_scope = buffer.language_scope_at(start);
3420 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3421 &language_scope
3422 {
3423 let leading_whitespace_len = buffer
3424 .reversed_chars_at(start)
3425 .take_while(|c| c.is_whitespace() && *c != '\n')
3426 .map(|c| c.len_utf8())
3427 .sum::<usize>();
3428
3429 let trailing_whitespace_len = buffer
3430 .chars_at(end)
3431 .take_while(|c| c.is_whitespace() && *c != '\n')
3432 .map(|c| c.len_utf8())
3433 .sum::<usize>();
3434
3435 let insert_extra_newline =
3436 language.brackets().any(|(pair, enabled)| {
3437 let pair_start = pair.start.trim_end();
3438 let pair_end = pair.end.trim_start();
3439
3440 enabled
3441 && pair.newline
3442 && buffer.contains_str_at(
3443 end + trailing_whitespace_len,
3444 pair_end,
3445 )
3446 && buffer.contains_str_at(
3447 (start - leading_whitespace_len)
3448 .saturating_sub(pair_start.len()),
3449 pair_start,
3450 )
3451 });
3452
3453 // Comment extension on newline is allowed only for cursor selections
3454 let comment_delimiter = maybe!({
3455 if !selection_is_empty {
3456 return None;
3457 }
3458
3459 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3460 return None;
3461 }
3462
3463 let delimiters = language.line_comment_prefixes();
3464 let max_len_of_delimiter =
3465 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3466 let (snapshot, range) =
3467 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3468
3469 let mut index_of_first_non_whitespace = 0;
3470 let comment_candidate = snapshot
3471 .chars_for_range(range)
3472 .skip_while(|c| {
3473 let should_skip = c.is_whitespace();
3474 if should_skip {
3475 index_of_first_non_whitespace += 1;
3476 }
3477 should_skip
3478 })
3479 .take(max_len_of_delimiter)
3480 .collect::<String>();
3481 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3482 comment_candidate.starts_with(comment_prefix.as_ref())
3483 })?;
3484 let cursor_is_placed_after_comment_marker =
3485 index_of_first_non_whitespace + comment_prefix.len()
3486 <= start_point.column as usize;
3487 if cursor_is_placed_after_comment_marker {
3488 Some(comment_prefix.clone())
3489 } else {
3490 None
3491 }
3492 });
3493 (comment_delimiter, insert_extra_newline)
3494 } else {
3495 (None, false)
3496 };
3497
3498 let capacity_for_delimiter = comment_delimiter
3499 .as_deref()
3500 .map(str::len)
3501 .unwrap_or_default();
3502 let mut new_text =
3503 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3504 new_text.push_str("\n");
3505 new_text.extend(indent.chars());
3506 if let Some(delimiter) = &comment_delimiter {
3507 new_text.push_str(&delimiter);
3508 }
3509 if insert_extra_newline {
3510 new_text = new_text.repeat(2);
3511 }
3512
3513 let anchor = buffer.anchor_after(end);
3514 let new_selection = selection.map(|_| anchor);
3515 (
3516 (start..end, new_text),
3517 (insert_extra_newline, new_selection),
3518 )
3519 })
3520 .unzip()
3521 };
3522
3523 this.edit_with_autoindent(edits, cx);
3524 let buffer = this.buffer.read(cx).snapshot(cx);
3525 let new_selections = selection_fixup_info
3526 .into_iter()
3527 .map(|(extra_newline_inserted, new_selection)| {
3528 let mut cursor = new_selection.end.to_point(&buffer);
3529 if extra_newline_inserted {
3530 cursor.row -= 1;
3531 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3532 }
3533 new_selection.map(|_| cursor)
3534 })
3535 .collect();
3536
3537 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3538 this.refresh_inline_completion(true, false, cx);
3539 });
3540 }
3541
3542 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3543 let buffer = self.buffer.read(cx);
3544 let snapshot = buffer.snapshot(cx);
3545
3546 let mut edits = Vec::new();
3547 let mut rows = Vec::new();
3548
3549 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3550 let cursor = selection.head();
3551 let row = cursor.row;
3552
3553 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3554
3555 let newline = "\n".to_string();
3556 edits.push((start_of_line..start_of_line, newline));
3557
3558 rows.push(row + rows_inserted as u32);
3559 }
3560
3561 self.transact(cx, |editor, cx| {
3562 editor.edit(edits, cx);
3563
3564 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3565 let mut index = 0;
3566 s.move_cursors_with(|map, _, _| {
3567 let row = rows[index];
3568 index += 1;
3569
3570 let point = Point::new(row, 0);
3571 let boundary = map.next_line_boundary(point).1;
3572 let clipped = map.clip_point(boundary, Bias::Left);
3573
3574 (clipped, SelectionGoal::None)
3575 });
3576 });
3577
3578 let mut indent_edits = Vec::new();
3579 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3580 for row in rows {
3581 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3582 for (row, indent) in indents {
3583 if indent.len == 0 {
3584 continue;
3585 }
3586
3587 let text = match indent.kind {
3588 IndentKind::Space => " ".repeat(indent.len as usize),
3589 IndentKind::Tab => "\t".repeat(indent.len as usize),
3590 };
3591 let point = Point::new(row.0, 0);
3592 indent_edits.push((point..point, text));
3593 }
3594 }
3595 editor.edit(indent_edits, cx);
3596 });
3597 }
3598
3599 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3600 let buffer = self.buffer.read(cx);
3601 let snapshot = buffer.snapshot(cx);
3602
3603 let mut edits = Vec::new();
3604 let mut rows = Vec::new();
3605 let mut rows_inserted = 0;
3606
3607 for selection in self.selections.all_adjusted(cx) {
3608 let cursor = selection.head();
3609 let row = cursor.row;
3610
3611 let point = Point::new(row + 1, 0);
3612 let start_of_line = snapshot.clip_point(point, Bias::Left);
3613
3614 let newline = "\n".to_string();
3615 edits.push((start_of_line..start_of_line, newline));
3616
3617 rows_inserted += 1;
3618 rows.push(row + rows_inserted);
3619 }
3620
3621 self.transact(cx, |editor, cx| {
3622 editor.edit(edits, cx);
3623
3624 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3625 let mut index = 0;
3626 s.move_cursors_with(|map, _, _| {
3627 let row = rows[index];
3628 index += 1;
3629
3630 let point = Point::new(row, 0);
3631 let boundary = map.next_line_boundary(point).1;
3632 let clipped = map.clip_point(boundary, Bias::Left);
3633
3634 (clipped, SelectionGoal::None)
3635 });
3636 });
3637
3638 let mut indent_edits = Vec::new();
3639 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3640 for row in rows {
3641 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3642 for (row, indent) in indents {
3643 if indent.len == 0 {
3644 continue;
3645 }
3646
3647 let text = match indent.kind {
3648 IndentKind::Space => " ".repeat(indent.len as usize),
3649 IndentKind::Tab => "\t".repeat(indent.len as usize),
3650 };
3651 let point = Point::new(row.0, 0);
3652 indent_edits.push((point..point, text));
3653 }
3654 }
3655 editor.edit(indent_edits, cx);
3656 });
3657 }
3658
3659 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3660 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3661 original_indent_columns: Vec::new(),
3662 });
3663 self.insert_with_autoindent_mode(text, autoindent, cx);
3664 }
3665
3666 fn insert_with_autoindent_mode(
3667 &mut self,
3668 text: &str,
3669 autoindent_mode: Option<AutoindentMode>,
3670 cx: &mut ViewContext<Self>,
3671 ) {
3672 if self.read_only(cx) {
3673 return;
3674 }
3675
3676 let text: Arc<str> = text.into();
3677 self.transact(cx, |this, cx| {
3678 let old_selections = this.selections.all_adjusted(cx);
3679 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3680 let anchors = {
3681 let snapshot = buffer.read(cx);
3682 old_selections
3683 .iter()
3684 .map(|s| {
3685 let anchor = snapshot.anchor_after(s.head());
3686 s.map(|_| anchor)
3687 })
3688 .collect::<Vec<_>>()
3689 };
3690 buffer.edit(
3691 old_selections
3692 .iter()
3693 .map(|s| (s.start..s.end, text.clone())),
3694 autoindent_mode,
3695 cx,
3696 );
3697 anchors
3698 });
3699
3700 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3701 s.select_anchors(selection_anchors);
3702 })
3703 });
3704 }
3705
3706 fn trigger_completion_on_input(
3707 &mut self,
3708 text: &str,
3709 trigger_in_words: bool,
3710 cx: &mut ViewContext<Self>,
3711 ) {
3712 if self.is_completion_trigger(text, trigger_in_words, cx) {
3713 self.show_completions(
3714 &ShowCompletions {
3715 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3716 },
3717 cx,
3718 );
3719 } else {
3720 self.hide_context_menu(cx);
3721 }
3722 }
3723
3724 fn is_completion_trigger(
3725 &self,
3726 text: &str,
3727 trigger_in_words: bool,
3728 cx: &mut ViewContext<Self>,
3729 ) -> bool {
3730 let position = self.selections.newest_anchor().head();
3731 let multibuffer = self.buffer.read(cx);
3732 let Some(buffer) = position
3733 .buffer_id
3734 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3735 else {
3736 return false;
3737 };
3738
3739 if let Some(completion_provider) = &self.completion_provider {
3740 completion_provider.is_completion_trigger(
3741 &buffer,
3742 position.text_anchor,
3743 text,
3744 trigger_in_words,
3745 cx,
3746 )
3747 } else {
3748 false
3749 }
3750 }
3751
3752 /// If any empty selections is touching the start of its innermost containing autoclose
3753 /// region, expand it to select the brackets.
3754 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3755 let selections = self.selections.all::<usize>(cx);
3756 let buffer = self.buffer.read(cx).read(cx);
3757 let new_selections = self
3758 .selections_with_autoclose_regions(selections, &buffer)
3759 .map(|(mut selection, region)| {
3760 if !selection.is_empty() {
3761 return selection;
3762 }
3763
3764 if let Some(region) = region {
3765 let mut range = region.range.to_offset(&buffer);
3766 if selection.start == range.start && range.start >= region.pair.start.len() {
3767 range.start -= region.pair.start.len();
3768 if buffer.contains_str_at(range.start, ®ion.pair.start)
3769 && buffer.contains_str_at(range.end, ®ion.pair.end)
3770 {
3771 range.end += region.pair.end.len();
3772 selection.start = range.start;
3773 selection.end = range.end;
3774
3775 return selection;
3776 }
3777 }
3778 }
3779
3780 let always_treat_brackets_as_autoclosed = buffer
3781 .settings_at(selection.start, cx)
3782 .always_treat_brackets_as_autoclosed;
3783
3784 if !always_treat_brackets_as_autoclosed {
3785 return selection;
3786 }
3787
3788 if let Some(scope) = buffer.language_scope_at(selection.start) {
3789 for (pair, enabled) in scope.brackets() {
3790 if !enabled || !pair.close {
3791 continue;
3792 }
3793
3794 if buffer.contains_str_at(selection.start, &pair.end) {
3795 let pair_start_len = pair.start.len();
3796 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3797 {
3798 selection.start -= pair_start_len;
3799 selection.end += pair.end.len();
3800
3801 return selection;
3802 }
3803 }
3804 }
3805 }
3806
3807 selection
3808 })
3809 .collect();
3810
3811 drop(buffer);
3812 self.change_selections(None, cx, |selections| selections.select(new_selections));
3813 }
3814
3815 /// Iterate the given selections, and for each one, find the smallest surrounding
3816 /// autoclose region. This uses the ordering of the selections and the autoclose
3817 /// regions to avoid repeated comparisons.
3818 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3819 &'a self,
3820 selections: impl IntoIterator<Item = Selection<D>>,
3821 buffer: &'a MultiBufferSnapshot,
3822 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3823 let mut i = 0;
3824 let mut regions = self.autoclose_regions.as_slice();
3825 selections.into_iter().map(move |selection| {
3826 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3827
3828 let mut enclosing = None;
3829 while let Some(pair_state) = regions.get(i) {
3830 if pair_state.range.end.to_offset(buffer) < range.start {
3831 regions = ®ions[i + 1..];
3832 i = 0;
3833 } else if pair_state.range.start.to_offset(buffer) > range.end {
3834 break;
3835 } else {
3836 if pair_state.selection_id == selection.id {
3837 enclosing = Some(pair_state);
3838 }
3839 i += 1;
3840 }
3841 }
3842
3843 (selection.clone(), enclosing)
3844 })
3845 }
3846
3847 /// Remove any autoclose regions that no longer contain their selection.
3848 fn invalidate_autoclose_regions(
3849 &mut self,
3850 mut selections: &[Selection<Anchor>],
3851 buffer: &MultiBufferSnapshot,
3852 ) {
3853 self.autoclose_regions.retain(|state| {
3854 let mut i = 0;
3855 while let Some(selection) = selections.get(i) {
3856 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3857 selections = &selections[1..];
3858 continue;
3859 }
3860 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3861 break;
3862 }
3863 if selection.id == state.selection_id {
3864 return true;
3865 } else {
3866 i += 1;
3867 }
3868 }
3869 false
3870 });
3871 }
3872
3873 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3874 let offset = position.to_offset(buffer);
3875 let (word_range, kind) = buffer.surrounding_word(offset);
3876 if offset > word_range.start && kind == Some(CharKind::Word) {
3877 Some(
3878 buffer
3879 .text_for_range(word_range.start..offset)
3880 .collect::<String>(),
3881 )
3882 } else {
3883 None
3884 }
3885 }
3886
3887 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3888 self.refresh_inlay_hints(
3889 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3890 cx,
3891 );
3892 }
3893
3894 pub fn inlay_hints_enabled(&self) -> bool {
3895 self.inlay_hint_cache.enabled
3896 }
3897
3898 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3899 if self.project.is_none() || self.mode != EditorMode::Full {
3900 return;
3901 }
3902
3903 let reason_description = reason.description();
3904 let ignore_debounce = matches!(
3905 reason,
3906 InlayHintRefreshReason::SettingsChange(_)
3907 | InlayHintRefreshReason::Toggle(_)
3908 | InlayHintRefreshReason::ExcerptsRemoved(_)
3909 );
3910 let (invalidate_cache, required_languages) = match reason {
3911 InlayHintRefreshReason::Toggle(enabled) => {
3912 self.inlay_hint_cache.enabled = enabled;
3913 if enabled {
3914 (InvalidationStrategy::RefreshRequested, None)
3915 } else {
3916 self.inlay_hint_cache.clear();
3917 self.splice_inlays(
3918 self.visible_inlay_hints(cx)
3919 .iter()
3920 .map(|inlay| inlay.id)
3921 .collect(),
3922 Vec::new(),
3923 cx,
3924 );
3925 return;
3926 }
3927 }
3928 InlayHintRefreshReason::SettingsChange(new_settings) => {
3929 match self.inlay_hint_cache.update_settings(
3930 &self.buffer,
3931 new_settings,
3932 self.visible_inlay_hints(cx),
3933 cx,
3934 ) {
3935 ControlFlow::Break(Some(InlaySplice {
3936 to_remove,
3937 to_insert,
3938 })) => {
3939 self.splice_inlays(to_remove, to_insert, cx);
3940 return;
3941 }
3942 ControlFlow::Break(None) => return,
3943 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3944 }
3945 }
3946 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3947 if let Some(InlaySplice {
3948 to_remove,
3949 to_insert,
3950 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3951 {
3952 self.splice_inlays(to_remove, to_insert, cx);
3953 }
3954 return;
3955 }
3956 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3957 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3958 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3959 }
3960 InlayHintRefreshReason::RefreshRequested => {
3961 (InvalidationStrategy::RefreshRequested, None)
3962 }
3963 };
3964
3965 if let Some(InlaySplice {
3966 to_remove,
3967 to_insert,
3968 }) = self.inlay_hint_cache.spawn_hint_refresh(
3969 reason_description,
3970 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3971 invalidate_cache,
3972 ignore_debounce,
3973 cx,
3974 ) {
3975 self.splice_inlays(to_remove, to_insert, cx);
3976 }
3977 }
3978
3979 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
3980 self.display_map
3981 .read(cx)
3982 .current_inlays()
3983 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3984 .cloned()
3985 .collect()
3986 }
3987
3988 pub fn excerpts_for_inlay_hints_query(
3989 &self,
3990 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3991 cx: &mut ViewContext<Editor>,
3992 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3993 let Some(project) = self.project.as_ref() else {
3994 return HashMap::default();
3995 };
3996 let project = project.read(cx);
3997 let multi_buffer = self.buffer().read(cx);
3998 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3999 let multi_buffer_visible_start = self
4000 .scroll_manager
4001 .anchor()
4002 .anchor
4003 .to_point(&multi_buffer_snapshot);
4004 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4005 multi_buffer_visible_start
4006 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4007 Bias::Left,
4008 );
4009 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4010 multi_buffer
4011 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4012 .into_iter()
4013 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4014 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4015 let buffer = buffer_handle.read(cx);
4016 let buffer_file = project::File::from_dyn(buffer.file())?;
4017 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4018 let worktree_entry = buffer_worktree
4019 .read(cx)
4020 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4021 if worktree_entry.is_ignored {
4022 return None;
4023 }
4024
4025 let language = buffer.language()?;
4026 if let Some(restrict_to_languages) = restrict_to_languages {
4027 if !restrict_to_languages.contains(language) {
4028 return None;
4029 }
4030 }
4031 Some((
4032 excerpt_id,
4033 (
4034 buffer_handle,
4035 buffer.version().clone(),
4036 excerpt_visible_range,
4037 ),
4038 ))
4039 })
4040 .collect()
4041 }
4042
4043 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4044 TextLayoutDetails {
4045 text_system: cx.text_system().clone(),
4046 editor_style: self.style.clone().unwrap(),
4047 rem_size: cx.rem_size(),
4048 scroll_anchor: self.scroll_manager.anchor(),
4049 visible_rows: self.visible_line_count(),
4050 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4051 }
4052 }
4053
4054 fn splice_inlays(
4055 &self,
4056 to_remove: Vec<InlayId>,
4057 to_insert: Vec<Inlay>,
4058 cx: &mut ViewContext<Self>,
4059 ) {
4060 self.display_map.update(cx, |display_map, cx| {
4061 display_map.splice_inlays(to_remove, to_insert, cx);
4062 });
4063 cx.notify();
4064 }
4065
4066 fn trigger_on_type_formatting(
4067 &self,
4068 input: String,
4069 cx: &mut ViewContext<Self>,
4070 ) -> Option<Task<Result<()>>> {
4071 if input.len() != 1 {
4072 return None;
4073 }
4074
4075 let project = self.project.as_ref()?;
4076 let position = self.selections.newest_anchor().head();
4077 let (buffer, buffer_position) = self
4078 .buffer
4079 .read(cx)
4080 .text_anchor_for_position(position, cx)?;
4081
4082 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4083 // hence we do LSP request & edit on host side only — add formats to host's history.
4084 let push_to_lsp_host_history = true;
4085 // If this is not the host, append its history with new edits.
4086 let push_to_client_history = project.read(cx).is_via_collab();
4087
4088 let on_type_formatting = project.update(cx, |project, cx| {
4089 project.on_type_format(
4090 buffer.clone(),
4091 buffer_position,
4092 input,
4093 push_to_lsp_host_history,
4094 cx,
4095 )
4096 });
4097 Some(cx.spawn(|editor, mut cx| async move {
4098 if let Some(transaction) = on_type_formatting.await? {
4099 if push_to_client_history {
4100 buffer
4101 .update(&mut cx, |buffer, _| {
4102 buffer.push_transaction(transaction, Instant::now());
4103 })
4104 .ok();
4105 }
4106 editor.update(&mut cx, |editor, cx| {
4107 editor.refresh_document_highlights(cx);
4108 })?;
4109 }
4110 Ok(())
4111 }))
4112 }
4113
4114 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4115 if self.pending_rename.is_some() {
4116 return;
4117 }
4118
4119 let Some(provider) = self.completion_provider.as_ref() else {
4120 return;
4121 };
4122
4123 let position = self.selections.newest_anchor().head();
4124 let (buffer, buffer_position) =
4125 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4126 output
4127 } else {
4128 return;
4129 };
4130
4131 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4132 let is_followup_invoke = {
4133 let context_menu_state = self.context_menu.read();
4134 matches!(
4135 context_menu_state.deref(),
4136 Some(ContextMenu::Completions(_))
4137 )
4138 };
4139 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4140 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4141 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(&trigger) => {
4142 CompletionTriggerKind::TRIGGER_CHARACTER
4143 }
4144
4145 _ => CompletionTriggerKind::INVOKED,
4146 };
4147 let completion_context = CompletionContext {
4148 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4149 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4150 Some(String::from(trigger))
4151 } else {
4152 None
4153 }
4154 }),
4155 trigger_kind,
4156 };
4157 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4158 let sort_completions = provider.sort_completions();
4159
4160 let id = post_inc(&mut self.next_completion_id);
4161 let task = cx.spawn(|this, mut cx| {
4162 async move {
4163 this.update(&mut cx, |this, _| {
4164 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4165 })?;
4166 let completions = completions.await.log_err();
4167 let menu = if let Some(completions) = completions {
4168 let mut menu = CompletionsMenu {
4169 id,
4170 sort_completions,
4171 initial_position: position,
4172 match_candidates: completions
4173 .iter()
4174 .enumerate()
4175 .map(|(id, completion)| {
4176 StringMatchCandidate::new(
4177 id,
4178 completion.label.text[completion.label.filter_range.clone()]
4179 .into(),
4180 )
4181 })
4182 .collect(),
4183 buffer: buffer.clone(),
4184 completions: Arc::new(RwLock::new(completions.into())),
4185 matches: Vec::new().into(),
4186 selected_item: 0,
4187 scroll_handle: UniformListScrollHandle::new(),
4188 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4189 DebouncedDelay::new(),
4190 )),
4191 };
4192 menu.filter(query.as_deref(), cx.background_executor().clone())
4193 .await;
4194
4195 if menu.matches.is_empty() {
4196 None
4197 } else {
4198 this.update(&mut cx, |editor, cx| {
4199 let completions = menu.completions.clone();
4200 let matches = menu.matches.clone();
4201
4202 let delay_ms = EditorSettings::get_global(cx)
4203 .completion_documentation_secondary_query_debounce;
4204 let delay = Duration::from_millis(delay_ms);
4205 editor
4206 .completion_documentation_pre_resolve_debounce
4207 .fire_new(delay, cx, |editor, cx| {
4208 CompletionsMenu::pre_resolve_completion_documentation(
4209 buffer,
4210 completions,
4211 matches,
4212 editor,
4213 cx,
4214 )
4215 });
4216 })
4217 .ok();
4218 Some(menu)
4219 }
4220 } else {
4221 None
4222 };
4223
4224 this.update(&mut cx, |this, cx| {
4225 let mut context_menu = this.context_menu.write();
4226 match context_menu.as_ref() {
4227 None => {}
4228
4229 Some(ContextMenu::Completions(prev_menu)) => {
4230 if prev_menu.id > id {
4231 return;
4232 }
4233 }
4234
4235 _ => return,
4236 }
4237
4238 if this.focus_handle.is_focused(cx) && menu.is_some() {
4239 let menu = menu.unwrap();
4240 *context_menu = Some(ContextMenu::Completions(menu));
4241 drop(context_menu);
4242 this.discard_inline_completion(false, cx);
4243 cx.notify();
4244 } else if this.completion_tasks.len() <= 1 {
4245 // If there are no more completion tasks and the last menu was
4246 // empty, we should hide it. If it was already hidden, we should
4247 // also show the copilot completion when available.
4248 drop(context_menu);
4249 if this.hide_context_menu(cx).is_none() {
4250 this.update_visible_inline_completion(cx);
4251 }
4252 }
4253 })?;
4254
4255 Ok::<_, anyhow::Error>(())
4256 }
4257 .log_err()
4258 });
4259
4260 self.completion_tasks.push((id, task));
4261 }
4262
4263 pub fn confirm_completion(
4264 &mut self,
4265 action: &ConfirmCompletion,
4266 cx: &mut ViewContext<Self>,
4267 ) -> Option<Task<Result<()>>> {
4268 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4269 }
4270
4271 pub fn compose_completion(
4272 &mut self,
4273 action: &ComposeCompletion,
4274 cx: &mut ViewContext<Self>,
4275 ) -> Option<Task<Result<()>>> {
4276 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4277 }
4278
4279 fn do_completion(
4280 &mut self,
4281 item_ix: Option<usize>,
4282 intent: CompletionIntent,
4283 cx: &mut ViewContext<Editor>,
4284 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4285 use language::ToOffset as _;
4286
4287 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4288 menu
4289 } else {
4290 return None;
4291 };
4292
4293 let mat = completions_menu
4294 .matches
4295 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4296 let buffer_handle = completions_menu.buffer;
4297 let completions = completions_menu.completions.read();
4298 let completion = completions.get(mat.candidate_id)?;
4299 cx.stop_propagation();
4300
4301 let snippet;
4302 let text;
4303
4304 if completion.is_snippet() {
4305 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4306 text = snippet.as_ref().unwrap().text.clone();
4307 } else {
4308 snippet = None;
4309 text = completion.new_text.clone();
4310 };
4311 let selections = self.selections.all::<usize>(cx);
4312 let buffer = buffer_handle.read(cx);
4313 let old_range = completion.old_range.to_offset(buffer);
4314 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4315
4316 let newest_selection = self.selections.newest_anchor();
4317 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4318 return None;
4319 }
4320
4321 let lookbehind = newest_selection
4322 .start
4323 .text_anchor
4324 .to_offset(buffer)
4325 .saturating_sub(old_range.start);
4326 let lookahead = old_range
4327 .end
4328 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4329 let mut common_prefix_len = old_text
4330 .bytes()
4331 .zip(text.bytes())
4332 .take_while(|(a, b)| a == b)
4333 .count();
4334
4335 let snapshot = self.buffer.read(cx).snapshot(cx);
4336 let mut range_to_replace: Option<Range<isize>> = None;
4337 let mut ranges = Vec::new();
4338 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4339 for selection in &selections {
4340 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4341 let start = selection.start.saturating_sub(lookbehind);
4342 let end = selection.end + lookahead;
4343 if selection.id == newest_selection.id {
4344 range_to_replace = Some(
4345 ((start + common_prefix_len) as isize - selection.start as isize)
4346 ..(end as isize - selection.start as isize),
4347 );
4348 }
4349 ranges.push(start + common_prefix_len..end);
4350 } else {
4351 common_prefix_len = 0;
4352 ranges.clear();
4353 ranges.extend(selections.iter().map(|s| {
4354 if s.id == newest_selection.id {
4355 range_to_replace = Some(
4356 old_range.start.to_offset_utf16(&snapshot).0 as isize
4357 - selection.start as isize
4358 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4359 - selection.start as isize,
4360 );
4361 old_range.clone()
4362 } else {
4363 s.start..s.end
4364 }
4365 }));
4366 break;
4367 }
4368 if !self.linked_edit_ranges.is_empty() {
4369 let start_anchor = snapshot.anchor_before(selection.head());
4370 let end_anchor = snapshot.anchor_after(selection.tail());
4371 if let Some(ranges) = self
4372 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4373 {
4374 for (buffer, edits) in ranges {
4375 linked_edits.entry(buffer.clone()).or_default().extend(
4376 edits
4377 .into_iter()
4378 .map(|range| (range, text[common_prefix_len..].to_owned())),
4379 );
4380 }
4381 }
4382 }
4383 }
4384 let text = &text[common_prefix_len..];
4385
4386 cx.emit(EditorEvent::InputHandled {
4387 utf16_range_to_replace: range_to_replace,
4388 text: text.into(),
4389 });
4390
4391 self.transact(cx, |this, cx| {
4392 if let Some(mut snippet) = snippet {
4393 snippet.text = text.to_string();
4394 for tabstop in snippet.tabstops.iter_mut().flatten() {
4395 tabstop.start -= common_prefix_len as isize;
4396 tabstop.end -= common_prefix_len as isize;
4397 }
4398
4399 this.insert_snippet(&ranges, snippet, cx).log_err();
4400 } else {
4401 this.buffer.update(cx, |buffer, cx| {
4402 buffer.edit(
4403 ranges.iter().map(|range| (range.clone(), text)),
4404 this.autoindent_mode.clone(),
4405 cx,
4406 );
4407 });
4408 }
4409 for (buffer, edits) in linked_edits {
4410 buffer.update(cx, |buffer, cx| {
4411 let snapshot = buffer.snapshot();
4412 let edits = edits
4413 .into_iter()
4414 .map(|(range, text)| {
4415 use text::ToPoint as TP;
4416 let end_point = TP::to_point(&range.end, &snapshot);
4417 let start_point = TP::to_point(&range.start, &snapshot);
4418 (start_point..end_point, text)
4419 })
4420 .sorted_by_key(|(range, _)| range.start)
4421 .collect::<Vec<_>>();
4422 buffer.edit(edits, None, cx);
4423 })
4424 }
4425
4426 this.refresh_inline_completion(true, false, cx);
4427 });
4428
4429 let show_new_completions_on_confirm = completion
4430 .confirm
4431 .as_ref()
4432 .map_or(false, |confirm| confirm(intent, cx));
4433 if show_new_completions_on_confirm {
4434 self.show_completions(&ShowCompletions { trigger: None }, cx);
4435 }
4436
4437 let provider = self.completion_provider.as_ref()?;
4438 let apply_edits = provider.apply_additional_edits_for_completion(
4439 buffer_handle,
4440 completion.clone(),
4441 true,
4442 cx,
4443 );
4444
4445 let editor_settings = EditorSettings::get_global(cx);
4446 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4447 // After the code completion is finished, users often want to know what signatures are needed.
4448 // so we should automatically call signature_help
4449 self.show_signature_help(&ShowSignatureHelp, cx);
4450 }
4451
4452 Some(cx.foreground_executor().spawn(async move {
4453 apply_edits.await?;
4454 Ok(())
4455 }))
4456 }
4457
4458 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4459 let mut context_menu = self.context_menu.write();
4460 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4461 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4462 // Toggle if we're selecting the same one
4463 *context_menu = None;
4464 cx.notify();
4465 return;
4466 } else {
4467 // Otherwise, clear it and start a new one
4468 *context_menu = None;
4469 cx.notify();
4470 }
4471 }
4472 drop(context_menu);
4473 let snapshot = self.snapshot(cx);
4474 let deployed_from_indicator = action.deployed_from_indicator;
4475 let mut task = self.code_actions_task.take();
4476 let action = action.clone();
4477 cx.spawn(|editor, mut cx| async move {
4478 while let Some(prev_task) = task {
4479 prev_task.await;
4480 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4481 }
4482
4483 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4484 if editor.focus_handle.is_focused(cx) {
4485 let multibuffer_point = action
4486 .deployed_from_indicator
4487 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4488 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4489 let (buffer, buffer_row) = snapshot
4490 .buffer_snapshot
4491 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4492 .and_then(|(buffer_snapshot, range)| {
4493 editor
4494 .buffer
4495 .read(cx)
4496 .buffer(buffer_snapshot.remote_id())
4497 .map(|buffer| (buffer, range.start.row))
4498 })?;
4499 let (_, code_actions) = editor
4500 .available_code_actions
4501 .clone()
4502 .and_then(|(location, code_actions)| {
4503 let snapshot = location.buffer.read(cx).snapshot();
4504 let point_range = location.range.to_point(&snapshot);
4505 let point_range = point_range.start.row..=point_range.end.row;
4506 if point_range.contains(&buffer_row) {
4507 Some((location, code_actions))
4508 } else {
4509 None
4510 }
4511 })
4512 .unzip();
4513 let buffer_id = buffer.read(cx).remote_id();
4514 let tasks = editor
4515 .tasks
4516 .get(&(buffer_id, buffer_row))
4517 .map(|t| Arc::new(t.to_owned()));
4518 if tasks.is_none() && code_actions.is_none() {
4519 return None;
4520 }
4521
4522 editor.completion_tasks.clear();
4523 editor.discard_inline_completion(false, cx);
4524 let task_context =
4525 tasks
4526 .as_ref()
4527 .zip(editor.project.clone())
4528 .map(|(tasks, project)| {
4529 let position = Point::new(buffer_row, tasks.column);
4530 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4531 let location = Location {
4532 buffer: buffer.clone(),
4533 range: range_start..range_start,
4534 };
4535 // Fill in the environmental variables from the tree-sitter captures
4536 let mut captured_task_variables = TaskVariables::default();
4537 for (capture_name, value) in tasks.extra_variables.clone() {
4538 captured_task_variables.insert(
4539 task::VariableName::Custom(capture_name.into()),
4540 value.clone(),
4541 );
4542 }
4543 project.update(cx, |project, cx| {
4544 project.task_context_for_location(
4545 captured_task_variables,
4546 location,
4547 cx,
4548 )
4549 })
4550 });
4551
4552 Some(cx.spawn(|editor, mut cx| async move {
4553 let task_context = match task_context {
4554 Some(task_context) => task_context.await,
4555 None => None,
4556 };
4557 let resolved_tasks =
4558 tasks.zip(task_context).map(|(tasks, task_context)| {
4559 Arc::new(ResolvedTasks {
4560 templates: tasks
4561 .templates
4562 .iter()
4563 .filter_map(|(kind, template)| {
4564 template
4565 .resolve_task(&kind.to_id_base(), &task_context)
4566 .map(|task| (kind.clone(), task))
4567 })
4568 .collect(),
4569 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4570 multibuffer_point.row,
4571 tasks.column,
4572 )),
4573 })
4574 });
4575 let spawn_straight_away = resolved_tasks
4576 .as_ref()
4577 .map_or(false, |tasks| tasks.templates.len() == 1)
4578 && code_actions
4579 .as_ref()
4580 .map_or(true, |actions| actions.is_empty());
4581 if let Some(task) = editor
4582 .update(&mut cx, |editor, cx| {
4583 *editor.context_menu.write() =
4584 Some(ContextMenu::CodeActions(CodeActionsMenu {
4585 buffer,
4586 actions: CodeActionContents {
4587 tasks: resolved_tasks,
4588 actions: code_actions,
4589 },
4590 selected_item: Default::default(),
4591 scroll_handle: UniformListScrollHandle::default(),
4592 deployed_from_indicator,
4593 }));
4594 if spawn_straight_away {
4595 if let Some(task) = editor.confirm_code_action(
4596 &ConfirmCodeAction { item_ix: Some(0) },
4597 cx,
4598 ) {
4599 cx.notify();
4600 return task;
4601 }
4602 }
4603 cx.notify();
4604 Task::ready(Ok(()))
4605 })
4606 .ok()
4607 {
4608 task.await
4609 } else {
4610 Ok(())
4611 }
4612 }))
4613 } else {
4614 Some(Task::ready(Ok(())))
4615 }
4616 })?;
4617 if let Some(task) = spawned_test_task {
4618 task.await?;
4619 }
4620
4621 Ok::<_, anyhow::Error>(())
4622 })
4623 .detach_and_log_err(cx);
4624 }
4625
4626 pub fn confirm_code_action(
4627 &mut self,
4628 action: &ConfirmCodeAction,
4629 cx: &mut ViewContext<Self>,
4630 ) -> Option<Task<Result<()>>> {
4631 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4632 menu
4633 } else {
4634 return None;
4635 };
4636 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4637 let action = actions_menu.actions.get(action_ix)?;
4638 let title = action.label();
4639 let buffer = actions_menu.buffer;
4640 let workspace = self.workspace()?;
4641
4642 match action {
4643 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4644 workspace.update(cx, |workspace, cx| {
4645 workspace::tasks::schedule_resolved_task(
4646 workspace,
4647 task_source_kind,
4648 resolved_task,
4649 false,
4650 cx,
4651 );
4652
4653 Some(Task::ready(Ok(())))
4654 })
4655 }
4656 CodeActionsItem::CodeAction(action) => {
4657 let apply_code_actions = workspace
4658 .read(cx)
4659 .project()
4660 .clone()
4661 .update(cx, |project, cx| {
4662 project.apply_code_action(buffer, action, true, cx)
4663 });
4664 let workspace = workspace.downgrade();
4665 Some(cx.spawn(|editor, cx| async move {
4666 let project_transaction = apply_code_actions.await?;
4667 Self::open_project_transaction(
4668 &editor,
4669 workspace,
4670 project_transaction,
4671 title,
4672 cx,
4673 )
4674 .await
4675 }))
4676 }
4677 }
4678 }
4679
4680 pub async fn open_project_transaction(
4681 this: &WeakView<Editor>,
4682 workspace: WeakView<Workspace>,
4683 transaction: ProjectTransaction,
4684 title: String,
4685 mut cx: AsyncWindowContext,
4686 ) -> Result<()> {
4687 let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
4688
4689 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4690 cx.update(|cx| {
4691 entries.sort_unstable_by_key(|(buffer, _)| {
4692 buffer.read(cx).file().map(|f| f.path().clone())
4693 });
4694 })?;
4695
4696 // If the project transaction's edits are all contained within this editor, then
4697 // avoid opening a new editor to display them.
4698
4699 if let Some((buffer, transaction)) = entries.first() {
4700 if entries.len() == 1 {
4701 let excerpt = this.update(&mut cx, |editor, cx| {
4702 editor
4703 .buffer()
4704 .read(cx)
4705 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4706 })?;
4707 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4708 if excerpted_buffer == *buffer {
4709 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4710 let excerpt_range = excerpt_range.to_offset(buffer);
4711 buffer
4712 .edited_ranges_for_transaction::<usize>(transaction)
4713 .all(|range| {
4714 excerpt_range.start <= range.start
4715 && excerpt_range.end >= range.end
4716 })
4717 })?;
4718
4719 if all_edits_within_excerpt {
4720 return Ok(());
4721 }
4722 }
4723 }
4724 }
4725 } else {
4726 return Ok(());
4727 }
4728
4729 let mut ranges_to_highlight = Vec::new();
4730 let excerpt_buffer = cx.new_model(|cx| {
4731 let mut multibuffer =
4732 MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
4733 for (buffer_handle, transaction) in &entries {
4734 let buffer = buffer_handle.read(cx);
4735 ranges_to_highlight.extend(
4736 multibuffer.push_excerpts_with_context_lines(
4737 buffer_handle.clone(),
4738 buffer
4739 .edited_ranges_for_transaction::<usize>(transaction)
4740 .collect(),
4741 DEFAULT_MULTIBUFFER_CONTEXT,
4742 cx,
4743 ),
4744 );
4745 }
4746 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4747 multibuffer
4748 })?;
4749
4750 workspace.update(&mut cx, |workspace, cx| {
4751 let project = workspace.project().clone();
4752 let editor =
4753 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4754 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4755 editor.update(cx, |editor, cx| {
4756 editor.highlight_background::<Self>(
4757 &ranges_to_highlight,
4758 |theme| theme.editor_highlighted_line_background,
4759 cx,
4760 );
4761 });
4762 })?;
4763
4764 Ok(())
4765 }
4766
4767 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4768 let project = self.project.clone()?;
4769 let buffer = self.buffer.read(cx);
4770 let newest_selection = self.selections.newest_anchor().clone();
4771 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4772 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4773 if start_buffer != end_buffer {
4774 return None;
4775 }
4776
4777 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4778 cx.background_executor()
4779 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4780 .await;
4781
4782 let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
4783 project.code_actions(&start_buffer, start..end, cx)
4784 }) {
4785 code_actions.await
4786 } else {
4787 Vec::new()
4788 };
4789
4790 this.update(&mut cx, |this, cx| {
4791 this.available_code_actions = if actions.is_empty() {
4792 None
4793 } else {
4794 Some((
4795 Location {
4796 buffer: start_buffer,
4797 range: start..end,
4798 },
4799 actions.into(),
4800 ))
4801 };
4802 cx.notify();
4803 })
4804 .log_err();
4805 }));
4806 None
4807 }
4808
4809 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4810 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4811 self.show_git_blame_inline = false;
4812
4813 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4814 cx.background_executor().timer(delay).await;
4815
4816 this.update(&mut cx, |this, cx| {
4817 this.show_git_blame_inline = true;
4818 cx.notify();
4819 })
4820 .log_err();
4821 }));
4822 }
4823 }
4824
4825 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4826 if self.pending_rename.is_some() {
4827 return None;
4828 }
4829
4830 let project = self.project.clone()?;
4831 let buffer = self.buffer.read(cx);
4832 let newest_selection = self.selections.newest_anchor().clone();
4833 let cursor_position = newest_selection.head();
4834 let (cursor_buffer, cursor_buffer_position) =
4835 buffer.text_anchor_for_position(cursor_position, cx)?;
4836 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4837 if cursor_buffer != tail_buffer {
4838 return None;
4839 }
4840
4841 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4842 cx.background_executor()
4843 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
4844 .await;
4845
4846 let highlights = if let Some(highlights) = project
4847 .update(&mut cx, |project, cx| {
4848 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4849 })
4850 .log_err()
4851 {
4852 highlights.await.log_err()
4853 } else {
4854 None
4855 };
4856
4857 if let Some(highlights) = highlights {
4858 this.update(&mut cx, |this, cx| {
4859 if this.pending_rename.is_some() {
4860 return;
4861 }
4862
4863 let buffer_id = cursor_position.buffer_id;
4864 let buffer = this.buffer.read(cx);
4865 if !buffer
4866 .text_anchor_for_position(cursor_position, cx)
4867 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4868 {
4869 return;
4870 }
4871
4872 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4873 let mut write_ranges = Vec::new();
4874 let mut read_ranges = Vec::new();
4875 for highlight in highlights {
4876 for (excerpt_id, excerpt_range) in
4877 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4878 {
4879 let start = highlight
4880 .range
4881 .start
4882 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4883 let end = highlight
4884 .range
4885 .end
4886 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4887 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4888 continue;
4889 }
4890
4891 let range = Anchor {
4892 buffer_id,
4893 excerpt_id,
4894 text_anchor: start,
4895 }..Anchor {
4896 buffer_id,
4897 excerpt_id,
4898 text_anchor: end,
4899 };
4900 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4901 write_ranges.push(range);
4902 } else {
4903 read_ranges.push(range);
4904 }
4905 }
4906 }
4907
4908 this.highlight_background::<DocumentHighlightRead>(
4909 &read_ranges,
4910 |theme| theme.editor_document_highlight_read_background,
4911 cx,
4912 );
4913 this.highlight_background::<DocumentHighlightWrite>(
4914 &write_ranges,
4915 |theme| theme.editor_document_highlight_write_background,
4916 cx,
4917 );
4918 cx.notify();
4919 })
4920 .log_err();
4921 }
4922 }));
4923 None
4924 }
4925
4926 pub fn refresh_inline_completion(
4927 &mut self,
4928 debounce: bool,
4929 user_requested: bool,
4930 cx: &mut ViewContext<Self>,
4931 ) -> Option<()> {
4932 let provider = self.inline_completion_provider()?;
4933 let cursor = self.selections.newest_anchor().head();
4934 let (buffer, cursor_buffer_position) =
4935 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4936 if !user_requested
4937 && (!self.show_inline_completions
4938 || !provider.is_enabled(&buffer, cursor_buffer_position, cx))
4939 {
4940 self.discard_inline_completion(false, cx);
4941 return None;
4942 }
4943
4944 self.update_visible_inline_completion(cx);
4945 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4946 Some(())
4947 }
4948
4949 fn cycle_inline_completion(
4950 &mut self,
4951 direction: Direction,
4952 cx: &mut ViewContext<Self>,
4953 ) -> Option<()> {
4954 let provider = self.inline_completion_provider()?;
4955 let cursor = self.selections.newest_anchor().head();
4956 let (buffer, cursor_buffer_position) =
4957 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4958 if !self.show_inline_completions
4959 || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
4960 {
4961 return None;
4962 }
4963
4964 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4965 self.update_visible_inline_completion(cx);
4966
4967 Some(())
4968 }
4969
4970 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4971 if !self.has_active_inline_completion(cx) {
4972 self.refresh_inline_completion(false, true, cx);
4973 return;
4974 }
4975
4976 self.update_visible_inline_completion(cx);
4977 }
4978
4979 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4980 self.show_cursor_names(cx);
4981 }
4982
4983 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4984 self.show_cursor_names = true;
4985 cx.notify();
4986 cx.spawn(|this, mut cx| async move {
4987 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4988 this.update(&mut cx, |this, cx| {
4989 this.show_cursor_names = false;
4990 cx.notify()
4991 })
4992 .ok()
4993 })
4994 .detach();
4995 }
4996
4997 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4998 if self.has_active_inline_completion(cx) {
4999 self.cycle_inline_completion(Direction::Next, cx);
5000 } else {
5001 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5002 if is_copilot_disabled {
5003 cx.propagate();
5004 }
5005 }
5006 }
5007
5008 pub fn previous_inline_completion(
5009 &mut self,
5010 _: &PreviousInlineCompletion,
5011 cx: &mut ViewContext<Self>,
5012 ) {
5013 if self.has_active_inline_completion(cx) {
5014 self.cycle_inline_completion(Direction::Prev, cx);
5015 } else {
5016 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5017 if is_copilot_disabled {
5018 cx.propagate();
5019 }
5020 }
5021 }
5022
5023 pub fn accept_inline_completion(
5024 &mut self,
5025 _: &AcceptInlineCompletion,
5026 cx: &mut ViewContext<Self>,
5027 ) {
5028 let Some((completion, delete_range)) = self.take_active_inline_completion(cx) else {
5029 return;
5030 };
5031 if let Some(provider) = self.inline_completion_provider() {
5032 provider.accept(cx);
5033 }
5034
5035 cx.emit(EditorEvent::InputHandled {
5036 utf16_range_to_replace: None,
5037 text: completion.text.to_string().into(),
5038 });
5039
5040 if let Some(range) = delete_range {
5041 self.change_selections(None, cx, |s| s.select_ranges([range]))
5042 }
5043 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5044 self.refresh_inline_completion(true, true, cx);
5045 cx.notify();
5046 }
5047
5048 pub fn accept_partial_inline_completion(
5049 &mut self,
5050 _: &AcceptPartialInlineCompletion,
5051 cx: &mut ViewContext<Self>,
5052 ) {
5053 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5054 if let Some((completion, delete_range)) = self.take_active_inline_completion(cx) {
5055 let mut partial_completion = completion
5056 .text
5057 .chars()
5058 .by_ref()
5059 .take_while(|c| c.is_alphabetic())
5060 .collect::<String>();
5061 if partial_completion.is_empty() {
5062 partial_completion = completion
5063 .text
5064 .chars()
5065 .by_ref()
5066 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5067 .collect::<String>();
5068 }
5069
5070 cx.emit(EditorEvent::InputHandled {
5071 utf16_range_to_replace: None,
5072 text: partial_completion.clone().into(),
5073 });
5074
5075 if let Some(range) = delete_range {
5076 self.change_selections(None, cx, |s| s.select_ranges([range]))
5077 }
5078 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5079
5080 self.refresh_inline_completion(true, true, cx);
5081 cx.notify();
5082 }
5083 }
5084 }
5085
5086 fn discard_inline_completion(
5087 &mut self,
5088 should_report_inline_completion_event: bool,
5089 cx: &mut ViewContext<Self>,
5090 ) -> bool {
5091 if let Some(provider) = self.inline_completion_provider() {
5092 provider.discard(should_report_inline_completion_event, cx);
5093 }
5094
5095 self.take_active_inline_completion(cx).is_some()
5096 }
5097
5098 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5099 if let Some(completion) = self.active_inline_completion.as_ref() {
5100 let buffer = self.buffer.read(cx).read(cx);
5101 completion.0.position.is_valid(&buffer)
5102 } else {
5103 false
5104 }
5105 }
5106
5107 fn take_active_inline_completion(
5108 &mut self,
5109 cx: &mut ViewContext<Self>,
5110 ) -> Option<(Inlay, Option<Range<Anchor>>)> {
5111 let completion = self.active_inline_completion.take()?;
5112 self.display_map.update(cx, |map, cx| {
5113 map.splice_inlays(vec![completion.0.id], Default::default(), cx);
5114 });
5115 let buffer = self.buffer.read(cx).read(cx);
5116
5117 if completion.0.position.is_valid(&buffer) {
5118 Some(completion)
5119 } else {
5120 None
5121 }
5122 }
5123
5124 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5125 let selection = self.selections.newest_anchor();
5126 let cursor = selection.head();
5127
5128 let excerpt_id = cursor.excerpt_id;
5129
5130 if self.context_menu.read().is_none()
5131 && self.completion_tasks.is_empty()
5132 && selection.start == selection.end
5133 {
5134 if let Some(provider) = self.inline_completion_provider() {
5135 if let Some((buffer, cursor_buffer_position)) =
5136 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5137 {
5138 if let Some((text, text_anchor_range)) =
5139 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5140 {
5141 let text = Rope::from(text);
5142 let mut to_remove = Vec::new();
5143 if let Some(completion) = self.active_inline_completion.take() {
5144 to_remove.push(completion.0.id);
5145 }
5146
5147 let completion_inlay =
5148 Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
5149
5150 let multibuffer_anchor_range = text_anchor_range.and_then(|range| {
5151 let snapshot = self.buffer.read(cx).snapshot(cx);
5152 Some(
5153 snapshot.anchor_in_excerpt(excerpt_id, range.start)?
5154 ..snapshot.anchor_in_excerpt(excerpt_id, range.end)?,
5155 )
5156 });
5157 self.active_inline_completion =
5158 Some((completion_inlay.clone(), multibuffer_anchor_range));
5159
5160 self.display_map.update(cx, move |map, cx| {
5161 map.splice_inlays(to_remove, vec![completion_inlay], cx)
5162 });
5163 cx.notify();
5164 return;
5165 }
5166 }
5167 }
5168 }
5169
5170 self.discard_inline_completion(false, cx);
5171 }
5172
5173 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5174 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5175 }
5176
5177 fn render_code_actions_indicator(
5178 &self,
5179 _style: &EditorStyle,
5180 row: DisplayRow,
5181 is_active: bool,
5182 cx: &mut ViewContext<Self>,
5183 ) -> Option<IconButton> {
5184 if self.available_code_actions.is_some() {
5185 Some(
5186 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5187 .shape(ui::IconButtonShape::Square)
5188 .icon_size(IconSize::XSmall)
5189 .icon_color(Color::Muted)
5190 .selected(is_active)
5191 .on_click(cx.listener(move |editor, _e, cx| {
5192 editor.focus(cx);
5193 editor.toggle_code_actions(
5194 &ToggleCodeActions {
5195 deployed_from_indicator: Some(row),
5196 },
5197 cx,
5198 );
5199 })),
5200 )
5201 } else {
5202 None
5203 }
5204 }
5205
5206 fn clear_tasks(&mut self) {
5207 self.tasks.clear()
5208 }
5209
5210 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5211 if let Some(_) = self.tasks.insert(key, value) {
5212 // This case should hopefully be rare, but just in case...
5213 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5214 }
5215 }
5216
5217 fn render_run_indicator(
5218 &self,
5219 _style: &EditorStyle,
5220 is_active: bool,
5221 row: DisplayRow,
5222 cx: &mut ViewContext<Self>,
5223 ) -> IconButton {
5224 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5225 .shape(ui::IconButtonShape::Square)
5226 .icon_size(IconSize::XSmall)
5227 .icon_color(Color::Muted)
5228 .selected(is_active)
5229 .on_click(cx.listener(move |editor, _e, cx| {
5230 editor.focus(cx);
5231 editor.toggle_code_actions(
5232 &ToggleCodeActions {
5233 deployed_from_indicator: Some(row),
5234 },
5235 cx,
5236 );
5237 }))
5238 }
5239
5240 fn close_hunk_diff_button(
5241 &self,
5242 hunk: HoveredHunk,
5243 row: DisplayRow,
5244 cx: &mut ViewContext<Self>,
5245 ) -> IconButton {
5246 IconButton::new(
5247 ("close_hunk_diff_indicator", row.0 as usize),
5248 ui::IconName::Close,
5249 )
5250 .shape(ui::IconButtonShape::Square)
5251 .icon_size(IconSize::XSmall)
5252 .icon_color(Color::Muted)
5253 .tooltip(|cx| Tooltip::for_action("Close hunk diff", &ToggleHunkDiff, cx))
5254 .on_click(cx.listener(move |editor, _e, cx| editor.toggle_hovered_hunk(&hunk, cx)))
5255 }
5256
5257 pub fn context_menu_visible(&self) -> bool {
5258 self.context_menu
5259 .read()
5260 .as_ref()
5261 .map_or(false, |menu| menu.visible())
5262 }
5263
5264 fn render_context_menu(
5265 &self,
5266 cursor_position: DisplayPoint,
5267 style: &EditorStyle,
5268 max_height: Pixels,
5269 cx: &mut ViewContext<Editor>,
5270 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5271 self.context_menu.read().as_ref().map(|menu| {
5272 menu.render(
5273 cursor_position,
5274 style,
5275 max_height,
5276 self.workspace.as_ref().map(|(w, _)| w.clone()),
5277 cx,
5278 )
5279 })
5280 }
5281
5282 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5283 cx.notify();
5284 self.completion_tasks.clear();
5285 let context_menu = self.context_menu.write().take();
5286 if context_menu.is_some() {
5287 self.update_visible_inline_completion(cx);
5288 }
5289 context_menu
5290 }
5291
5292 pub fn insert_snippet(
5293 &mut self,
5294 insertion_ranges: &[Range<usize>],
5295 snippet: Snippet,
5296 cx: &mut ViewContext<Self>,
5297 ) -> Result<()> {
5298 struct Tabstop<T> {
5299 is_end_tabstop: bool,
5300 ranges: Vec<Range<T>>,
5301 }
5302
5303 let tabstops = self.buffer.update(cx, |buffer, cx| {
5304 let snippet_text: Arc<str> = snippet.text.clone().into();
5305 buffer.edit(
5306 insertion_ranges
5307 .iter()
5308 .cloned()
5309 .map(|range| (range, snippet_text.clone())),
5310 Some(AutoindentMode::EachLine),
5311 cx,
5312 );
5313
5314 let snapshot = &*buffer.read(cx);
5315 let snippet = &snippet;
5316 snippet
5317 .tabstops
5318 .iter()
5319 .map(|tabstop| {
5320 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5321 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5322 });
5323 let mut tabstop_ranges = tabstop
5324 .iter()
5325 .flat_map(|tabstop_range| {
5326 let mut delta = 0_isize;
5327 insertion_ranges.iter().map(move |insertion_range| {
5328 let insertion_start = insertion_range.start as isize + delta;
5329 delta +=
5330 snippet.text.len() as isize - insertion_range.len() as isize;
5331
5332 let start = ((insertion_start + tabstop_range.start) as usize)
5333 .min(snapshot.len());
5334 let end = ((insertion_start + tabstop_range.end) as usize)
5335 .min(snapshot.len());
5336 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5337 })
5338 })
5339 .collect::<Vec<_>>();
5340 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5341
5342 Tabstop {
5343 is_end_tabstop,
5344 ranges: tabstop_ranges,
5345 }
5346 })
5347 .collect::<Vec<_>>()
5348 });
5349 if let Some(tabstop) = tabstops.first() {
5350 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5351 s.select_ranges(tabstop.ranges.iter().cloned());
5352 });
5353
5354 // If we're already at the last tabstop and it's at the end of the snippet,
5355 // we're done, we don't need to keep the state around.
5356 if !tabstop.is_end_tabstop {
5357 let ranges = tabstops
5358 .into_iter()
5359 .map(|tabstop| tabstop.ranges)
5360 .collect::<Vec<_>>();
5361 self.snippet_stack.push(SnippetState {
5362 active_index: 0,
5363 ranges,
5364 });
5365 }
5366
5367 // Check whether the just-entered snippet ends with an auto-closable bracket.
5368 if self.autoclose_regions.is_empty() {
5369 let snapshot = self.buffer.read(cx).snapshot(cx);
5370 for selection in &mut self.selections.all::<Point>(cx) {
5371 let selection_head = selection.head();
5372 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5373 continue;
5374 };
5375
5376 let mut bracket_pair = None;
5377 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5378 let prev_chars = snapshot
5379 .reversed_chars_at(selection_head)
5380 .collect::<String>();
5381 for (pair, enabled) in scope.brackets() {
5382 if enabled
5383 && pair.close
5384 && prev_chars.starts_with(pair.start.as_str())
5385 && next_chars.starts_with(pair.end.as_str())
5386 {
5387 bracket_pair = Some(pair.clone());
5388 break;
5389 }
5390 }
5391 if let Some(pair) = bracket_pair {
5392 let start = snapshot.anchor_after(selection_head);
5393 let end = snapshot.anchor_after(selection_head);
5394 self.autoclose_regions.push(AutocloseRegion {
5395 selection_id: selection.id,
5396 range: start..end,
5397 pair,
5398 });
5399 }
5400 }
5401 }
5402 }
5403 Ok(())
5404 }
5405
5406 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5407 self.move_to_snippet_tabstop(Bias::Right, cx)
5408 }
5409
5410 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5411 self.move_to_snippet_tabstop(Bias::Left, cx)
5412 }
5413
5414 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5415 if let Some(mut snippet) = self.snippet_stack.pop() {
5416 match bias {
5417 Bias::Left => {
5418 if snippet.active_index > 0 {
5419 snippet.active_index -= 1;
5420 } else {
5421 self.snippet_stack.push(snippet);
5422 return false;
5423 }
5424 }
5425 Bias::Right => {
5426 if snippet.active_index + 1 < snippet.ranges.len() {
5427 snippet.active_index += 1;
5428 } else {
5429 self.snippet_stack.push(snippet);
5430 return false;
5431 }
5432 }
5433 }
5434 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5435 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5436 s.select_anchor_ranges(current_ranges.iter().cloned())
5437 });
5438 // If snippet state is not at the last tabstop, push it back on the stack
5439 if snippet.active_index + 1 < snippet.ranges.len() {
5440 self.snippet_stack.push(snippet);
5441 }
5442 return true;
5443 }
5444 }
5445
5446 false
5447 }
5448
5449 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5450 self.transact(cx, |this, cx| {
5451 this.select_all(&SelectAll, cx);
5452 this.insert("", cx);
5453 });
5454 }
5455
5456 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5457 self.transact(cx, |this, cx| {
5458 this.select_autoclose_pair(cx);
5459 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5460 if !this.linked_edit_ranges.is_empty() {
5461 let selections = this.selections.all::<MultiBufferPoint>(cx);
5462 let snapshot = this.buffer.read(cx).snapshot(cx);
5463
5464 for selection in selections.iter() {
5465 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5466 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5467 if selection_start.buffer_id != selection_end.buffer_id {
5468 continue;
5469 }
5470 if let Some(ranges) =
5471 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5472 {
5473 for (buffer, entries) in ranges {
5474 linked_ranges.entry(buffer).or_default().extend(entries);
5475 }
5476 }
5477 }
5478 }
5479
5480 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5481 if !this.selections.line_mode {
5482 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5483 for selection in &mut selections {
5484 if selection.is_empty() {
5485 let old_head = selection.head();
5486 let mut new_head =
5487 movement::left(&display_map, old_head.to_display_point(&display_map))
5488 .to_point(&display_map);
5489 if let Some((buffer, line_buffer_range)) = display_map
5490 .buffer_snapshot
5491 .buffer_line_for_row(MultiBufferRow(old_head.row))
5492 {
5493 let indent_size =
5494 buffer.indent_size_for_line(line_buffer_range.start.row);
5495 let indent_len = match indent_size.kind {
5496 IndentKind::Space => {
5497 buffer.settings_at(line_buffer_range.start, cx).tab_size
5498 }
5499 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5500 };
5501 if old_head.column <= indent_size.len && old_head.column > 0 {
5502 let indent_len = indent_len.get();
5503 new_head = cmp::min(
5504 new_head,
5505 MultiBufferPoint::new(
5506 old_head.row,
5507 ((old_head.column - 1) / indent_len) * indent_len,
5508 ),
5509 );
5510 }
5511 }
5512
5513 selection.set_head(new_head, SelectionGoal::None);
5514 }
5515 }
5516 }
5517
5518 this.signature_help_state.set_backspace_pressed(true);
5519 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5520 this.insert("", cx);
5521 let empty_str: Arc<str> = Arc::from("");
5522 for (buffer, edits) in linked_ranges {
5523 let snapshot = buffer.read(cx).snapshot();
5524 use text::ToPoint as TP;
5525
5526 let edits = edits
5527 .into_iter()
5528 .map(|range| {
5529 let end_point = TP::to_point(&range.end, &snapshot);
5530 let mut start_point = TP::to_point(&range.start, &snapshot);
5531
5532 if end_point == start_point {
5533 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5534 .saturating_sub(1);
5535 start_point = TP::to_point(&offset, &snapshot);
5536 };
5537
5538 (start_point..end_point, empty_str.clone())
5539 })
5540 .sorted_by_key(|(range, _)| range.start)
5541 .collect::<Vec<_>>();
5542 buffer.update(cx, |this, cx| {
5543 this.edit(edits, None, cx);
5544 })
5545 }
5546 this.refresh_inline_completion(true, false, cx);
5547 linked_editing_ranges::refresh_linked_ranges(this, cx);
5548 });
5549 }
5550
5551 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5552 self.transact(cx, |this, cx| {
5553 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5554 let line_mode = s.line_mode;
5555 s.move_with(|map, selection| {
5556 if selection.is_empty() && !line_mode {
5557 let cursor = movement::right(map, selection.head());
5558 selection.end = cursor;
5559 selection.reversed = true;
5560 selection.goal = SelectionGoal::None;
5561 }
5562 })
5563 });
5564 this.insert("", cx);
5565 this.refresh_inline_completion(true, false, cx);
5566 });
5567 }
5568
5569 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5570 if self.move_to_prev_snippet_tabstop(cx) {
5571 return;
5572 }
5573
5574 self.outdent(&Outdent, cx);
5575 }
5576
5577 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5578 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5579 return;
5580 }
5581
5582 let mut selections = self.selections.all_adjusted(cx);
5583 let buffer = self.buffer.read(cx);
5584 let snapshot = buffer.snapshot(cx);
5585 let rows_iter = selections.iter().map(|s| s.head().row);
5586 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5587
5588 let mut edits = Vec::new();
5589 let mut prev_edited_row = 0;
5590 let mut row_delta = 0;
5591 for selection in &mut selections {
5592 if selection.start.row != prev_edited_row {
5593 row_delta = 0;
5594 }
5595 prev_edited_row = selection.end.row;
5596
5597 // If the selection is non-empty, then increase the indentation of the selected lines.
5598 if !selection.is_empty() {
5599 row_delta =
5600 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5601 continue;
5602 }
5603
5604 // If the selection is empty and the cursor is in the leading whitespace before the
5605 // suggested indentation, then auto-indent the line.
5606 let cursor = selection.head();
5607 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5608 if let Some(suggested_indent) =
5609 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5610 {
5611 if cursor.column < suggested_indent.len
5612 && cursor.column <= current_indent.len
5613 && current_indent.len <= suggested_indent.len
5614 {
5615 selection.start = Point::new(cursor.row, suggested_indent.len);
5616 selection.end = selection.start;
5617 if row_delta == 0 {
5618 edits.extend(Buffer::edit_for_indent_size_adjustment(
5619 cursor.row,
5620 current_indent,
5621 suggested_indent,
5622 ));
5623 row_delta = suggested_indent.len - current_indent.len;
5624 }
5625 continue;
5626 }
5627 }
5628
5629 // Otherwise, insert a hard or soft tab.
5630 let settings = buffer.settings_at(cursor, cx);
5631 let tab_size = if settings.hard_tabs {
5632 IndentSize::tab()
5633 } else {
5634 let tab_size = settings.tab_size.get();
5635 let char_column = snapshot
5636 .text_for_range(Point::new(cursor.row, 0)..cursor)
5637 .flat_map(str::chars)
5638 .count()
5639 + row_delta as usize;
5640 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5641 IndentSize::spaces(chars_to_next_tab_stop)
5642 };
5643 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5644 selection.end = selection.start;
5645 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5646 row_delta += tab_size.len;
5647 }
5648
5649 self.transact(cx, |this, cx| {
5650 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5651 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5652 this.refresh_inline_completion(true, false, cx);
5653 });
5654 }
5655
5656 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5657 if self.read_only(cx) {
5658 return;
5659 }
5660 let mut selections = self.selections.all::<Point>(cx);
5661 let mut prev_edited_row = 0;
5662 let mut row_delta = 0;
5663 let mut edits = Vec::new();
5664 let buffer = self.buffer.read(cx);
5665 let snapshot = buffer.snapshot(cx);
5666 for selection in &mut selections {
5667 if selection.start.row != prev_edited_row {
5668 row_delta = 0;
5669 }
5670 prev_edited_row = selection.end.row;
5671
5672 row_delta =
5673 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5674 }
5675
5676 self.transact(cx, |this, cx| {
5677 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5678 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5679 });
5680 }
5681
5682 fn indent_selection(
5683 buffer: &MultiBuffer,
5684 snapshot: &MultiBufferSnapshot,
5685 selection: &mut Selection<Point>,
5686 edits: &mut Vec<(Range<Point>, String)>,
5687 delta_for_start_row: u32,
5688 cx: &AppContext,
5689 ) -> u32 {
5690 let settings = buffer.settings_at(selection.start, cx);
5691 let tab_size = settings.tab_size.get();
5692 let indent_kind = if settings.hard_tabs {
5693 IndentKind::Tab
5694 } else {
5695 IndentKind::Space
5696 };
5697 let mut start_row = selection.start.row;
5698 let mut end_row = selection.end.row + 1;
5699
5700 // If a selection ends at the beginning of a line, don't indent
5701 // that last line.
5702 if selection.end.column == 0 && selection.end.row > selection.start.row {
5703 end_row -= 1;
5704 }
5705
5706 // Avoid re-indenting a row that has already been indented by a
5707 // previous selection, but still update this selection's column
5708 // to reflect that indentation.
5709 if delta_for_start_row > 0 {
5710 start_row += 1;
5711 selection.start.column += delta_for_start_row;
5712 if selection.end.row == selection.start.row {
5713 selection.end.column += delta_for_start_row;
5714 }
5715 }
5716
5717 let mut delta_for_end_row = 0;
5718 let has_multiple_rows = start_row + 1 != end_row;
5719 for row in start_row..end_row {
5720 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5721 let indent_delta = match (current_indent.kind, indent_kind) {
5722 (IndentKind::Space, IndentKind::Space) => {
5723 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5724 IndentSize::spaces(columns_to_next_tab_stop)
5725 }
5726 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5727 (_, IndentKind::Tab) => IndentSize::tab(),
5728 };
5729
5730 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5731 0
5732 } else {
5733 selection.start.column
5734 };
5735 let row_start = Point::new(row, start);
5736 edits.push((
5737 row_start..row_start,
5738 indent_delta.chars().collect::<String>(),
5739 ));
5740
5741 // Update this selection's endpoints to reflect the indentation.
5742 if row == selection.start.row {
5743 selection.start.column += indent_delta.len;
5744 }
5745 if row == selection.end.row {
5746 selection.end.column += indent_delta.len;
5747 delta_for_end_row = indent_delta.len;
5748 }
5749 }
5750
5751 if selection.start.row == selection.end.row {
5752 delta_for_start_row + delta_for_end_row
5753 } else {
5754 delta_for_end_row
5755 }
5756 }
5757
5758 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5759 if self.read_only(cx) {
5760 return;
5761 }
5762 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5763 let selections = self.selections.all::<Point>(cx);
5764 let mut deletion_ranges = Vec::new();
5765 let mut last_outdent = None;
5766 {
5767 let buffer = self.buffer.read(cx);
5768 let snapshot = buffer.snapshot(cx);
5769 for selection in &selections {
5770 let settings = buffer.settings_at(selection.start, cx);
5771 let tab_size = settings.tab_size.get();
5772 let mut rows = selection.spanned_rows(false, &display_map);
5773
5774 // Avoid re-outdenting a row that has already been outdented by a
5775 // previous selection.
5776 if let Some(last_row) = last_outdent {
5777 if last_row == rows.start {
5778 rows.start = rows.start.next_row();
5779 }
5780 }
5781 let has_multiple_rows = rows.len() > 1;
5782 for row in rows.iter_rows() {
5783 let indent_size = snapshot.indent_size_for_line(row);
5784 if indent_size.len > 0 {
5785 let deletion_len = match indent_size.kind {
5786 IndentKind::Space => {
5787 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5788 if columns_to_prev_tab_stop == 0 {
5789 tab_size
5790 } else {
5791 columns_to_prev_tab_stop
5792 }
5793 }
5794 IndentKind::Tab => 1,
5795 };
5796 let start = if has_multiple_rows
5797 || deletion_len > selection.start.column
5798 || indent_size.len < selection.start.column
5799 {
5800 0
5801 } else {
5802 selection.start.column - deletion_len
5803 };
5804 deletion_ranges.push(
5805 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5806 );
5807 last_outdent = Some(row);
5808 }
5809 }
5810 }
5811 }
5812
5813 self.transact(cx, |this, cx| {
5814 this.buffer.update(cx, |buffer, cx| {
5815 let empty_str: Arc<str> = Arc::default();
5816 buffer.edit(
5817 deletion_ranges
5818 .into_iter()
5819 .map(|range| (range, empty_str.clone())),
5820 None,
5821 cx,
5822 );
5823 });
5824 let selections = this.selections.all::<usize>(cx);
5825 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5826 });
5827 }
5828
5829 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5830 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5831 let selections = self.selections.all::<Point>(cx);
5832
5833 let mut new_cursors = Vec::new();
5834 let mut edit_ranges = Vec::new();
5835 let mut selections = selections.iter().peekable();
5836 while let Some(selection) = selections.next() {
5837 let mut rows = selection.spanned_rows(false, &display_map);
5838 let goal_display_column = selection.head().to_display_point(&display_map).column();
5839
5840 // Accumulate contiguous regions of rows that we want to delete.
5841 while let Some(next_selection) = selections.peek() {
5842 let next_rows = next_selection.spanned_rows(false, &display_map);
5843 if next_rows.start <= rows.end {
5844 rows.end = next_rows.end;
5845 selections.next().unwrap();
5846 } else {
5847 break;
5848 }
5849 }
5850
5851 let buffer = &display_map.buffer_snapshot;
5852 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5853 let edit_end;
5854 let cursor_buffer_row;
5855 if buffer.max_point().row >= rows.end.0 {
5856 // If there's a line after the range, delete the \n from the end of the row range
5857 // and position the cursor on the next line.
5858 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5859 cursor_buffer_row = rows.end;
5860 } else {
5861 // If there isn't a line after the range, delete the \n from the line before the
5862 // start of the row range and position the cursor there.
5863 edit_start = edit_start.saturating_sub(1);
5864 edit_end = buffer.len();
5865 cursor_buffer_row = rows.start.previous_row();
5866 }
5867
5868 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5869 *cursor.column_mut() =
5870 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5871
5872 new_cursors.push((
5873 selection.id,
5874 buffer.anchor_after(cursor.to_point(&display_map)),
5875 ));
5876 edit_ranges.push(edit_start..edit_end);
5877 }
5878
5879 self.transact(cx, |this, cx| {
5880 let buffer = this.buffer.update(cx, |buffer, cx| {
5881 let empty_str: Arc<str> = Arc::default();
5882 buffer.edit(
5883 edit_ranges
5884 .into_iter()
5885 .map(|range| (range, empty_str.clone())),
5886 None,
5887 cx,
5888 );
5889 buffer.snapshot(cx)
5890 });
5891 let new_selections = new_cursors
5892 .into_iter()
5893 .map(|(id, cursor)| {
5894 let cursor = cursor.to_point(&buffer);
5895 Selection {
5896 id,
5897 start: cursor,
5898 end: cursor,
5899 reversed: false,
5900 goal: SelectionGoal::None,
5901 }
5902 })
5903 .collect();
5904
5905 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5906 s.select(new_selections);
5907 });
5908 });
5909 }
5910
5911 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5912 if self.read_only(cx) {
5913 return;
5914 }
5915 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5916 for selection in self.selections.all::<Point>(cx) {
5917 let start = MultiBufferRow(selection.start.row);
5918 let end = if selection.start.row == selection.end.row {
5919 MultiBufferRow(selection.start.row + 1)
5920 } else {
5921 MultiBufferRow(selection.end.row)
5922 };
5923
5924 if let Some(last_row_range) = row_ranges.last_mut() {
5925 if start <= last_row_range.end {
5926 last_row_range.end = end;
5927 continue;
5928 }
5929 }
5930 row_ranges.push(start..end);
5931 }
5932
5933 let snapshot = self.buffer.read(cx).snapshot(cx);
5934 let mut cursor_positions = Vec::new();
5935 for row_range in &row_ranges {
5936 let anchor = snapshot.anchor_before(Point::new(
5937 row_range.end.previous_row().0,
5938 snapshot.line_len(row_range.end.previous_row()),
5939 ));
5940 cursor_positions.push(anchor..anchor);
5941 }
5942
5943 self.transact(cx, |this, cx| {
5944 for row_range in row_ranges.into_iter().rev() {
5945 for row in row_range.iter_rows().rev() {
5946 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5947 let next_line_row = row.next_row();
5948 let indent = snapshot.indent_size_for_line(next_line_row);
5949 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5950
5951 let replace = if snapshot.line_len(next_line_row) > indent.len {
5952 " "
5953 } else {
5954 ""
5955 };
5956
5957 this.buffer.update(cx, |buffer, cx| {
5958 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5959 });
5960 }
5961 }
5962
5963 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5964 s.select_anchor_ranges(cursor_positions)
5965 });
5966 });
5967 }
5968
5969 pub fn sort_lines_case_sensitive(
5970 &mut self,
5971 _: &SortLinesCaseSensitive,
5972 cx: &mut ViewContext<Self>,
5973 ) {
5974 self.manipulate_lines(cx, |lines| lines.sort())
5975 }
5976
5977 pub fn sort_lines_case_insensitive(
5978 &mut self,
5979 _: &SortLinesCaseInsensitive,
5980 cx: &mut ViewContext<Self>,
5981 ) {
5982 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5983 }
5984
5985 pub fn unique_lines_case_insensitive(
5986 &mut self,
5987 _: &UniqueLinesCaseInsensitive,
5988 cx: &mut ViewContext<Self>,
5989 ) {
5990 self.manipulate_lines(cx, |lines| {
5991 let mut seen = HashSet::default();
5992 lines.retain(|line| seen.insert(line.to_lowercase()));
5993 })
5994 }
5995
5996 pub fn unique_lines_case_sensitive(
5997 &mut self,
5998 _: &UniqueLinesCaseSensitive,
5999 cx: &mut ViewContext<Self>,
6000 ) {
6001 self.manipulate_lines(cx, |lines| {
6002 let mut seen = HashSet::default();
6003 lines.retain(|line| seen.insert(*line));
6004 })
6005 }
6006
6007 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6008 let mut revert_changes = HashMap::default();
6009 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6010 for hunk in hunks_for_rows(
6011 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6012 &multi_buffer_snapshot,
6013 ) {
6014 Self::prepare_revert_change(&mut revert_changes, &self.buffer(), &hunk, cx);
6015 }
6016 if !revert_changes.is_empty() {
6017 self.transact(cx, |editor, cx| {
6018 editor.revert(revert_changes, cx);
6019 });
6020 }
6021 }
6022
6023 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6024 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6025 if !revert_changes.is_empty() {
6026 self.transact(cx, |editor, cx| {
6027 editor.revert(revert_changes, cx);
6028 });
6029 }
6030 }
6031
6032 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6033 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6034 let project_path = buffer.read(cx).project_path(cx)?;
6035 let project = self.project.as_ref()?.read(cx);
6036 let entry = project.entry_for_path(&project_path, cx)?;
6037 let abs_path = project.absolute_path(&project_path, cx)?;
6038 let parent = if entry.is_symlink {
6039 abs_path.canonicalize().ok()?
6040 } else {
6041 abs_path
6042 }
6043 .parent()?
6044 .to_path_buf();
6045 Some(parent)
6046 }) {
6047 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6048 }
6049 }
6050
6051 fn gather_revert_changes(
6052 &mut self,
6053 selections: &[Selection<Anchor>],
6054 cx: &mut ViewContext<'_, Editor>,
6055 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6056 let mut revert_changes = HashMap::default();
6057 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6058 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6059 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6060 }
6061 revert_changes
6062 }
6063
6064 pub fn prepare_revert_change(
6065 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6066 multi_buffer: &Model<MultiBuffer>,
6067 hunk: &DiffHunk<MultiBufferRow>,
6068 cx: &AppContext,
6069 ) -> Option<()> {
6070 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6071 let buffer = buffer.read(cx);
6072 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6073 let buffer_snapshot = buffer.snapshot();
6074 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6075 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6076 probe
6077 .0
6078 .start
6079 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6080 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6081 }) {
6082 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6083 Some(())
6084 } else {
6085 None
6086 }
6087 }
6088
6089 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6090 self.manipulate_lines(cx, |lines| lines.reverse())
6091 }
6092
6093 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6094 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6095 }
6096
6097 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6098 where
6099 Fn: FnMut(&mut Vec<&str>),
6100 {
6101 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6102 let buffer = self.buffer.read(cx).snapshot(cx);
6103
6104 let mut edits = Vec::new();
6105
6106 let selections = self.selections.all::<Point>(cx);
6107 let mut selections = selections.iter().peekable();
6108 let mut contiguous_row_selections = Vec::new();
6109 let mut new_selections = Vec::new();
6110 let mut added_lines = 0;
6111 let mut removed_lines = 0;
6112
6113 while let Some(selection) = selections.next() {
6114 let (start_row, end_row) = consume_contiguous_rows(
6115 &mut contiguous_row_selections,
6116 selection,
6117 &display_map,
6118 &mut selections,
6119 );
6120
6121 let start_point = Point::new(start_row.0, 0);
6122 let end_point = Point::new(
6123 end_row.previous_row().0,
6124 buffer.line_len(end_row.previous_row()),
6125 );
6126 let text = buffer
6127 .text_for_range(start_point..end_point)
6128 .collect::<String>();
6129
6130 let mut lines = text.split('\n').collect_vec();
6131
6132 let lines_before = lines.len();
6133 callback(&mut lines);
6134 let lines_after = lines.len();
6135
6136 edits.push((start_point..end_point, lines.join("\n")));
6137
6138 // Selections must change based on added and removed line count
6139 let start_row =
6140 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6141 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6142 new_selections.push(Selection {
6143 id: selection.id,
6144 start: start_row,
6145 end: end_row,
6146 goal: SelectionGoal::None,
6147 reversed: selection.reversed,
6148 });
6149
6150 if lines_after > lines_before {
6151 added_lines += lines_after - lines_before;
6152 } else if lines_before > lines_after {
6153 removed_lines += lines_before - lines_after;
6154 }
6155 }
6156
6157 self.transact(cx, |this, cx| {
6158 let buffer = this.buffer.update(cx, |buffer, cx| {
6159 buffer.edit(edits, None, cx);
6160 buffer.snapshot(cx)
6161 });
6162
6163 // Recalculate offsets on newly edited buffer
6164 let new_selections = new_selections
6165 .iter()
6166 .map(|s| {
6167 let start_point = Point::new(s.start.0, 0);
6168 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6169 Selection {
6170 id: s.id,
6171 start: buffer.point_to_offset(start_point),
6172 end: buffer.point_to_offset(end_point),
6173 goal: s.goal,
6174 reversed: s.reversed,
6175 }
6176 })
6177 .collect();
6178
6179 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6180 s.select(new_selections);
6181 });
6182
6183 this.request_autoscroll(Autoscroll::fit(), cx);
6184 });
6185 }
6186
6187 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6188 self.manipulate_text(cx, |text| text.to_uppercase())
6189 }
6190
6191 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6192 self.manipulate_text(cx, |text| text.to_lowercase())
6193 }
6194
6195 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6196 self.manipulate_text(cx, |text| {
6197 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6198 // https://github.com/rutrum/convert-case/issues/16
6199 text.split('\n')
6200 .map(|line| line.to_case(Case::Title))
6201 .join("\n")
6202 })
6203 }
6204
6205 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6206 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6207 }
6208
6209 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6210 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6211 }
6212
6213 pub fn convert_to_upper_camel_case(
6214 &mut self,
6215 _: &ConvertToUpperCamelCase,
6216 cx: &mut ViewContext<Self>,
6217 ) {
6218 self.manipulate_text(cx, |text| {
6219 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6220 // https://github.com/rutrum/convert-case/issues/16
6221 text.split('\n')
6222 .map(|line| line.to_case(Case::UpperCamel))
6223 .join("\n")
6224 })
6225 }
6226
6227 pub fn convert_to_lower_camel_case(
6228 &mut self,
6229 _: &ConvertToLowerCamelCase,
6230 cx: &mut ViewContext<Self>,
6231 ) {
6232 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6233 }
6234
6235 pub fn convert_to_opposite_case(
6236 &mut self,
6237 _: &ConvertToOppositeCase,
6238 cx: &mut ViewContext<Self>,
6239 ) {
6240 self.manipulate_text(cx, |text| {
6241 text.chars()
6242 .fold(String::with_capacity(text.len()), |mut t, c| {
6243 if c.is_uppercase() {
6244 t.extend(c.to_lowercase());
6245 } else {
6246 t.extend(c.to_uppercase());
6247 }
6248 t
6249 })
6250 })
6251 }
6252
6253 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6254 where
6255 Fn: FnMut(&str) -> String,
6256 {
6257 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6258 let buffer = self.buffer.read(cx).snapshot(cx);
6259
6260 let mut new_selections = Vec::new();
6261 let mut edits = Vec::new();
6262 let mut selection_adjustment = 0i32;
6263
6264 for selection in self.selections.all::<usize>(cx) {
6265 let selection_is_empty = selection.is_empty();
6266
6267 let (start, end) = if selection_is_empty {
6268 let word_range = movement::surrounding_word(
6269 &display_map,
6270 selection.start.to_display_point(&display_map),
6271 );
6272 let start = word_range.start.to_offset(&display_map, Bias::Left);
6273 let end = word_range.end.to_offset(&display_map, Bias::Left);
6274 (start, end)
6275 } else {
6276 (selection.start, selection.end)
6277 };
6278
6279 let text = buffer.text_for_range(start..end).collect::<String>();
6280 let old_length = text.len() as i32;
6281 let text = callback(&text);
6282
6283 new_selections.push(Selection {
6284 start: (start as i32 - selection_adjustment) as usize,
6285 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6286 goal: SelectionGoal::None,
6287 ..selection
6288 });
6289
6290 selection_adjustment += old_length - text.len() as i32;
6291
6292 edits.push((start..end, text));
6293 }
6294
6295 self.transact(cx, |this, cx| {
6296 this.buffer.update(cx, |buffer, cx| {
6297 buffer.edit(edits, None, cx);
6298 });
6299
6300 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6301 s.select(new_selections);
6302 });
6303
6304 this.request_autoscroll(Autoscroll::fit(), cx);
6305 });
6306 }
6307
6308 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6309 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6310 let buffer = &display_map.buffer_snapshot;
6311 let selections = self.selections.all::<Point>(cx);
6312
6313 let mut edits = Vec::new();
6314 let mut selections_iter = selections.iter().peekable();
6315 while let Some(selection) = selections_iter.next() {
6316 // Avoid duplicating the same lines twice.
6317 let mut rows = selection.spanned_rows(false, &display_map);
6318
6319 while let Some(next_selection) = selections_iter.peek() {
6320 let next_rows = next_selection.spanned_rows(false, &display_map);
6321 if next_rows.start < rows.end {
6322 rows.end = next_rows.end;
6323 selections_iter.next().unwrap();
6324 } else {
6325 break;
6326 }
6327 }
6328
6329 // Copy the text from the selected row region and splice it either at the start
6330 // or end of the region.
6331 let start = Point::new(rows.start.0, 0);
6332 let end = Point::new(
6333 rows.end.previous_row().0,
6334 buffer.line_len(rows.end.previous_row()),
6335 );
6336 let text = buffer
6337 .text_for_range(start..end)
6338 .chain(Some("\n"))
6339 .collect::<String>();
6340 let insert_location = if upwards {
6341 Point::new(rows.end.0, 0)
6342 } else {
6343 start
6344 };
6345 edits.push((insert_location..insert_location, text));
6346 }
6347
6348 self.transact(cx, |this, cx| {
6349 this.buffer.update(cx, |buffer, cx| {
6350 buffer.edit(edits, None, cx);
6351 });
6352
6353 this.request_autoscroll(Autoscroll::fit(), cx);
6354 });
6355 }
6356
6357 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6358 self.duplicate_line(true, cx);
6359 }
6360
6361 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6362 self.duplicate_line(false, cx);
6363 }
6364
6365 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6366 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6367 let buffer = self.buffer.read(cx).snapshot(cx);
6368
6369 let mut edits = Vec::new();
6370 let mut unfold_ranges = Vec::new();
6371 let mut refold_ranges = Vec::new();
6372
6373 let selections = self.selections.all::<Point>(cx);
6374 let mut selections = selections.iter().peekable();
6375 let mut contiguous_row_selections = Vec::new();
6376 let mut new_selections = Vec::new();
6377
6378 while let Some(selection) = selections.next() {
6379 // Find all the selections that span a contiguous row range
6380 let (start_row, end_row) = consume_contiguous_rows(
6381 &mut contiguous_row_selections,
6382 selection,
6383 &display_map,
6384 &mut selections,
6385 );
6386
6387 // Move the text spanned by the row range to be before the line preceding the row range
6388 if start_row.0 > 0 {
6389 let range_to_move = Point::new(
6390 start_row.previous_row().0,
6391 buffer.line_len(start_row.previous_row()),
6392 )
6393 ..Point::new(
6394 end_row.previous_row().0,
6395 buffer.line_len(end_row.previous_row()),
6396 );
6397 let insertion_point = display_map
6398 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6399 .0;
6400
6401 // Don't move lines across excerpts
6402 if buffer
6403 .excerpt_boundaries_in_range((
6404 Bound::Excluded(insertion_point),
6405 Bound::Included(range_to_move.end),
6406 ))
6407 .next()
6408 .is_none()
6409 {
6410 let text = buffer
6411 .text_for_range(range_to_move.clone())
6412 .flat_map(|s| s.chars())
6413 .skip(1)
6414 .chain(['\n'])
6415 .collect::<String>();
6416
6417 edits.push((
6418 buffer.anchor_after(range_to_move.start)
6419 ..buffer.anchor_before(range_to_move.end),
6420 String::new(),
6421 ));
6422 let insertion_anchor = buffer.anchor_after(insertion_point);
6423 edits.push((insertion_anchor..insertion_anchor, text));
6424
6425 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6426
6427 // Move selections up
6428 new_selections.extend(contiguous_row_selections.drain(..).map(
6429 |mut selection| {
6430 selection.start.row -= row_delta;
6431 selection.end.row -= row_delta;
6432 selection
6433 },
6434 ));
6435
6436 // Move folds up
6437 unfold_ranges.push(range_to_move.clone());
6438 for fold in display_map.folds_in_range(
6439 buffer.anchor_before(range_to_move.start)
6440 ..buffer.anchor_after(range_to_move.end),
6441 ) {
6442 let mut start = fold.range.start.to_point(&buffer);
6443 let mut end = fold.range.end.to_point(&buffer);
6444 start.row -= row_delta;
6445 end.row -= row_delta;
6446 refold_ranges.push((start..end, fold.placeholder.clone()));
6447 }
6448 }
6449 }
6450
6451 // If we didn't move line(s), preserve the existing selections
6452 new_selections.append(&mut contiguous_row_selections);
6453 }
6454
6455 self.transact(cx, |this, cx| {
6456 this.unfold_ranges(unfold_ranges, true, true, cx);
6457 this.buffer.update(cx, |buffer, cx| {
6458 for (range, text) in edits {
6459 buffer.edit([(range, text)], None, cx);
6460 }
6461 });
6462 this.fold_ranges(refold_ranges, true, cx);
6463 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6464 s.select(new_selections);
6465 })
6466 });
6467 }
6468
6469 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6470 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6471 let buffer = self.buffer.read(cx).snapshot(cx);
6472
6473 let mut edits = Vec::new();
6474 let mut unfold_ranges = Vec::new();
6475 let mut refold_ranges = Vec::new();
6476
6477 let selections = self.selections.all::<Point>(cx);
6478 let mut selections = selections.iter().peekable();
6479 let mut contiguous_row_selections = Vec::new();
6480 let mut new_selections = Vec::new();
6481
6482 while let Some(selection) = selections.next() {
6483 // Find all the selections that span a contiguous row range
6484 let (start_row, end_row) = consume_contiguous_rows(
6485 &mut contiguous_row_selections,
6486 selection,
6487 &display_map,
6488 &mut selections,
6489 );
6490
6491 // Move the text spanned by the row range to be after the last line of the row range
6492 if end_row.0 <= buffer.max_point().row {
6493 let range_to_move =
6494 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6495 let insertion_point = display_map
6496 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6497 .0;
6498
6499 // Don't move lines across excerpt boundaries
6500 if buffer
6501 .excerpt_boundaries_in_range((
6502 Bound::Excluded(range_to_move.start),
6503 Bound::Included(insertion_point),
6504 ))
6505 .next()
6506 .is_none()
6507 {
6508 let mut text = String::from("\n");
6509 text.extend(buffer.text_for_range(range_to_move.clone()));
6510 text.pop(); // Drop trailing newline
6511 edits.push((
6512 buffer.anchor_after(range_to_move.start)
6513 ..buffer.anchor_before(range_to_move.end),
6514 String::new(),
6515 ));
6516 let insertion_anchor = buffer.anchor_after(insertion_point);
6517 edits.push((insertion_anchor..insertion_anchor, text));
6518
6519 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6520
6521 // Move selections down
6522 new_selections.extend(contiguous_row_selections.drain(..).map(
6523 |mut selection| {
6524 selection.start.row += row_delta;
6525 selection.end.row += row_delta;
6526 selection
6527 },
6528 ));
6529
6530 // Move folds down
6531 unfold_ranges.push(range_to_move.clone());
6532 for fold in display_map.folds_in_range(
6533 buffer.anchor_before(range_to_move.start)
6534 ..buffer.anchor_after(range_to_move.end),
6535 ) {
6536 let mut start = fold.range.start.to_point(&buffer);
6537 let mut end = fold.range.end.to_point(&buffer);
6538 start.row += row_delta;
6539 end.row += row_delta;
6540 refold_ranges.push((start..end, fold.placeholder.clone()));
6541 }
6542 }
6543 }
6544
6545 // If we didn't move line(s), preserve the existing selections
6546 new_selections.append(&mut contiguous_row_selections);
6547 }
6548
6549 self.transact(cx, |this, cx| {
6550 this.unfold_ranges(unfold_ranges, true, true, cx);
6551 this.buffer.update(cx, |buffer, cx| {
6552 for (range, text) in edits {
6553 buffer.edit([(range, text)], None, cx);
6554 }
6555 });
6556 this.fold_ranges(refold_ranges, true, cx);
6557 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6558 });
6559 }
6560
6561 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6562 let text_layout_details = &self.text_layout_details(cx);
6563 self.transact(cx, |this, cx| {
6564 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6565 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6566 let line_mode = s.line_mode;
6567 s.move_with(|display_map, selection| {
6568 if !selection.is_empty() || line_mode {
6569 return;
6570 }
6571
6572 let mut head = selection.head();
6573 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6574 if head.column() == display_map.line_len(head.row()) {
6575 transpose_offset = display_map
6576 .buffer_snapshot
6577 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6578 }
6579
6580 if transpose_offset == 0 {
6581 return;
6582 }
6583
6584 *head.column_mut() += 1;
6585 head = display_map.clip_point(head, Bias::Right);
6586 let goal = SelectionGoal::HorizontalPosition(
6587 display_map
6588 .x_for_display_point(head, &text_layout_details)
6589 .into(),
6590 );
6591 selection.collapse_to(head, goal);
6592
6593 let transpose_start = display_map
6594 .buffer_snapshot
6595 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6596 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6597 let transpose_end = display_map
6598 .buffer_snapshot
6599 .clip_offset(transpose_offset + 1, Bias::Right);
6600 if let Some(ch) =
6601 display_map.buffer_snapshot.chars_at(transpose_start).next()
6602 {
6603 edits.push((transpose_start..transpose_offset, String::new()));
6604 edits.push((transpose_end..transpose_end, ch.to_string()));
6605 }
6606 }
6607 });
6608 edits
6609 });
6610 this.buffer
6611 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6612 let selections = this.selections.all::<usize>(cx);
6613 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6614 s.select(selections);
6615 });
6616 });
6617 }
6618
6619 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6620 let mut text = String::new();
6621 let buffer = self.buffer.read(cx).snapshot(cx);
6622 let mut selections = self.selections.all::<Point>(cx);
6623 let mut clipboard_selections = Vec::with_capacity(selections.len());
6624 {
6625 let max_point = buffer.max_point();
6626 let mut is_first = true;
6627 for selection in &mut selections {
6628 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6629 if is_entire_line {
6630 selection.start = Point::new(selection.start.row, 0);
6631 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6632 selection.goal = SelectionGoal::None;
6633 }
6634 if is_first {
6635 is_first = false;
6636 } else {
6637 text += "\n";
6638 }
6639 let mut len = 0;
6640 for chunk in buffer.text_for_range(selection.start..selection.end) {
6641 text.push_str(chunk);
6642 len += chunk.len();
6643 }
6644 clipboard_selections.push(ClipboardSelection {
6645 len,
6646 is_entire_line,
6647 first_line_indent: buffer
6648 .indent_size_for_line(MultiBufferRow(selection.start.row))
6649 .len,
6650 });
6651 }
6652 }
6653
6654 self.transact(cx, |this, cx| {
6655 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6656 s.select(selections);
6657 });
6658 this.insert("", cx);
6659 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6660 text,
6661 clipboard_selections,
6662 ));
6663 });
6664 }
6665
6666 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6667 let selections = self.selections.all::<Point>(cx);
6668 let buffer = self.buffer.read(cx).read(cx);
6669 let mut text = String::new();
6670
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 selections.iter() {
6676 let mut start = selection.start;
6677 let mut end = selection.end;
6678 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6679 if is_entire_line {
6680 start = Point::new(start.row, 0);
6681 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6682 }
6683 if is_first {
6684 is_first = false;
6685 } else {
6686 text += "\n";
6687 }
6688 let mut len = 0;
6689 for chunk in buffer.text_for_range(start..end) {
6690 text.push_str(chunk);
6691 len += chunk.len();
6692 }
6693 clipboard_selections.push(ClipboardSelection {
6694 len,
6695 is_entire_line,
6696 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6697 });
6698 }
6699 }
6700
6701 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6702 text,
6703 clipboard_selections,
6704 ));
6705 }
6706
6707 pub fn do_paste(
6708 &mut self,
6709 text: &String,
6710 clipboard_selections: Option<Vec<ClipboardSelection>>,
6711 handle_entire_lines: bool,
6712 cx: &mut ViewContext<Self>,
6713 ) {
6714 if self.read_only(cx) {
6715 return;
6716 }
6717
6718 let clipboard_text = Cow::Borrowed(text);
6719
6720 self.transact(cx, |this, cx| {
6721 if let Some(mut clipboard_selections) = clipboard_selections {
6722 let old_selections = this.selections.all::<usize>(cx);
6723 let all_selections_were_entire_line =
6724 clipboard_selections.iter().all(|s| s.is_entire_line);
6725 let first_selection_indent_column =
6726 clipboard_selections.first().map(|s| s.first_line_indent);
6727 if clipboard_selections.len() != old_selections.len() {
6728 clipboard_selections.drain(..);
6729 }
6730
6731 this.buffer.update(cx, |buffer, cx| {
6732 let snapshot = buffer.read(cx);
6733 let mut start_offset = 0;
6734 let mut edits = Vec::new();
6735 let mut original_indent_columns = Vec::new();
6736 for (ix, selection) in old_selections.iter().enumerate() {
6737 let to_insert;
6738 let entire_line;
6739 let original_indent_column;
6740 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6741 let end_offset = start_offset + clipboard_selection.len;
6742 to_insert = &clipboard_text[start_offset..end_offset];
6743 entire_line = clipboard_selection.is_entire_line;
6744 start_offset = end_offset + 1;
6745 original_indent_column = Some(clipboard_selection.first_line_indent);
6746 } else {
6747 to_insert = clipboard_text.as_str();
6748 entire_line = all_selections_were_entire_line;
6749 original_indent_column = first_selection_indent_column
6750 }
6751
6752 // If the corresponding selection was empty when this slice of the
6753 // clipboard text was written, then the entire line containing the
6754 // selection was copied. If this selection is also currently empty,
6755 // then paste the line before the current line of the buffer.
6756 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6757 let column = selection.start.to_point(&snapshot).column as usize;
6758 let line_start = selection.start - column;
6759 line_start..line_start
6760 } else {
6761 selection.range()
6762 };
6763
6764 edits.push((range, to_insert));
6765 original_indent_columns.extend(original_indent_column);
6766 }
6767 drop(snapshot);
6768
6769 buffer.edit(
6770 edits,
6771 Some(AutoindentMode::Block {
6772 original_indent_columns,
6773 }),
6774 cx,
6775 );
6776 });
6777
6778 let selections = this.selections.all::<usize>(cx);
6779 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6780 } else {
6781 this.insert(&clipboard_text, cx);
6782 }
6783 });
6784 }
6785
6786 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
6787 if let Some(item) = cx.read_from_clipboard() {
6788 let entries = item.entries();
6789
6790 match entries.first() {
6791 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
6792 // of all the pasted entries.
6793 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
6794 .do_paste(
6795 clipboard_string.text(),
6796 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
6797 true,
6798 cx,
6799 ),
6800 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
6801 }
6802 }
6803 }
6804
6805 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
6806 if self.read_only(cx) {
6807 return;
6808 }
6809
6810 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
6811 if let Some((selections, _)) =
6812 self.selection_history.transaction(transaction_id).cloned()
6813 {
6814 self.change_selections(None, cx, |s| {
6815 s.select_anchors(selections.to_vec());
6816 });
6817 }
6818 self.request_autoscroll(Autoscroll::fit(), cx);
6819 self.unmark_text(cx);
6820 self.refresh_inline_completion(true, false, cx);
6821 cx.emit(EditorEvent::Edited { transaction_id });
6822 cx.emit(EditorEvent::TransactionUndone { transaction_id });
6823 }
6824 }
6825
6826 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
6827 if self.read_only(cx) {
6828 return;
6829 }
6830
6831 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
6832 if let Some((_, Some(selections))) =
6833 self.selection_history.transaction(transaction_id).cloned()
6834 {
6835 self.change_selections(None, cx, |s| {
6836 s.select_anchors(selections.to_vec());
6837 });
6838 }
6839 self.request_autoscroll(Autoscroll::fit(), cx);
6840 self.unmark_text(cx);
6841 self.refresh_inline_completion(true, false, cx);
6842 cx.emit(EditorEvent::Edited { transaction_id });
6843 }
6844 }
6845
6846 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
6847 self.buffer
6848 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
6849 }
6850
6851 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
6852 self.buffer
6853 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
6854 }
6855
6856 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
6857 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6858 let line_mode = s.line_mode;
6859 s.move_with(|map, selection| {
6860 let cursor = if selection.is_empty() && !line_mode {
6861 movement::left(map, selection.start)
6862 } else {
6863 selection.start
6864 };
6865 selection.collapse_to(cursor, SelectionGoal::None);
6866 });
6867 })
6868 }
6869
6870 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
6871 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6872 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
6873 })
6874 }
6875
6876 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
6877 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6878 let line_mode = s.line_mode;
6879 s.move_with(|map, selection| {
6880 let cursor = if selection.is_empty() && !line_mode {
6881 movement::right(map, selection.end)
6882 } else {
6883 selection.end
6884 };
6885 selection.collapse_to(cursor, SelectionGoal::None)
6886 });
6887 })
6888 }
6889
6890 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
6891 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6892 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
6893 })
6894 }
6895
6896 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
6897 if self.take_rename(true, cx).is_some() {
6898 return;
6899 }
6900
6901 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6902 cx.propagate();
6903 return;
6904 }
6905
6906 let text_layout_details = &self.text_layout_details(cx);
6907 let selection_count = self.selections.count();
6908 let first_selection = self.selections.first_anchor();
6909
6910 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6911 let line_mode = s.line_mode;
6912 s.move_with(|map, selection| {
6913 if !selection.is_empty() && !line_mode {
6914 selection.goal = SelectionGoal::None;
6915 }
6916 let (cursor, goal) = movement::up(
6917 map,
6918 selection.start,
6919 selection.goal,
6920 false,
6921 &text_layout_details,
6922 );
6923 selection.collapse_to(cursor, goal);
6924 });
6925 });
6926
6927 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
6928 {
6929 cx.propagate();
6930 }
6931 }
6932
6933 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
6934 if self.take_rename(true, cx).is_some() {
6935 return;
6936 }
6937
6938 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6939 cx.propagate();
6940 return;
6941 }
6942
6943 let text_layout_details = &self.text_layout_details(cx);
6944
6945 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6946 let line_mode = s.line_mode;
6947 s.move_with(|map, selection| {
6948 if !selection.is_empty() && !line_mode {
6949 selection.goal = SelectionGoal::None;
6950 }
6951 let (cursor, goal) = movement::up_by_rows(
6952 map,
6953 selection.start,
6954 action.lines,
6955 selection.goal,
6956 false,
6957 &text_layout_details,
6958 );
6959 selection.collapse_to(cursor, goal);
6960 });
6961 })
6962 }
6963
6964 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
6965 if self.take_rename(true, cx).is_some() {
6966 return;
6967 }
6968
6969 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6970 cx.propagate();
6971 return;
6972 }
6973
6974 let text_layout_details = &self.text_layout_details(cx);
6975
6976 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6977 let line_mode = s.line_mode;
6978 s.move_with(|map, selection| {
6979 if !selection.is_empty() && !line_mode {
6980 selection.goal = SelectionGoal::None;
6981 }
6982 let (cursor, goal) = movement::down_by_rows(
6983 map,
6984 selection.start,
6985 action.lines,
6986 selection.goal,
6987 false,
6988 &text_layout_details,
6989 );
6990 selection.collapse_to(cursor, goal);
6991 });
6992 })
6993 }
6994
6995 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
6996 let text_layout_details = &self.text_layout_details(cx);
6997 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6998 s.move_heads_with(|map, head, goal| {
6999 movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
7000 })
7001 })
7002 }
7003
7004 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7005 let text_layout_details = &self.text_layout_details(cx);
7006 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7007 s.move_heads_with(|map, head, goal| {
7008 movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
7009 })
7010 })
7011 }
7012
7013 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7014 let Some(row_count) = self.visible_row_count() else {
7015 return;
7016 };
7017
7018 let text_layout_details = &self.text_layout_details(cx);
7019
7020 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7021 s.move_heads_with(|map, head, goal| {
7022 movement::up_by_rows(map, head, row_count, goal, false, &text_layout_details)
7023 })
7024 })
7025 }
7026
7027 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7028 if self.take_rename(true, cx).is_some() {
7029 return;
7030 }
7031
7032 if self
7033 .context_menu
7034 .write()
7035 .as_mut()
7036 .map(|menu| menu.select_first(self.project.as_ref(), cx))
7037 .unwrap_or(false)
7038 {
7039 return;
7040 }
7041
7042 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7043 cx.propagate();
7044 return;
7045 }
7046
7047 let Some(row_count) = self.visible_row_count() else {
7048 return;
7049 };
7050
7051 let autoscroll = if action.center_cursor {
7052 Autoscroll::center()
7053 } else {
7054 Autoscroll::fit()
7055 };
7056
7057 let text_layout_details = &self.text_layout_details(cx);
7058
7059 self.change_selections(Some(autoscroll), cx, |s| {
7060 let line_mode = s.line_mode;
7061 s.move_with(|map, selection| {
7062 if !selection.is_empty() && !line_mode {
7063 selection.goal = SelectionGoal::None;
7064 }
7065 let (cursor, goal) = movement::up_by_rows(
7066 map,
7067 selection.end,
7068 row_count,
7069 selection.goal,
7070 false,
7071 &text_layout_details,
7072 );
7073 selection.collapse_to(cursor, goal);
7074 });
7075 });
7076 }
7077
7078 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7079 let text_layout_details = &self.text_layout_details(cx);
7080 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7081 s.move_heads_with(|map, head, goal| {
7082 movement::up(map, head, goal, false, &text_layout_details)
7083 })
7084 })
7085 }
7086
7087 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7088 self.take_rename(true, cx);
7089
7090 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7091 cx.propagate();
7092 return;
7093 }
7094
7095 let text_layout_details = &self.text_layout_details(cx);
7096 let selection_count = self.selections.count();
7097 let first_selection = self.selections.first_anchor();
7098
7099 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7100 let line_mode = s.line_mode;
7101 s.move_with(|map, selection| {
7102 if !selection.is_empty() && !line_mode {
7103 selection.goal = SelectionGoal::None;
7104 }
7105 let (cursor, goal) = movement::down(
7106 map,
7107 selection.end,
7108 selection.goal,
7109 false,
7110 &text_layout_details,
7111 );
7112 selection.collapse_to(cursor, goal);
7113 });
7114 });
7115
7116 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7117 {
7118 cx.propagate();
7119 }
7120 }
7121
7122 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7123 let Some(row_count) = self.visible_row_count() else {
7124 return;
7125 };
7126
7127 let text_layout_details = &self.text_layout_details(cx);
7128
7129 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7130 s.move_heads_with(|map, head, goal| {
7131 movement::down_by_rows(map, head, row_count, goal, false, &text_layout_details)
7132 })
7133 })
7134 }
7135
7136 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7137 if self.take_rename(true, cx).is_some() {
7138 return;
7139 }
7140
7141 if self
7142 .context_menu
7143 .write()
7144 .as_mut()
7145 .map(|menu| menu.select_last(self.project.as_ref(), cx))
7146 .unwrap_or(false)
7147 {
7148 return;
7149 }
7150
7151 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7152 cx.propagate();
7153 return;
7154 }
7155
7156 let Some(row_count) = self.visible_row_count() else {
7157 return;
7158 };
7159
7160 let autoscroll = if action.center_cursor {
7161 Autoscroll::center()
7162 } else {
7163 Autoscroll::fit()
7164 };
7165
7166 let text_layout_details = &self.text_layout_details(cx);
7167 self.change_selections(Some(autoscroll), cx, |s| {
7168 let line_mode = s.line_mode;
7169 s.move_with(|map, selection| {
7170 if !selection.is_empty() && !line_mode {
7171 selection.goal = SelectionGoal::None;
7172 }
7173 let (cursor, goal) = movement::down_by_rows(
7174 map,
7175 selection.end,
7176 row_count,
7177 selection.goal,
7178 false,
7179 &text_layout_details,
7180 );
7181 selection.collapse_to(cursor, goal);
7182 });
7183 });
7184 }
7185
7186 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7187 let text_layout_details = &self.text_layout_details(cx);
7188 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7189 s.move_heads_with(|map, head, goal| {
7190 movement::down(map, head, goal, false, &text_layout_details)
7191 })
7192 });
7193 }
7194
7195 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7196 if let Some(context_menu) = self.context_menu.write().as_mut() {
7197 context_menu.select_first(self.project.as_ref(), cx);
7198 }
7199 }
7200
7201 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7202 if let Some(context_menu) = self.context_menu.write().as_mut() {
7203 context_menu.select_prev(self.project.as_ref(), cx);
7204 }
7205 }
7206
7207 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7208 if let Some(context_menu) = self.context_menu.write().as_mut() {
7209 context_menu.select_next(self.project.as_ref(), cx);
7210 }
7211 }
7212
7213 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7214 if let Some(context_menu) = self.context_menu.write().as_mut() {
7215 context_menu.select_last(self.project.as_ref(), cx);
7216 }
7217 }
7218
7219 pub fn move_to_previous_word_start(
7220 &mut self,
7221 _: &MoveToPreviousWordStart,
7222 cx: &mut ViewContext<Self>,
7223 ) {
7224 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7225 s.move_cursors_with(|map, head, _| {
7226 (
7227 movement::previous_word_start(map, head),
7228 SelectionGoal::None,
7229 )
7230 });
7231 })
7232 }
7233
7234 pub fn move_to_previous_subword_start(
7235 &mut self,
7236 _: &MoveToPreviousSubwordStart,
7237 cx: &mut ViewContext<Self>,
7238 ) {
7239 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7240 s.move_cursors_with(|map, head, _| {
7241 (
7242 movement::previous_subword_start(map, head),
7243 SelectionGoal::None,
7244 )
7245 });
7246 })
7247 }
7248
7249 pub fn select_to_previous_word_start(
7250 &mut self,
7251 _: &SelectToPreviousWordStart,
7252 cx: &mut ViewContext<Self>,
7253 ) {
7254 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7255 s.move_heads_with(|map, head, _| {
7256 (
7257 movement::previous_word_start(map, head),
7258 SelectionGoal::None,
7259 )
7260 });
7261 })
7262 }
7263
7264 pub fn select_to_previous_subword_start(
7265 &mut self,
7266 _: &SelectToPreviousSubwordStart,
7267 cx: &mut ViewContext<Self>,
7268 ) {
7269 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7270 s.move_heads_with(|map, head, _| {
7271 (
7272 movement::previous_subword_start(map, head),
7273 SelectionGoal::None,
7274 )
7275 });
7276 })
7277 }
7278
7279 pub fn delete_to_previous_word_start(
7280 &mut self,
7281 _: &DeleteToPreviousWordStart,
7282 cx: &mut ViewContext<Self>,
7283 ) {
7284 self.transact(cx, |this, cx| {
7285 this.select_autoclose_pair(cx);
7286 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7287 let line_mode = s.line_mode;
7288 s.move_with(|map, selection| {
7289 if selection.is_empty() && !line_mode {
7290 let cursor = movement::previous_word_start(map, selection.head());
7291 selection.set_head(cursor, SelectionGoal::None);
7292 }
7293 });
7294 });
7295 this.insert("", cx);
7296 });
7297 }
7298
7299 pub fn delete_to_previous_subword_start(
7300 &mut self,
7301 _: &DeleteToPreviousSubwordStart,
7302 cx: &mut ViewContext<Self>,
7303 ) {
7304 self.transact(cx, |this, cx| {
7305 this.select_autoclose_pair(cx);
7306 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7307 let line_mode = s.line_mode;
7308 s.move_with(|map, selection| {
7309 if selection.is_empty() && !line_mode {
7310 let cursor = movement::previous_subword_start(map, selection.head());
7311 selection.set_head(cursor, SelectionGoal::None);
7312 }
7313 });
7314 });
7315 this.insert("", cx);
7316 });
7317 }
7318
7319 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7320 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7321 s.move_cursors_with(|map, head, _| {
7322 (movement::next_word_end(map, head), SelectionGoal::None)
7323 });
7324 })
7325 }
7326
7327 pub fn move_to_next_subword_end(
7328 &mut self,
7329 _: &MoveToNextSubwordEnd,
7330 cx: &mut ViewContext<Self>,
7331 ) {
7332 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7333 s.move_cursors_with(|map, head, _| {
7334 (movement::next_subword_end(map, head), SelectionGoal::None)
7335 });
7336 })
7337 }
7338
7339 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7340 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7341 s.move_heads_with(|map, head, _| {
7342 (movement::next_word_end(map, head), SelectionGoal::None)
7343 });
7344 })
7345 }
7346
7347 pub fn select_to_next_subword_end(
7348 &mut self,
7349 _: &SelectToNextSubwordEnd,
7350 cx: &mut ViewContext<Self>,
7351 ) {
7352 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7353 s.move_heads_with(|map, head, _| {
7354 (movement::next_subword_end(map, head), SelectionGoal::None)
7355 });
7356 })
7357 }
7358
7359 pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
7360 self.transact(cx, |this, cx| {
7361 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7362 let line_mode = s.line_mode;
7363 s.move_with(|map, selection| {
7364 if selection.is_empty() && !line_mode {
7365 let cursor = movement::next_word_end(map, selection.head());
7366 selection.set_head(cursor, SelectionGoal::None);
7367 }
7368 });
7369 });
7370 this.insert("", cx);
7371 });
7372 }
7373
7374 pub fn delete_to_next_subword_end(
7375 &mut self,
7376 _: &DeleteToNextSubwordEnd,
7377 cx: &mut ViewContext<Self>,
7378 ) {
7379 self.transact(cx, |this, cx| {
7380 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7381 s.move_with(|map, selection| {
7382 if selection.is_empty() {
7383 let cursor = movement::next_subword_end(map, selection.head());
7384 selection.set_head(cursor, SelectionGoal::None);
7385 }
7386 });
7387 });
7388 this.insert("", cx);
7389 });
7390 }
7391
7392 pub fn move_to_beginning_of_line(
7393 &mut self,
7394 action: &MoveToBeginningOfLine,
7395 cx: &mut ViewContext<Self>,
7396 ) {
7397 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7398 s.move_cursors_with(|map, head, _| {
7399 (
7400 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7401 SelectionGoal::None,
7402 )
7403 });
7404 })
7405 }
7406
7407 pub fn select_to_beginning_of_line(
7408 &mut self,
7409 action: &SelectToBeginningOfLine,
7410 cx: &mut ViewContext<Self>,
7411 ) {
7412 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7413 s.move_heads_with(|map, head, _| {
7414 (
7415 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7416 SelectionGoal::None,
7417 )
7418 });
7419 });
7420 }
7421
7422 pub fn delete_to_beginning_of_line(
7423 &mut self,
7424 _: &DeleteToBeginningOfLine,
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(|_, selection| {
7430 selection.reversed = true;
7431 });
7432 });
7433
7434 this.select_to_beginning_of_line(
7435 &SelectToBeginningOfLine {
7436 stop_at_soft_wraps: false,
7437 },
7438 cx,
7439 );
7440 this.backspace(&Backspace, cx);
7441 });
7442 }
7443
7444 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7445 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7446 s.move_cursors_with(|map, head, _| {
7447 (
7448 movement::line_end(map, head, action.stop_at_soft_wraps),
7449 SelectionGoal::None,
7450 )
7451 });
7452 })
7453 }
7454
7455 pub fn select_to_end_of_line(
7456 &mut self,
7457 action: &SelectToEndOfLine,
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::line_end(map, head, action.stop_at_soft_wraps),
7464 SelectionGoal::None,
7465 )
7466 });
7467 })
7468 }
7469
7470 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7471 self.transact(cx, |this, cx| {
7472 this.select_to_end_of_line(
7473 &SelectToEndOfLine {
7474 stop_at_soft_wraps: false,
7475 },
7476 cx,
7477 );
7478 this.delete(&Delete, cx);
7479 });
7480 }
7481
7482 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7483 self.transact(cx, |this, cx| {
7484 this.select_to_end_of_line(
7485 &SelectToEndOfLine {
7486 stop_at_soft_wraps: false,
7487 },
7488 cx,
7489 );
7490 this.cut(&Cut, cx);
7491 });
7492 }
7493
7494 pub fn move_to_start_of_paragraph(
7495 &mut self,
7496 _: &MoveToStartOfParagraph,
7497 cx: &mut ViewContext<Self>,
7498 ) {
7499 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7500 cx.propagate();
7501 return;
7502 }
7503
7504 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7505 s.move_with(|map, selection| {
7506 selection.collapse_to(
7507 movement::start_of_paragraph(map, selection.head(), 1),
7508 SelectionGoal::None,
7509 )
7510 });
7511 })
7512 }
7513
7514 pub fn move_to_end_of_paragraph(
7515 &mut self,
7516 _: &MoveToEndOfParagraph,
7517 cx: &mut ViewContext<Self>,
7518 ) {
7519 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7520 cx.propagate();
7521 return;
7522 }
7523
7524 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7525 s.move_with(|map, selection| {
7526 selection.collapse_to(
7527 movement::end_of_paragraph(map, selection.head(), 1),
7528 SelectionGoal::None,
7529 )
7530 });
7531 })
7532 }
7533
7534 pub fn select_to_start_of_paragraph(
7535 &mut self,
7536 _: &SelectToStartOfParagraph,
7537 cx: &mut ViewContext<Self>,
7538 ) {
7539 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7540 cx.propagate();
7541 return;
7542 }
7543
7544 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7545 s.move_heads_with(|map, head, _| {
7546 (
7547 movement::start_of_paragraph(map, head, 1),
7548 SelectionGoal::None,
7549 )
7550 });
7551 })
7552 }
7553
7554 pub fn select_to_end_of_paragraph(
7555 &mut self,
7556 _: &SelectToEndOfParagraph,
7557 cx: &mut ViewContext<Self>,
7558 ) {
7559 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7560 cx.propagate();
7561 return;
7562 }
7563
7564 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7565 s.move_heads_with(|map, head, _| {
7566 (
7567 movement::end_of_paragraph(map, head, 1),
7568 SelectionGoal::None,
7569 )
7570 });
7571 })
7572 }
7573
7574 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7575 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7576 cx.propagate();
7577 return;
7578 }
7579
7580 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7581 s.select_ranges(vec![0..0]);
7582 });
7583 }
7584
7585 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7586 let mut selection = self.selections.last::<Point>(cx);
7587 selection.set_head(Point::zero(), SelectionGoal::None);
7588
7589 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7590 s.select(vec![selection]);
7591 });
7592 }
7593
7594 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7595 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7596 cx.propagate();
7597 return;
7598 }
7599
7600 let cursor = self.buffer.read(cx).read(cx).len();
7601 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7602 s.select_ranges(vec![cursor..cursor])
7603 });
7604 }
7605
7606 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7607 self.nav_history = nav_history;
7608 }
7609
7610 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7611 self.nav_history.as_ref()
7612 }
7613
7614 fn push_to_nav_history(
7615 &mut self,
7616 cursor_anchor: Anchor,
7617 new_position: Option<Point>,
7618 cx: &mut ViewContext<Self>,
7619 ) {
7620 if let Some(nav_history) = self.nav_history.as_mut() {
7621 let buffer = self.buffer.read(cx).read(cx);
7622 let cursor_position = cursor_anchor.to_point(&buffer);
7623 let scroll_state = self.scroll_manager.anchor();
7624 let scroll_top_row = scroll_state.top_row(&buffer);
7625 drop(buffer);
7626
7627 if let Some(new_position) = new_position {
7628 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7629 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7630 return;
7631 }
7632 }
7633
7634 nav_history.push(
7635 Some(NavigationData {
7636 cursor_anchor,
7637 cursor_position,
7638 scroll_anchor: scroll_state,
7639 scroll_top_row,
7640 }),
7641 cx,
7642 );
7643 }
7644 }
7645
7646 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7647 let buffer = self.buffer.read(cx).snapshot(cx);
7648 let mut selection = self.selections.first::<usize>(cx);
7649 selection.set_head(buffer.len(), SelectionGoal::None);
7650 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7651 s.select(vec![selection]);
7652 });
7653 }
7654
7655 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7656 let end = self.buffer.read(cx).read(cx).len();
7657 self.change_selections(None, cx, |s| {
7658 s.select_ranges(vec![0..end]);
7659 });
7660 }
7661
7662 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7663 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7664 let mut selections = self.selections.all::<Point>(cx);
7665 let max_point = display_map.buffer_snapshot.max_point();
7666 for selection in &mut selections {
7667 let rows = selection.spanned_rows(true, &display_map);
7668 selection.start = Point::new(rows.start.0, 0);
7669 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7670 selection.reversed = false;
7671 }
7672 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7673 s.select(selections);
7674 });
7675 }
7676
7677 pub fn split_selection_into_lines(
7678 &mut self,
7679 _: &SplitSelectionIntoLines,
7680 cx: &mut ViewContext<Self>,
7681 ) {
7682 let mut to_unfold = Vec::new();
7683 let mut new_selection_ranges = Vec::new();
7684 {
7685 let selections = self.selections.all::<Point>(cx);
7686 let buffer = self.buffer.read(cx).read(cx);
7687 for selection in selections {
7688 for row in selection.start.row..selection.end.row {
7689 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7690 new_selection_ranges.push(cursor..cursor);
7691 }
7692 new_selection_ranges.push(selection.end..selection.end);
7693 to_unfold.push(selection.start..selection.end);
7694 }
7695 }
7696 self.unfold_ranges(to_unfold, true, true, cx);
7697 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7698 s.select_ranges(new_selection_ranges);
7699 });
7700 }
7701
7702 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7703 self.add_selection(true, cx);
7704 }
7705
7706 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7707 self.add_selection(false, cx);
7708 }
7709
7710 fn add_selection(&mut self, above: bool, 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 text_layout_details = self.text_layout_details(cx);
7714 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7715 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7716 let range = oldest_selection.display_range(&display_map).sorted();
7717
7718 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7719 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7720 let positions = start_x.min(end_x)..start_x.max(end_x);
7721
7722 selections.clear();
7723 let mut stack = Vec::new();
7724 for row in range.start.row().0..=range.end.row().0 {
7725 if let Some(selection) = self.selections.build_columnar_selection(
7726 &display_map,
7727 DisplayRow(row),
7728 &positions,
7729 oldest_selection.reversed,
7730 &text_layout_details,
7731 ) {
7732 stack.push(selection.id);
7733 selections.push(selection);
7734 }
7735 }
7736
7737 if above {
7738 stack.reverse();
7739 }
7740
7741 AddSelectionsState { above, stack }
7742 });
7743
7744 let last_added_selection = *state.stack.last().unwrap();
7745 let mut new_selections = Vec::new();
7746 if above == state.above {
7747 let end_row = if above {
7748 DisplayRow(0)
7749 } else {
7750 display_map.max_point().row()
7751 };
7752
7753 'outer: for selection in selections {
7754 if selection.id == last_added_selection {
7755 let range = selection.display_range(&display_map).sorted();
7756 debug_assert_eq!(range.start.row(), range.end.row());
7757 let mut row = range.start.row();
7758 let positions =
7759 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7760 px(start)..px(end)
7761 } else {
7762 let start_x =
7763 display_map.x_for_display_point(range.start, &text_layout_details);
7764 let end_x =
7765 display_map.x_for_display_point(range.end, &text_layout_details);
7766 start_x.min(end_x)..start_x.max(end_x)
7767 };
7768
7769 while row != end_row {
7770 if above {
7771 row.0 -= 1;
7772 } else {
7773 row.0 += 1;
7774 }
7775
7776 if let Some(new_selection) = self.selections.build_columnar_selection(
7777 &display_map,
7778 row,
7779 &positions,
7780 selection.reversed,
7781 &text_layout_details,
7782 ) {
7783 state.stack.push(new_selection.id);
7784 if above {
7785 new_selections.push(new_selection);
7786 new_selections.push(selection);
7787 } else {
7788 new_selections.push(selection);
7789 new_selections.push(new_selection);
7790 }
7791
7792 continue 'outer;
7793 }
7794 }
7795 }
7796
7797 new_selections.push(selection);
7798 }
7799 } else {
7800 new_selections = selections;
7801 new_selections.retain(|s| s.id != last_added_selection);
7802 state.stack.pop();
7803 }
7804
7805 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7806 s.select(new_selections);
7807 });
7808 if state.stack.len() > 1 {
7809 self.add_selections_state = Some(state);
7810 }
7811 }
7812
7813 pub fn select_next_match_internal(
7814 &mut self,
7815 display_map: &DisplaySnapshot,
7816 replace_newest: bool,
7817 autoscroll: Option<Autoscroll>,
7818 cx: &mut ViewContext<Self>,
7819 ) -> Result<()> {
7820 fn select_next_match_ranges(
7821 this: &mut Editor,
7822 range: Range<usize>,
7823 replace_newest: bool,
7824 auto_scroll: Option<Autoscroll>,
7825 cx: &mut ViewContext<Editor>,
7826 ) {
7827 this.unfold_ranges([range.clone()], false, true, cx);
7828 this.change_selections(auto_scroll, cx, |s| {
7829 if replace_newest {
7830 s.delete(s.newest_anchor().id);
7831 }
7832 s.insert_range(range.clone());
7833 });
7834 }
7835
7836 let buffer = &display_map.buffer_snapshot;
7837 let mut selections = self.selections.all::<usize>(cx);
7838 if let Some(mut select_next_state) = self.select_next_state.take() {
7839 let query = &select_next_state.query;
7840 if !select_next_state.done {
7841 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7842 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7843 let mut next_selected_range = None;
7844
7845 let bytes_after_last_selection =
7846 buffer.bytes_in_range(last_selection.end..buffer.len());
7847 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
7848 let query_matches = query
7849 .stream_find_iter(bytes_after_last_selection)
7850 .map(|result| (last_selection.end, result))
7851 .chain(
7852 query
7853 .stream_find_iter(bytes_before_first_selection)
7854 .map(|result| (0, result)),
7855 );
7856
7857 for (start_offset, query_match) in query_matches {
7858 let query_match = query_match.unwrap(); // can only fail due to I/O
7859 let offset_range =
7860 start_offset + query_match.start()..start_offset + query_match.end();
7861 let display_range = offset_range.start.to_display_point(&display_map)
7862 ..offset_range.end.to_display_point(&display_map);
7863
7864 if !select_next_state.wordwise
7865 || (!movement::is_inside_word(&display_map, display_range.start)
7866 && !movement::is_inside_word(&display_map, display_range.end))
7867 {
7868 // TODO: This is n^2, because we might check all the selections
7869 if !selections
7870 .iter()
7871 .any(|selection| selection.range().overlaps(&offset_range))
7872 {
7873 next_selected_range = Some(offset_range);
7874 break;
7875 }
7876 }
7877 }
7878
7879 if let Some(next_selected_range) = next_selected_range {
7880 select_next_match_ranges(
7881 self,
7882 next_selected_range,
7883 replace_newest,
7884 autoscroll,
7885 cx,
7886 );
7887 } else {
7888 select_next_state.done = true;
7889 }
7890 }
7891
7892 self.select_next_state = Some(select_next_state);
7893 } else {
7894 let mut only_carets = true;
7895 let mut same_text_selected = true;
7896 let mut selected_text = None;
7897
7898 let mut selections_iter = selections.iter().peekable();
7899 while let Some(selection) = selections_iter.next() {
7900 if selection.start != selection.end {
7901 only_carets = false;
7902 }
7903
7904 if same_text_selected {
7905 if selected_text.is_none() {
7906 selected_text =
7907 Some(buffer.text_for_range(selection.range()).collect::<String>());
7908 }
7909
7910 if let Some(next_selection) = selections_iter.peek() {
7911 if next_selection.range().len() == selection.range().len() {
7912 let next_selected_text = buffer
7913 .text_for_range(next_selection.range())
7914 .collect::<String>();
7915 if Some(next_selected_text) != selected_text {
7916 same_text_selected = false;
7917 selected_text = None;
7918 }
7919 } else {
7920 same_text_selected = false;
7921 selected_text = None;
7922 }
7923 }
7924 }
7925 }
7926
7927 if only_carets {
7928 for selection in &mut selections {
7929 let word_range = movement::surrounding_word(
7930 &display_map,
7931 selection.start.to_display_point(&display_map),
7932 );
7933 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
7934 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
7935 selection.goal = SelectionGoal::None;
7936 selection.reversed = false;
7937 select_next_match_ranges(
7938 self,
7939 selection.start..selection.end,
7940 replace_newest,
7941 autoscroll,
7942 cx,
7943 );
7944 }
7945
7946 if selections.len() == 1 {
7947 let selection = selections
7948 .last()
7949 .expect("ensured that there's only one selection");
7950 let query = buffer
7951 .text_for_range(selection.start..selection.end)
7952 .collect::<String>();
7953 let is_empty = query.is_empty();
7954 let select_state = SelectNextState {
7955 query: AhoCorasick::new(&[query])?,
7956 wordwise: true,
7957 done: is_empty,
7958 };
7959 self.select_next_state = Some(select_state);
7960 } else {
7961 self.select_next_state = None;
7962 }
7963 } else if let Some(selected_text) = selected_text {
7964 self.select_next_state = Some(SelectNextState {
7965 query: AhoCorasick::new(&[selected_text])?,
7966 wordwise: false,
7967 done: false,
7968 });
7969 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
7970 }
7971 }
7972 Ok(())
7973 }
7974
7975 pub fn select_all_matches(
7976 &mut self,
7977 _action: &SelectAllMatches,
7978 cx: &mut ViewContext<Self>,
7979 ) -> Result<()> {
7980 self.push_to_selection_history();
7981 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7982
7983 self.select_next_match_internal(&display_map, false, None, cx)?;
7984 let Some(select_next_state) = self.select_next_state.as_mut() else {
7985 return Ok(());
7986 };
7987 if select_next_state.done {
7988 return Ok(());
7989 }
7990
7991 let mut new_selections = self.selections.all::<usize>(cx);
7992
7993 let buffer = &display_map.buffer_snapshot;
7994 let query_matches = select_next_state
7995 .query
7996 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
7997
7998 for query_match in query_matches {
7999 let query_match = query_match.unwrap(); // can only fail due to I/O
8000 let offset_range = query_match.start()..query_match.end();
8001 let display_range = offset_range.start.to_display_point(&display_map)
8002 ..offset_range.end.to_display_point(&display_map);
8003
8004 if !select_next_state.wordwise
8005 || (!movement::is_inside_word(&display_map, display_range.start)
8006 && !movement::is_inside_word(&display_map, display_range.end))
8007 {
8008 self.selections.change_with(cx, |selections| {
8009 new_selections.push(Selection {
8010 id: selections.new_selection_id(),
8011 start: offset_range.start,
8012 end: offset_range.end,
8013 reversed: false,
8014 goal: SelectionGoal::None,
8015 });
8016 });
8017 }
8018 }
8019
8020 new_selections.sort_by_key(|selection| selection.start);
8021 let mut ix = 0;
8022 while ix + 1 < new_selections.len() {
8023 let current_selection = &new_selections[ix];
8024 let next_selection = &new_selections[ix + 1];
8025 if current_selection.range().overlaps(&next_selection.range()) {
8026 if current_selection.id < next_selection.id {
8027 new_selections.remove(ix + 1);
8028 } else {
8029 new_selections.remove(ix);
8030 }
8031 } else {
8032 ix += 1;
8033 }
8034 }
8035
8036 select_next_state.done = true;
8037 self.unfold_ranges(
8038 new_selections.iter().map(|selection| selection.range()),
8039 false,
8040 false,
8041 cx,
8042 );
8043 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8044 selections.select(new_selections)
8045 });
8046
8047 Ok(())
8048 }
8049
8050 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8051 self.push_to_selection_history();
8052 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8053 self.select_next_match_internal(
8054 &display_map,
8055 action.replace_newest,
8056 Some(Autoscroll::newest()),
8057 cx,
8058 )?;
8059 Ok(())
8060 }
8061
8062 pub fn select_previous(
8063 &mut self,
8064 action: &SelectPrevious,
8065 cx: &mut ViewContext<Self>,
8066 ) -> Result<()> {
8067 self.push_to_selection_history();
8068 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8069 let buffer = &display_map.buffer_snapshot;
8070 let mut selections = self.selections.all::<usize>(cx);
8071 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8072 let query = &select_prev_state.query;
8073 if !select_prev_state.done {
8074 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8075 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8076 let mut next_selected_range = None;
8077 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8078 let bytes_before_last_selection =
8079 buffer.reversed_bytes_in_range(0..last_selection.start);
8080 let bytes_after_first_selection =
8081 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8082 let query_matches = query
8083 .stream_find_iter(bytes_before_last_selection)
8084 .map(|result| (last_selection.start, result))
8085 .chain(
8086 query
8087 .stream_find_iter(bytes_after_first_selection)
8088 .map(|result| (buffer.len(), result)),
8089 );
8090 for (end_offset, query_match) in query_matches {
8091 let query_match = query_match.unwrap(); // can only fail due to I/O
8092 let offset_range =
8093 end_offset - query_match.end()..end_offset - query_match.start();
8094 let display_range = offset_range.start.to_display_point(&display_map)
8095 ..offset_range.end.to_display_point(&display_map);
8096
8097 if !select_prev_state.wordwise
8098 || (!movement::is_inside_word(&display_map, display_range.start)
8099 && !movement::is_inside_word(&display_map, display_range.end))
8100 {
8101 next_selected_range = Some(offset_range);
8102 break;
8103 }
8104 }
8105
8106 if let Some(next_selected_range) = next_selected_range {
8107 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8108 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8109 if action.replace_newest {
8110 s.delete(s.newest_anchor().id);
8111 }
8112 s.insert_range(next_selected_range);
8113 });
8114 } else {
8115 select_prev_state.done = true;
8116 }
8117 }
8118
8119 self.select_prev_state = Some(select_prev_state);
8120 } else {
8121 let mut only_carets = true;
8122 let mut same_text_selected = true;
8123 let mut selected_text = None;
8124
8125 let mut selections_iter = selections.iter().peekable();
8126 while let Some(selection) = selections_iter.next() {
8127 if selection.start != selection.end {
8128 only_carets = false;
8129 }
8130
8131 if same_text_selected {
8132 if selected_text.is_none() {
8133 selected_text =
8134 Some(buffer.text_for_range(selection.range()).collect::<String>());
8135 }
8136
8137 if let Some(next_selection) = selections_iter.peek() {
8138 if next_selection.range().len() == selection.range().len() {
8139 let next_selected_text = buffer
8140 .text_for_range(next_selection.range())
8141 .collect::<String>();
8142 if Some(next_selected_text) != selected_text {
8143 same_text_selected = false;
8144 selected_text = None;
8145 }
8146 } else {
8147 same_text_selected = false;
8148 selected_text = None;
8149 }
8150 }
8151 }
8152 }
8153
8154 if only_carets {
8155 for selection in &mut selections {
8156 let word_range = movement::surrounding_word(
8157 &display_map,
8158 selection.start.to_display_point(&display_map),
8159 );
8160 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8161 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8162 selection.goal = SelectionGoal::None;
8163 selection.reversed = false;
8164 }
8165 if selections.len() == 1 {
8166 let selection = selections
8167 .last()
8168 .expect("ensured that there's only one selection");
8169 let query = buffer
8170 .text_for_range(selection.start..selection.end)
8171 .collect::<String>();
8172 let is_empty = query.is_empty();
8173 let select_state = SelectNextState {
8174 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8175 wordwise: true,
8176 done: is_empty,
8177 };
8178 self.select_prev_state = Some(select_state);
8179 } else {
8180 self.select_prev_state = None;
8181 }
8182
8183 self.unfold_ranges(
8184 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8185 false,
8186 true,
8187 cx,
8188 );
8189 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8190 s.select(selections);
8191 });
8192 } else if let Some(selected_text) = selected_text {
8193 self.select_prev_state = Some(SelectNextState {
8194 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8195 wordwise: false,
8196 done: false,
8197 });
8198 self.select_previous(action, cx)?;
8199 }
8200 }
8201 Ok(())
8202 }
8203
8204 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8205 let text_layout_details = &self.text_layout_details(cx);
8206 self.transact(cx, |this, cx| {
8207 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8208 let mut edits = Vec::new();
8209 let mut selection_edit_ranges = Vec::new();
8210 let mut last_toggled_row = None;
8211 let snapshot = this.buffer.read(cx).read(cx);
8212 let empty_str: Arc<str> = Arc::default();
8213 let mut suffixes_inserted = Vec::new();
8214
8215 fn comment_prefix_range(
8216 snapshot: &MultiBufferSnapshot,
8217 row: MultiBufferRow,
8218 comment_prefix: &str,
8219 comment_prefix_whitespace: &str,
8220 ) -> Range<Point> {
8221 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8222
8223 let mut line_bytes = snapshot
8224 .bytes_in_range(start..snapshot.max_point())
8225 .flatten()
8226 .copied();
8227
8228 // If this line currently begins with the line comment prefix, then record
8229 // the range containing the prefix.
8230 if line_bytes
8231 .by_ref()
8232 .take(comment_prefix.len())
8233 .eq(comment_prefix.bytes())
8234 {
8235 // Include any whitespace that matches the comment prefix.
8236 let matching_whitespace_len = line_bytes
8237 .zip(comment_prefix_whitespace.bytes())
8238 .take_while(|(a, b)| a == b)
8239 .count() as u32;
8240 let end = Point::new(
8241 start.row,
8242 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8243 );
8244 start..end
8245 } else {
8246 start..start
8247 }
8248 }
8249
8250 fn comment_suffix_range(
8251 snapshot: &MultiBufferSnapshot,
8252 row: MultiBufferRow,
8253 comment_suffix: &str,
8254 comment_suffix_has_leading_space: bool,
8255 ) -> Range<Point> {
8256 let end = Point::new(row.0, snapshot.line_len(row));
8257 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8258
8259 let mut line_end_bytes = snapshot
8260 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8261 .flatten()
8262 .copied();
8263
8264 let leading_space_len = if suffix_start_column > 0
8265 && line_end_bytes.next() == Some(b' ')
8266 && comment_suffix_has_leading_space
8267 {
8268 1
8269 } else {
8270 0
8271 };
8272
8273 // If this line currently begins with the line comment prefix, then record
8274 // the range containing the prefix.
8275 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8276 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8277 start..end
8278 } else {
8279 end..end
8280 }
8281 }
8282
8283 // TODO: Handle selections that cross excerpts
8284 for selection in &mut selections {
8285 let start_column = snapshot
8286 .indent_size_for_line(MultiBufferRow(selection.start.row))
8287 .len;
8288 let language = if let Some(language) =
8289 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8290 {
8291 language
8292 } else {
8293 continue;
8294 };
8295
8296 selection_edit_ranges.clear();
8297
8298 // If multiple selections contain a given row, avoid processing that
8299 // row more than once.
8300 let mut start_row = MultiBufferRow(selection.start.row);
8301 if last_toggled_row == Some(start_row) {
8302 start_row = start_row.next_row();
8303 }
8304 let end_row =
8305 if selection.end.row > selection.start.row && selection.end.column == 0 {
8306 MultiBufferRow(selection.end.row - 1)
8307 } else {
8308 MultiBufferRow(selection.end.row)
8309 };
8310 last_toggled_row = Some(end_row);
8311
8312 if start_row > end_row {
8313 continue;
8314 }
8315
8316 // If the language has line comments, toggle those.
8317 let full_comment_prefixes = language.line_comment_prefixes();
8318 if !full_comment_prefixes.is_empty() {
8319 let first_prefix = full_comment_prefixes
8320 .first()
8321 .expect("prefixes is non-empty");
8322 let prefix_trimmed_lengths = full_comment_prefixes
8323 .iter()
8324 .map(|p| p.trim_end_matches(' ').len())
8325 .collect::<SmallVec<[usize; 4]>>();
8326
8327 let mut all_selection_lines_are_comments = true;
8328
8329 for row in start_row.0..=end_row.0 {
8330 let row = MultiBufferRow(row);
8331 if start_row < end_row && snapshot.is_line_blank(row) {
8332 continue;
8333 }
8334
8335 let prefix_range = full_comment_prefixes
8336 .iter()
8337 .zip(prefix_trimmed_lengths.iter().copied())
8338 .map(|(prefix, trimmed_prefix_len)| {
8339 comment_prefix_range(
8340 snapshot.deref(),
8341 row,
8342 &prefix[..trimmed_prefix_len],
8343 &prefix[trimmed_prefix_len..],
8344 )
8345 })
8346 .max_by_key(|range| range.end.column - range.start.column)
8347 .expect("prefixes is non-empty");
8348
8349 if prefix_range.is_empty() {
8350 all_selection_lines_are_comments = false;
8351 }
8352
8353 selection_edit_ranges.push(prefix_range);
8354 }
8355
8356 if all_selection_lines_are_comments {
8357 edits.extend(
8358 selection_edit_ranges
8359 .iter()
8360 .cloned()
8361 .map(|range| (range, empty_str.clone())),
8362 );
8363 } else {
8364 let min_column = selection_edit_ranges
8365 .iter()
8366 .map(|range| range.start.column)
8367 .min()
8368 .unwrap_or(0);
8369 edits.extend(selection_edit_ranges.iter().map(|range| {
8370 let position = Point::new(range.start.row, min_column);
8371 (position..position, first_prefix.clone())
8372 }));
8373 }
8374 } else if let Some((full_comment_prefix, comment_suffix)) =
8375 language.block_comment_delimiters()
8376 {
8377 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8378 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8379 let prefix_range = comment_prefix_range(
8380 snapshot.deref(),
8381 start_row,
8382 comment_prefix,
8383 comment_prefix_whitespace,
8384 );
8385 let suffix_range = comment_suffix_range(
8386 snapshot.deref(),
8387 end_row,
8388 comment_suffix.trim_start_matches(' '),
8389 comment_suffix.starts_with(' '),
8390 );
8391
8392 if prefix_range.is_empty() || suffix_range.is_empty() {
8393 edits.push((
8394 prefix_range.start..prefix_range.start,
8395 full_comment_prefix.clone(),
8396 ));
8397 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8398 suffixes_inserted.push((end_row, comment_suffix.len()));
8399 } else {
8400 edits.push((prefix_range, empty_str.clone()));
8401 edits.push((suffix_range, empty_str.clone()));
8402 }
8403 } else {
8404 continue;
8405 }
8406 }
8407
8408 drop(snapshot);
8409 this.buffer.update(cx, |buffer, cx| {
8410 buffer.edit(edits, None, cx);
8411 });
8412
8413 // Adjust selections so that they end before any comment suffixes that
8414 // were inserted.
8415 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8416 let mut selections = this.selections.all::<Point>(cx);
8417 let snapshot = this.buffer.read(cx).read(cx);
8418 for selection in &mut selections {
8419 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8420 match row.cmp(&MultiBufferRow(selection.end.row)) {
8421 Ordering::Less => {
8422 suffixes_inserted.next();
8423 continue;
8424 }
8425 Ordering::Greater => break,
8426 Ordering::Equal => {
8427 if selection.end.column == snapshot.line_len(row) {
8428 if selection.is_empty() {
8429 selection.start.column -= suffix_len as u32;
8430 }
8431 selection.end.column -= suffix_len as u32;
8432 }
8433 break;
8434 }
8435 }
8436 }
8437 }
8438
8439 drop(snapshot);
8440 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8441
8442 let selections = this.selections.all::<Point>(cx);
8443 let selections_on_single_row = selections.windows(2).all(|selections| {
8444 selections[0].start.row == selections[1].start.row
8445 && selections[0].end.row == selections[1].end.row
8446 && selections[0].start.row == selections[0].end.row
8447 });
8448 let selections_selecting = selections
8449 .iter()
8450 .any(|selection| selection.start != selection.end);
8451 let advance_downwards = action.advance_downwards
8452 && selections_on_single_row
8453 && !selections_selecting
8454 && !matches!(this.mode, EditorMode::SingleLine { .. });
8455
8456 if advance_downwards {
8457 let snapshot = this.buffer.read(cx).snapshot(cx);
8458
8459 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8460 s.move_cursors_with(|display_snapshot, display_point, _| {
8461 let mut point = display_point.to_point(display_snapshot);
8462 point.row += 1;
8463 point = snapshot.clip_point(point, Bias::Left);
8464 let display_point = point.to_display_point(display_snapshot);
8465 let goal = SelectionGoal::HorizontalPosition(
8466 display_snapshot
8467 .x_for_display_point(display_point, &text_layout_details)
8468 .into(),
8469 );
8470 (display_point, goal)
8471 })
8472 });
8473 }
8474 });
8475 }
8476
8477 pub fn select_enclosing_symbol(
8478 &mut self,
8479 _: &SelectEnclosingSymbol,
8480 cx: &mut ViewContext<Self>,
8481 ) {
8482 let buffer = self.buffer.read(cx).snapshot(cx);
8483 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8484
8485 fn update_selection(
8486 selection: &Selection<usize>,
8487 buffer_snap: &MultiBufferSnapshot,
8488 ) -> Option<Selection<usize>> {
8489 let cursor = selection.head();
8490 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8491 for symbol in symbols.iter().rev() {
8492 let start = symbol.range.start.to_offset(&buffer_snap);
8493 let end = symbol.range.end.to_offset(&buffer_snap);
8494 let new_range = start..end;
8495 if start < selection.start || end > selection.end {
8496 return Some(Selection {
8497 id: selection.id,
8498 start: new_range.start,
8499 end: new_range.end,
8500 goal: SelectionGoal::None,
8501 reversed: selection.reversed,
8502 });
8503 }
8504 }
8505 None
8506 }
8507
8508 let mut selected_larger_symbol = false;
8509 let new_selections = old_selections
8510 .iter()
8511 .map(|selection| match update_selection(selection, &buffer) {
8512 Some(new_selection) => {
8513 if new_selection.range() != selection.range() {
8514 selected_larger_symbol = true;
8515 }
8516 new_selection
8517 }
8518 None => selection.clone(),
8519 })
8520 .collect::<Vec<_>>();
8521
8522 if selected_larger_symbol {
8523 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8524 s.select(new_selections);
8525 });
8526 }
8527 }
8528
8529 pub fn select_larger_syntax_node(
8530 &mut self,
8531 _: &SelectLargerSyntaxNode,
8532 cx: &mut ViewContext<Self>,
8533 ) {
8534 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8535 let buffer = self.buffer.read(cx).snapshot(cx);
8536 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8537
8538 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8539 let mut selected_larger_node = false;
8540 let new_selections = old_selections
8541 .iter()
8542 .map(|selection| {
8543 let old_range = selection.start..selection.end;
8544 let mut new_range = old_range.clone();
8545 while let Some(containing_range) =
8546 buffer.range_for_syntax_ancestor(new_range.clone())
8547 {
8548 new_range = containing_range;
8549 if !display_map.intersects_fold(new_range.start)
8550 && !display_map.intersects_fold(new_range.end)
8551 {
8552 break;
8553 }
8554 }
8555
8556 selected_larger_node |= new_range != old_range;
8557 Selection {
8558 id: selection.id,
8559 start: new_range.start,
8560 end: new_range.end,
8561 goal: SelectionGoal::None,
8562 reversed: selection.reversed,
8563 }
8564 })
8565 .collect::<Vec<_>>();
8566
8567 if selected_larger_node {
8568 stack.push(old_selections);
8569 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8570 s.select(new_selections);
8571 });
8572 }
8573 self.select_larger_syntax_node_stack = stack;
8574 }
8575
8576 pub fn select_smaller_syntax_node(
8577 &mut self,
8578 _: &SelectSmallerSyntaxNode,
8579 cx: &mut ViewContext<Self>,
8580 ) {
8581 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8582 if let Some(selections) = stack.pop() {
8583 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8584 s.select(selections.to_vec());
8585 });
8586 }
8587 self.select_larger_syntax_node_stack = stack;
8588 }
8589
8590 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8591 if !EditorSettings::get_global(cx).gutter.runnables {
8592 self.clear_tasks();
8593 return Task::ready(());
8594 }
8595 let project = self.project.clone();
8596 cx.spawn(|this, mut cx| async move {
8597 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8598 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8599 }) else {
8600 return;
8601 };
8602
8603 let Some(project) = project else {
8604 return;
8605 };
8606
8607 let hide_runnables = project
8608 .update(&mut cx, |project, cx| {
8609 // Do not display any test indicators in non-dev server remote projects.
8610 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8611 })
8612 .unwrap_or(true);
8613 if hide_runnables {
8614 return;
8615 }
8616 let new_rows =
8617 cx.background_executor()
8618 .spawn({
8619 let snapshot = display_snapshot.clone();
8620 async move {
8621 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8622 }
8623 })
8624 .await;
8625 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8626
8627 this.update(&mut cx, |this, _| {
8628 this.clear_tasks();
8629 for (key, value) in rows {
8630 this.insert_tasks(key, value);
8631 }
8632 })
8633 .ok();
8634 })
8635 }
8636 fn fetch_runnable_ranges(
8637 snapshot: &DisplaySnapshot,
8638 range: Range<Anchor>,
8639 ) -> Vec<language::RunnableRange> {
8640 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8641 }
8642
8643 fn runnable_rows(
8644 project: Model<Project>,
8645 snapshot: DisplaySnapshot,
8646 runnable_ranges: Vec<RunnableRange>,
8647 mut cx: AsyncWindowContext,
8648 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8649 runnable_ranges
8650 .into_iter()
8651 .filter_map(|mut runnable| {
8652 let tasks = cx
8653 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8654 .ok()?;
8655 if tasks.is_empty() {
8656 return None;
8657 }
8658
8659 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8660
8661 let row = snapshot
8662 .buffer_snapshot
8663 .buffer_line_for_row(MultiBufferRow(point.row))?
8664 .1
8665 .start
8666 .row;
8667
8668 let context_range =
8669 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8670 Some((
8671 (runnable.buffer_id, row),
8672 RunnableTasks {
8673 templates: tasks,
8674 offset: MultiBufferOffset(runnable.run_range.start),
8675 context_range,
8676 column: point.column,
8677 extra_variables: runnable.extra_captures,
8678 },
8679 ))
8680 })
8681 .collect()
8682 }
8683
8684 fn templates_with_tags(
8685 project: &Model<Project>,
8686 runnable: &mut Runnable,
8687 cx: &WindowContext<'_>,
8688 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8689 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8690 let (worktree_id, file) = project
8691 .buffer_for_id(runnable.buffer, cx)
8692 .and_then(|buffer| buffer.read(cx).file())
8693 .map(|file| (WorktreeId::from_usize(file.worktree_id()), file.clone()))
8694 .unzip();
8695
8696 (project.task_inventory().clone(), worktree_id, file)
8697 });
8698
8699 let inventory = inventory.read(cx);
8700 let tags = mem::take(&mut runnable.tags);
8701 let mut tags: Vec<_> = tags
8702 .into_iter()
8703 .flat_map(|tag| {
8704 let tag = tag.0.clone();
8705 inventory
8706 .list_tasks(
8707 file.clone(),
8708 Some(runnable.language.clone()),
8709 worktree_id,
8710 cx,
8711 )
8712 .into_iter()
8713 .filter(move |(_, template)| {
8714 template.tags.iter().any(|source_tag| source_tag == &tag)
8715 })
8716 })
8717 .sorted_by_key(|(kind, _)| kind.to_owned())
8718 .collect();
8719 if let Some((leading_tag_source, _)) = tags.first() {
8720 // Strongest source wins; if we have worktree tag binding, prefer that to
8721 // global and language bindings;
8722 // if we have a global binding, prefer that to language binding.
8723 let first_mismatch = tags
8724 .iter()
8725 .position(|(tag_source, _)| tag_source != leading_tag_source);
8726 if let Some(index) = first_mismatch {
8727 tags.truncate(index);
8728 }
8729 }
8730
8731 tags
8732 }
8733
8734 pub fn move_to_enclosing_bracket(
8735 &mut self,
8736 _: &MoveToEnclosingBracket,
8737 cx: &mut ViewContext<Self>,
8738 ) {
8739 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8740 s.move_offsets_with(|snapshot, selection| {
8741 let Some(enclosing_bracket_ranges) =
8742 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
8743 else {
8744 return;
8745 };
8746
8747 let mut best_length = usize::MAX;
8748 let mut best_inside = false;
8749 let mut best_in_bracket_range = false;
8750 let mut best_destination = None;
8751 for (open, close) in enclosing_bracket_ranges {
8752 let close = close.to_inclusive();
8753 let length = close.end() - open.start;
8754 let inside = selection.start >= open.end && selection.end <= *close.start();
8755 let in_bracket_range = open.to_inclusive().contains(&selection.head())
8756 || close.contains(&selection.head());
8757
8758 // If best is next to a bracket and current isn't, skip
8759 if !in_bracket_range && best_in_bracket_range {
8760 continue;
8761 }
8762
8763 // Prefer smaller lengths unless best is inside and current isn't
8764 if length > best_length && (best_inside || !inside) {
8765 continue;
8766 }
8767
8768 best_length = length;
8769 best_inside = inside;
8770 best_in_bracket_range = in_bracket_range;
8771 best_destination = Some(
8772 if close.contains(&selection.start) && close.contains(&selection.end) {
8773 if inside {
8774 open.end
8775 } else {
8776 open.start
8777 }
8778 } else {
8779 if inside {
8780 *close.start()
8781 } else {
8782 *close.end()
8783 }
8784 },
8785 );
8786 }
8787
8788 if let Some(destination) = best_destination {
8789 selection.collapse_to(destination, SelectionGoal::None);
8790 }
8791 })
8792 });
8793 }
8794
8795 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
8796 self.end_selection(cx);
8797 self.selection_history.mode = SelectionHistoryMode::Undoing;
8798 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
8799 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8800 self.select_next_state = entry.select_next_state;
8801 self.select_prev_state = entry.select_prev_state;
8802 self.add_selections_state = entry.add_selections_state;
8803 self.request_autoscroll(Autoscroll::newest(), cx);
8804 }
8805 self.selection_history.mode = SelectionHistoryMode::Normal;
8806 }
8807
8808 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
8809 self.end_selection(cx);
8810 self.selection_history.mode = SelectionHistoryMode::Redoing;
8811 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
8812 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8813 self.select_next_state = entry.select_next_state;
8814 self.select_prev_state = entry.select_prev_state;
8815 self.add_selections_state = entry.add_selections_state;
8816 self.request_autoscroll(Autoscroll::newest(), cx);
8817 }
8818 self.selection_history.mode = SelectionHistoryMode::Normal;
8819 }
8820
8821 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
8822 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
8823 }
8824
8825 pub fn expand_excerpts_down(
8826 &mut self,
8827 action: &ExpandExcerptsDown,
8828 cx: &mut ViewContext<Self>,
8829 ) {
8830 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
8831 }
8832
8833 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
8834 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
8835 }
8836
8837 pub fn expand_excerpts_for_direction(
8838 &mut self,
8839 lines: u32,
8840 direction: ExpandExcerptDirection,
8841 cx: &mut ViewContext<Self>,
8842 ) {
8843 let selections = self.selections.disjoint_anchors();
8844
8845 let lines = if lines == 0 {
8846 EditorSettings::get_global(cx).expand_excerpt_lines
8847 } else {
8848 lines
8849 };
8850
8851 self.buffer.update(cx, |buffer, cx| {
8852 buffer.expand_excerpts(
8853 selections
8854 .into_iter()
8855 .map(|selection| selection.head().excerpt_id)
8856 .dedup(),
8857 lines,
8858 direction,
8859 cx,
8860 )
8861 })
8862 }
8863
8864 pub fn expand_excerpt(
8865 &mut self,
8866 excerpt: ExcerptId,
8867 direction: ExpandExcerptDirection,
8868 cx: &mut ViewContext<Self>,
8869 ) {
8870 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
8871 self.buffer.update(cx, |buffer, cx| {
8872 buffer.expand_excerpts([excerpt], lines, direction, cx)
8873 })
8874 }
8875
8876 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
8877 self.go_to_diagnostic_impl(Direction::Next, cx)
8878 }
8879
8880 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
8881 self.go_to_diagnostic_impl(Direction::Prev, cx)
8882 }
8883
8884 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
8885 let buffer = self.buffer.read(cx).snapshot(cx);
8886 let selection = self.selections.newest::<usize>(cx);
8887
8888 // If there is an active Diagnostic Popover jump to its diagnostic instead.
8889 if direction == Direction::Next {
8890 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
8891 let (group_id, jump_to) = popover.activation_info();
8892 if self.activate_diagnostics(group_id, cx) {
8893 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8894 let mut new_selection = s.newest_anchor().clone();
8895 new_selection.collapse_to(jump_to, SelectionGoal::None);
8896 s.select_anchors(vec![new_selection.clone()]);
8897 });
8898 }
8899 return;
8900 }
8901 }
8902
8903 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
8904 active_diagnostics
8905 .primary_range
8906 .to_offset(&buffer)
8907 .to_inclusive()
8908 });
8909 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
8910 if active_primary_range.contains(&selection.head()) {
8911 *active_primary_range.start()
8912 } else {
8913 selection.head()
8914 }
8915 } else {
8916 selection.head()
8917 };
8918 let snapshot = self.snapshot(cx);
8919 loop {
8920 let diagnostics = if direction == Direction::Prev {
8921 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
8922 } else {
8923 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
8924 }
8925 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
8926 let group = diagnostics
8927 // relies on diagnostics_in_range to return diagnostics with the same starting range to
8928 // be sorted in a stable way
8929 // skip until we are at current active diagnostic, if it exists
8930 .skip_while(|entry| {
8931 (match direction {
8932 Direction::Prev => entry.range.start >= search_start,
8933 Direction::Next => entry.range.start <= search_start,
8934 }) && self
8935 .active_diagnostics
8936 .as_ref()
8937 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
8938 })
8939 .find_map(|entry| {
8940 if entry.diagnostic.is_primary
8941 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
8942 && !entry.range.is_empty()
8943 // if we match with the active diagnostic, skip it
8944 && Some(entry.diagnostic.group_id)
8945 != self.active_diagnostics.as_ref().map(|d| d.group_id)
8946 {
8947 Some((entry.range, entry.diagnostic.group_id))
8948 } else {
8949 None
8950 }
8951 });
8952
8953 if let Some((primary_range, group_id)) = group {
8954 if self.activate_diagnostics(group_id, cx) {
8955 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8956 s.select(vec![Selection {
8957 id: selection.id,
8958 start: primary_range.start,
8959 end: primary_range.start,
8960 reversed: false,
8961 goal: SelectionGoal::None,
8962 }]);
8963 });
8964 }
8965 break;
8966 } else {
8967 // Cycle around to the start of the buffer, potentially moving back to the start of
8968 // the currently active diagnostic.
8969 active_primary_range.take();
8970 if direction == Direction::Prev {
8971 if search_start == buffer.len() {
8972 break;
8973 } else {
8974 search_start = buffer.len();
8975 }
8976 } else if search_start == 0 {
8977 break;
8978 } else {
8979 search_start = 0;
8980 }
8981 }
8982 }
8983 }
8984
8985 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
8986 let snapshot = self
8987 .display_map
8988 .update(cx, |display_map, cx| display_map.snapshot(cx));
8989 let selection = self.selections.newest::<Point>(cx);
8990
8991 if !self.seek_in_direction(
8992 &snapshot,
8993 selection.head(),
8994 false,
8995 snapshot.buffer_snapshot.git_diff_hunks_in_range(
8996 MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
8997 ),
8998 cx,
8999 ) {
9000 let wrapped_point = Point::zero();
9001 self.seek_in_direction(
9002 &snapshot,
9003 wrapped_point,
9004 true,
9005 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9006 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9007 ),
9008 cx,
9009 );
9010 }
9011 }
9012
9013 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9014 let snapshot = self
9015 .display_map
9016 .update(cx, |display_map, cx| display_map.snapshot(cx));
9017 let selection = self.selections.newest::<Point>(cx);
9018
9019 if !self.seek_in_direction(
9020 &snapshot,
9021 selection.head(),
9022 false,
9023 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9024 MultiBufferRow(0)..MultiBufferRow(selection.head().row),
9025 ),
9026 cx,
9027 ) {
9028 let wrapped_point = snapshot.buffer_snapshot.max_point();
9029 self.seek_in_direction(
9030 &snapshot,
9031 wrapped_point,
9032 true,
9033 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9034 MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
9035 ),
9036 cx,
9037 );
9038 }
9039 }
9040
9041 fn seek_in_direction(
9042 &mut self,
9043 snapshot: &DisplaySnapshot,
9044 initial_point: Point,
9045 is_wrapped: bool,
9046 hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
9047 cx: &mut ViewContext<Editor>,
9048 ) -> bool {
9049 let display_point = initial_point.to_display_point(snapshot);
9050 let mut hunks = hunks
9051 .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
9052 .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
9053 .dedup();
9054
9055 if let Some(hunk) = hunks.next() {
9056 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9057 let row = hunk.start_display_row();
9058 let point = DisplayPoint::new(row, 0);
9059 s.select_display_ranges([point..point]);
9060 });
9061
9062 true
9063 } else {
9064 false
9065 }
9066 }
9067
9068 pub fn go_to_definition(
9069 &mut self,
9070 _: &GoToDefinition,
9071 cx: &mut ViewContext<Self>,
9072 ) -> Task<Result<Navigated>> {
9073 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9074 let references = self.find_all_references(&FindAllReferences, cx);
9075 cx.background_executor().spawn(async move {
9076 if definition.await? == Navigated::Yes {
9077 return Ok(Navigated::Yes);
9078 }
9079 if let Some(references) = references {
9080 if references.await? == Navigated::Yes {
9081 return Ok(Navigated::Yes);
9082 }
9083 }
9084
9085 Ok(Navigated::No)
9086 })
9087 }
9088
9089 pub fn go_to_declaration(
9090 &mut self,
9091 _: &GoToDeclaration,
9092 cx: &mut ViewContext<Self>,
9093 ) -> Task<Result<Navigated>> {
9094 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9095 }
9096
9097 pub fn go_to_declaration_split(
9098 &mut self,
9099 _: &GoToDeclaration,
9100 cx: &mut ViewContext<Self>,
9101 ) -> Task<Result<Navigated>> {
9102 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9103 }
9104
9105 pub fn go_to_implementation(
9106 &mut self,
9107 _: &GoToImplementation,
9108 cx: &mut ViewContext<Self>,
9109 ) -> Task<Result<Navigated>> {
9110 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9111 }
9112
9113 pub fn go_to_implementation_split(
9114 &mut self,
9115 _: &GoToImplementationSplit,
9116 cx: &mut ViewContext<Self>,
9117 ) -> Task<Result<Navigated>> {
9118 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9119 }
9120
9121 pub fn go_to_type_definition(
9122 &mut self,
9123 _: &GoToTypeDefinition,
9124 cx: &mut ViewContext<Self>,
9125 ) -> Task<Result<Navigated>> {
9126 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9127 }
9128
9129 pub fn go_to_definition_split(
9130 &mut self,
9131 _: &GoToDefinitionSplit,
9132 cx: &mut ViewContext<Self>,
9133 ) -> Task<Result<Navigated>> {
9134 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9135 }
9136
9137 pub fn go_to_type_definition_split(
9138 &mut self,
9139 _: &GoToTypeDefinitionSplit,
9140 cx: &mut ViewContext<Self>,
9141 ) -> Task<Result<Navigated>> {
9142 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9143 }
9144
9145 fn go_to_definition_of_kind(
9146 &mut self,
9147 kind: GotoDefinitionKind,
9148 split: bool,
9149 cx: &mut ViewContext<Self>,
9150 ) -> Task<Result<Navigated>> {
9151 let Some(workspace) = self.workspace() else {
9152 return Task::ready(Ok(Navigated::No));
9153 };
9154 let buffer = self.buffer.read(cx);
9155 let head = self.selections.newest::<usize>(cx).head();
9156 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9157 text_anchor
9158 } else {
9159 return Task::ready(Ok(Navigated::No));
9160 };
9161
9162 let project = workspace.read(cx).project().clone();
9163 let definitions = project.update(cx, |project, cx| match kind {
9164 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
9165 GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
9166 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
9167 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
9168 });
9169
9170 cx.spawn(|editor, mut cx| async move {
9171 let definitions = definitions.await?;
9172 let navigated = editor
9173 .update(&mut cx, |editor, cx| {
9174 editor.navigate_to_hover_links(
9175 Some(kind),
9176 definitions
9177 .into_iter()
9178 .filter(|location| {
9179 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9180 })
9181 .map(HoverLink::Text)
9182 .collect::<Vec<_>>(),
9183 split,
9184 cx,
9185 )
9186 })?
9187 .await?;
9188 anyhow::Ok(navigated)
9189 })
9190 }
9191
9192 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9193 let position = self.selections.newest_anchor().head();
9194 let Some((buffer, buffer_position)) =
9195 self.buffer.read(cx).text_anchor_for_position(position, cx)
9196 else {
9197 return;
9198 };
9199
9200 cx.spawn(|editor, mut cx| async move {
9201 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9202 editor.update(&mut cx, |_, cx| {
9203 cx.open_url(&url);
9204 })
9205 } else {
9206 Ok(())
9207 }
9208 })
9209 .detach();
9210 }
9211
9212 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9213 let Some(workspace) = self.workspace() else {
9214 return;
9215 };
9216
9217 let position = self.selections.newest_anchor().head();
9218
9219 let Some((buffer, buffer_position)) =
9220 self.buffer.read(cx).text_anchor_for_position(position, cx)
9221 else {
9222 return;
9223 };
9224
9225 let Some(project) = self.project.clone() else {
9226 return;
9227 };
9228
9229 cx.spawn(|_, mut cx| async move {
9230 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9231
9232 if let Some((_, path)) = result {
9233 workspace
9234 .update(&mut cx, |workspace, cx| {
9235 workspace.open_resolved_path(path, cx)
9236 })?
9237 .await?;
9238 }
9239 anyhow::Ok(())
9240 })
9241 .detach();
9242 }
9243
9244 pub(crate) fn navigate_to_hover_links(
9245 &mut self,
9246 kind: Option<GotoDefinitionKind>,
9247 mut definitions: Vec<HoverLink>,
9248 split: bool,
9249 cx: &mut ViewContext<Editor>,
9250 ) -> Task<Result<Navigated>> {
9251 // If there is one definition, just open it directly
9252 if definitions.len() == 1 {
9253 let definition = definitions.pop().unwrap();
9254
9255 enum TargetTaskResult {
9256 Location(Option<Location>),
9257 AlreadyNavigated,
9258 }
9259
9260 let target_task = match definition {
9261 HoverLink::Text(link) => {
9262 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9263 }
9264 HoverLink::InlayHint(lsp_location, server_id) => {
9265 let computation = self.compute_target_location(lsp_location, server_id, cx);
9266 cx.background_executor().spawn(async move {
9267 let location = computation.await?;
9268 Ok(TargetTaskResult::Location(location))
9269 })
9270 }
9271 HoverLink::Url(url) => {
9272 cx.open_url(&url);
9273 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9274 }
9275 HoverLink::File(path) => {
9276 if let Some(workspace) = self.workspace() {
9277 cx.spawn(|_, mut cx| async move {
9278 workspace
9279 .update(&mut cx, |workspace, cx| {
9280 workspace.open_resolved_path(path, cx)
9281 })?
9282 .await
9283 .map(|_| TargetTaskResult::AlreadyNavigated)
9284 })
9285 } else {
9286 Task::ready(Ok(TargetTaskResult::Location(None)))
9287 }
9288 }
9289 };
9290 cx.spawn(|editor, mut cx| async move {
9291 let target = match target_task.await.context("target resolution task")? {
9292 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9293 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9294 TargetTaskResult::Location(Some(target)) => target,
9295 };
9296
9297 editor.update(&mut cx, |editor, cx| {
9298 let Some(workspace) = editor.workspace() else {
9299 return Navigated::No;
9300 };
9301 let pane = workspace.read(cx).active_pane().clone();
9302
9303 let range = target.range.to_offset(target.buffer.read(cx));
9304 let range = editor.range_for_match(&range);
9305
9306 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9307 let buffer = target.buffer.read(cx);
9308 let range = check_multiline_range(buffer, range);
9309 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
9310 s.select_ranges([range]);
9311 });
9312 } else {
9313 cx.window_context().defer(move |cx| {
9314 let target_editor: View<Self> =
9315 workspace.update(cx, |workspace, cx| {
9316 let pane = if split {
9317 workspace.adjacent_pane(cx)
9318 } else {
9319 workspace.active_pane().clone()
9320 };
9321
9322 workspace.open_project_item(
9323 pane,
9324 target.buffer.clone(),
9325 true,
9326 true,
9327 cx,
9328 )
9329 });
9330 target_editor.update(cx, |target_editor, cx| {
9331 // When selecting a definition in a different buffer, disable the nav history
9332 // to avoid creating a history entry at the previous cursor location.
9333 pane.update(cx, |pane, _| pane.disable_history());
9334 let buffer = target.buffer.read(cx);
9335 let range = check_multiline_range(buffer, range);
9336 target_editor.change_selections(
9337 Some(Autoscroll::focused()),
9338 cx,
9339 |s| {
9340 s.select_ranges([range]);
9341 },
9342 );
9343 pane.update(cx, |pane, _| pane.enable_history());
9344 });
9345 });
9346 }
9347 Navigated::Yes
9348 })
9349 })
9350 } else if !definitions.is_empty() {
9351 let replica_id = self.replica_id(cx);
9352 cx.spawn(|editor, mut cx| async move {
9353 let (title, location_tasks, workspace) = editor
9354 .update(&mut cx, |editor, cx| {
9355 let tab_kind = match kind {
9356 Some(GotoDefinitionKind::Implementation) => "Implementations",
9357 _ => "Definitions",
9358 };
9359 let title = definitions
9360 .iter()
9361 .find_map(|definition| match definition {
9362 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9363 let buffer = origin.buffer.read(cx);
9364 format!(
9365 "{} for {}",
9366 tab_kind,
9367 buffer
9368 .text_for_range(origin.range.clone())
9369 .collect::<String>()
9370 )
9371 }),
9372 HoverLink::InlayHint(_, _) => None,
9373 HoverLink::Url(_) => None,
9374 HoverLink::File(_) => None,
9375 })
9376 .unwrap_or(tab_kind.to_string());
9377 let location_tasks = definitions
9378 .into_iter()
9379 .map(|definition| match definition {
9380 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9381 HoverLink::InlayHint(lsp_location, server_id) => {
9382 editor.compute_target_location(lsp_location, server_id, cx)
9383 }
9384 HoverLink::Url(_) => Task::ready(Ok(None)),
9385 HoverLink::File(_) => Task::ready(Ok(None)),
9386 })
9387 .collect::<Vec<_>>();
9388 (title, location_tasks, editor.workspace().clone())
9389 })
9390 .context("location tasks preparation")?;
9391
9392 let locations = futures::future::join_all(location_tasks)
9393 .await
9394 .into_iter()
9395 .filter_map(|location| location.transpose())
9396 .collect::<Result<_>>()
9397 .context("location tasks")?;
9398
9399 let Some(workspace) = workspace else {
9400 return Ok(Navigated::No);
9401 };
9402 let opened = workspace
9403 .update(&mut cx, |workspace, cx| {
9404 Self::open_locations_in_multibuffer(
9405 workspace, locations, replica_id, title, split, cx,
9406 )
9407 })
9408 .ok();
9409
9410 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9411 })
9412 } else {
9413 Task::ready(Ok(Navigated::No))
9414 }
9415 }
9416
9417 fn compute_target_location(
9418 &self,
9419 lsp_location: lsp::Location,
9420 server_id: LanguageServerId,
9421 cx: &mut ViewContext<Editor>,
9422 ) -> Task<anyhow::Result<Option<Location>>> {
9423 let Some(project) = self.project.clone() else {
9424 return Task::Ready(Some(Ok(None)));
9425 };
9426
9427 cx.spawn(move |editor, mut cx| async move {
9428 let location_task = editor.update(&mut cx, |editor, cx| {
9429 project.update(cx, |project, cx| {
9430 let language_server_name =
9431 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9432 project
9433 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9434 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9435 });
9436 language_server_name.map(|language_server_name| {
9437 project.open_local_buffer_via_lsp(
9438 lsp_location.uri.clone(),
9439 server_id,
9440 language_server_name,
9441 cx,
9442 )
9443 })
9444 })
9445 })?;
9446 let location = match location_task {
9447 Some(task) => Some({
9448 let target_buffer_handle = task.await.context("open local buffer")?;
9449 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9450 let target_start = target_buffer
9451 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9452 let target_end = target_buffer
9453 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9454 target_buffer.anchor_after(target_start)
9455 ..target_buffer.anchor_before(target_end)
9456 })?;
9457 Location {
9458 buffer: target_buffer_handle,
9459 range,
9460 }
9461 }),
9462 None => None,
9463 };
9464 Ok(location)
9465 })
9466 }
9467
9468 pub fn find_all_references(
9469 &mut self,
9470 _: &FindAllReferences,
9471 cx: &mut ViewContext<Self>,
9472 ) -> Option<Task<Result<Navigated>>> {
9473 let multi_buffer = self.buffer.read(cx);
9474 let selection = self.selections.newest::<usize>(cx);
9475 let head = selection.head();
9476
9477 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9478 let head_anchor = multi_buffer_snapshot.anchor_at(
9479 head,
9480 if head < selection.tail() {
9481 Bias::Right
9482 } else {
9483 Bias::Left
9484 },
9485 );
9486
9487 match self
9488 .find_all_references_task_sources
9489 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9490 {
9491 Ok(_) => {
9492 log::info!(
9493 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9494 );
9495 return None;
9496 }
9497 Err(i) => {
9498 self.find_all_references_task_sources.insert(i, head_anchor);
9499 }
9500 }
9501
9502 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9503 let replica_id = self.replica_id(cx);
9504 let workspace = self.workspace()?;
9505 let project = workspace.read(cx).project().clone();
9506 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9507 Some(cx.spawn(|editor, mut cx| async move {
9508 let _cleanup = defer({
9509 let mut cx = cx.clone();
9510 move || {
9511 let _ = editor.update(&mut cx, |editor, _| {
9512 if let Ok(i) =
9513 editor
9514 .find_all_references_task_sources
9515 .binary_search_by(|anchor| {
9516 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9517 })
9518 {
9519 editor.find_all_references_task_sources.remove(i);
9520 }
9521 });
9522 }
9523 });
9524
9525 let locations = references.await?;
9526 if locations.is_empty() {
9527 return anyhow::Ok(Navigated::No);
9528 }
9529
9530 workspace.update(&mut cx, |workspace, cx| {
9531 let title = locations
9532 .first()
9533 .as_ref()
9534 .map(|location| {
9535 let buffer = location.buffer.read(cx);
9536 format!(
9537 "References to `{}`",
9538 buffer
9539 .text_for_range(location.range.clone())
9540 .collect::<String>()
9541 )
9542 })
9543 .unwrap();
9544 Self::open_locations_in_multibuffer(
9545 workspace, locations, replica_id, title, false, cx,
9546 );
9547 Navigated::Yes
9548 })
9549 }))
9550 }
9551
9552 /// Opens a multibuffer with the given project locations in it
9553 pub fn open_locations_in_multibuffer(
9554 workspace: &mut Workspace,
9555 mut locations: Vec<Location>,
9556 replica_id: ReplicaId,
9557 title: String,
9558 split: bool,
9559 cx: &mut ViewContext<Workspace>,
9560 ) {
9561 // If there are multiple definitions, open them in a multibuffer
9562 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9563 let mut locations = locations.into_iter().peekable();
9564 let mut ranges_to_highlight = Vec::new();
9565 let capability = workspace.project().read(cx).capability();
9566
9567 let excerpt_buffer = cx.new_model(|cx| {
9568 let mut multibuffer = MultiBuffer::new(replica_id, capability);
9569 while let Some(location) = locations.next() {
9570 let buffer = location.buffer.read(cx);
9571 let mut ranges_for_buffer = Vec::new();
9572 let range = location.range.to_offset(buffer);
9573 ranges_for_buffer.push(range.clone());
9574
9575 while let Some(next_location) = locations.peek() {
9576 if next_location.buffer == location.buffer {
9577 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9578 locations.next();
9579 } else {
9580 break;
9581 }
9582 }
9583
9584 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9585 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9586 location.buffer.clone(),
9587 ranges_for_buffer,
9588 DEFAULT_MULTIBUFFER_CONTEXT,
9589 cx,
9590 ))
9591 }
9592
9593 multibuffer.with_title(title)
9594 });
9595
9596 let editor = cx.new_view(|cx| {
9597 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9598 });
9599 editor.update(cx, |editor, cx| {
9600 if let Some(first_range) = ranges_to_highlight.first() {
9601 editor.change_selections(None, cx, |selections| {
9602 selections.clear_disjoint();
9603 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9604 });
9605 }
9606 editor.highlight_background::<Self>(
9607 &ranges_to_highlight,
9608 |theme| theme.editor_highlighted_line_background,
9609 cx,
9610 );
9611 });
9612
9613 let item = Box::new(editor);
9614 let item_id = item.item_id();
9615
9616 if split {
9617 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9618 } else {
9619 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9620 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9621 pane.close_current_preview_item(cx)
9622 } else {
9623 None
9624 }
9625 });
9626 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9627 }
9628 workspace.active_pane().update(cx, |pane, cx| {
9629 pane.set_preview_item_id(Some(item_id), cx);
9630 });
9631 }
9632
9633 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9634 use language::ToOffset as _;
9635
9636 let project = self.project.clone()?;
9637 let selection = self.selections.newest_anchor().clone();
9638 let (cursor_buffer, cursor_buffer_position) = self
9639 .buffer
9640 .read(cx)
9641 .text_anchor_for_position(selection.head(), cx)?;
9642 let (tail_buffer, cursor_buffer_position_end) = self
9643 .buffer
9644 .read(cx)
9645 .text_anchor_for_position(selection.tail(), cx)?;
9646 if tail_buffer != cursor_buffer {
9647 return None;
9648 }
9649
9650 let snapshot = cursor_buffer.read(cx).snapshot();
9651 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9652 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9653 let prepare_rename = project.update(cx, |project, cx| {
9654 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
9655 });
9656 drop(snapshot);
9657
9658 Some(cx.spawn(|this, mut cx| async move {
9659 let rename_range = if let Some(range) = prepare_rename.await? {
9660 Some(range)
9661 } else {
9662 this.update(&mut cx, |this, cx| {
9663 let buffer = this.buffer.read(cx).snapshot(cx);
9664 let mut buffer_highlights = this
9665 .document_highlights_for_position(selection.head(), &buffer)
9666 .filter(|highlight| {
9667 highlight.start.excerpt_id == selection.head().excerpt_id
9668 && highlight.end.excerpt_id == selection.head().excerpt_id
9669 });
9670 buffer_highlights
9671 .next()
9672 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9673 })?
9674 };
9675 if let Some(rename_range) = rename_range {
9676 this.update(&mut cx, |this, cx| {
9677 let snapshot = cursor_buffer.read(cx).snapshot();
9678 let rename_buffer_range = rename_range.to_offset(&snapshot);
9679 let cursor_offset_in_rename_range =
9680 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9681 let cursor_offset_in_rename_range_end =
9682 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9683
9684 this.take_rename(false, cx);
9685 let buffer = this.buffer.read(cx).read(cx);
9686 let cursor_offset = selection.head().to_offset(&buffer);
9687 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9688 let rename_end = rename_start + rename_buffer_range.len();
9689 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9690 let mut old_highlight_id = None;
9691 let old_name: Arc<str> = buffer
9692 .chunks(rename_start..rename_end, true)
9693 .map(|chunk| {
9694 if old_highlight_id.is_none() {
9695 old_highlight_id = chunk.syntax_highlight_id;
9696 }
9697 chunk.text
9698 })
9699 .collect::<String>()
9700 .into();
9701
9702 drop(buffer);
9703
9704 // Position the selection in the rename editor so that it matches the current selection.
9705 this.show_local_selections = false;
9706 let rename_editor = cx.new_view(|cx| {
9707 let mut editor = Editor::single_line(cx);
9708 editor.buffer.update(cx, |buffer, cx| {
9709 buffer.edit([(0..0, old_name.clone())], None, cx)
9710 });
9711 let rename_selection_range = match cursor_offset_in_rename_range
9712 .cmp(&cursor_offset_in_rename_range_end)
9713 {
9714 Ordering::Equal => {
9715 editor.select_all(&SelectAll, cx);
9716 return editor;
9717 }
9718 Ordering::Less => {
9719 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9720 }
9721 Ordering::Greater => {
9722 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9723 }
9724 };
9725 if rename_selection_range.end > old_name.len() {
9726 editor.select_all(&SelectAll, cx);
9727 } else {
9728 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9729 s.select_ranges([rename_selection_range]);
9730 });
9731 }
9732 editor
9733 });
9734 cx.subscribe(&rename_editor, |_, _, e, cx| match e {
9735 EditorEvent::Focused => cx.emit(EditorEvent::FocusedIn),
9736 _ => {}
9737 })
9738 .detach();
9739
9740 let write_highlights =
9741 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
9742 let read_highlights =
9743 this.clear_background_highlights::<DocumentHighlightRead>(cx);
9744 let ranges = write_highlights
9745 .iter()
9746 .flat_map(|(_, ranges)| ranges.iter())
9747 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
9748 .cloned()
9749 .collect();
9750
9751 this.highlight_text::<Rename>(
9752 ranges,
9753 HighlightStyle {
9754 fade_out: Some(0.6),
9755 ..Default::default()
9756 },
9757 cx,
9758 );
9759 let rename_focus_handle = rename_editor.focus_handle(cx);
9760 cx.focus(&rename_focus_handle);
9761 let block_id = this.insert_blocks(
9762 [BlockProperties {
9763 style: BlockStyle::Flex,
9764 position: range.start,
9765 height: 1,
9766 render: Box::new({
9767 let rename_editor = rename_editor.clone();
9768 move |cx: &mut BlockContext| {
9769 let mut text_style = cx.editor_style.text.clone();
9770 if let Some(highlight_style) = old_highlight_id
9771 .and_then(|h| h.style(&cx.editor_style.syntax))
9772 {
9773 text_style = text_style.highlight(highlight_style);
9774 }
9775 div()
9776 .pl(cx.anchor_x)
9777 .child(EditorElement::new(
9778 &rename_editor,
9779 EditorStyle {
9780 background: cx.theme().system().transparent,
9781 local_player: cx.editor_style.local_player,
9782 text: text_style,
9783 scrollbar_width: cx.editor_style.scrollbar_width,
9784 syntax: cx.editor_style.syntax.clone(),
9785 status: cx.editor_style.status.clone(),
9786 inlay_hints_style: HighlightStyle {
9787 color: Some(cx.theme().status().hint),
9788 font_weight: Some(FontWeight::BOLD),
9789 ..HighlightStyle::default()
9790 },
9791 suggestions_style: HighlightStyle {
9792 color: Some(cx.theme().status().predictive),
9793 ..HighlightStyle::default()
9794 },
9795 ..EditorStyle::default()
9796 },
9797 ))
9798 .into_any_element()
9799 }
9800 }),
9801 disposition: BlockDisposition::Below,
9802 priority: 0,
9803 }],
9804 Some(Autoscroll::fit()),
9805 cx,
9806 )[0];
9807 this.pending_rename = Some(RenameState {
9808 range,
9809 old_name,
9810 editor: rename_editor,
9811 block_id,
9812 });
9813 })?;
9814 }
9815
9816 Ok(())
9817 }))
9818 }
9819
9820 pub fn confirm_rename(
9821 &mut self,
9822 _: &ConfirmRename,
9823 cx: &mut ViewContext<Self>,
9824 ) -> Option<Task<Result<()>>> {
9825 let rename = self.take_rename(false, cx)?;
9826 let workspace = self.workspace()?;
9827 let (start_buffer, start) = self
9828 .buffer
9829 .read(cx)
9830 .text_anchor_for_position(rename.range.start, cx)?;
9831 let (end_buffer, end) = self
9832 .buffer
9833 .read(cx)
9834 .text_anchor_for_position(rename.range.end, cx)?;
9835 if start_buffer != end_buffer {
9836 return None;
9837 }
9838
9839 let buffer = start_buffer;
9840 let range = start..end;
9841 let old_name = rename.old_name;
9842 let new_name = rename.editor.read(cx).text(cx);
9843
9844 let rename = workspace
9845 .read(cx)
9846 .project()
9847 .clone()
9848 .update(cx, |project, cx| {
9849 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
9850 });
9851 let workspace = workspace.downgrade();
9852
9853 Some(cx.spawn(|editor, mut cx| async move {
9854 let project_transaction = rename.await?;
9855 Self::open_project_transaction(
9856 &editor,
9857 workspace,
9858 project_transaction,
9859 format!("Rename: {} → {}", old_name, new_name),
9860 cx.clone(),
9861 )
9862 .await?;
9863
9864 editor.update(&mut cx, |editor, cx| {
9865 editor.refresh_document_highlights(cx);
9866 })?;
9867 Ok(())
9868 }))
9869 }
9870
9871 fn take_rename(
9872 &mut self,
9873 moving_cursor: bool,
9874 cx: &mut ViewContext<Self>,
9875 ) -> Option<RenameState> {
9876 let rename = self.pending_rename.take()?;
9877 if rename.editor.focus_handle(cx).is_focused(cx) {
9878 cx.focus(&self.focus_handle);
9879 }
9880
9881 self.remove_blocks(
9882 [rename.block_id].into_iter().collect(),
9883 Some(Autoscroll::fit()),
9884 cx,
9885 );
9886 self.clear_highlights::<Rename>(cx);
9887 self.show_local_selections = true;
9888
9889 if moving_cursor {
9890 let rename_editor = rename.editor.read(cx);
9891 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
9892
9893 // Update the selection to match the position of the selection inside
9894 // the rename editor.
9895 let snapshot = self.buffer.read(cx).read(cx);
9896 let rename_range = rename.range.to_offset(&snapshot);
9897 let cursor_in_editor = snapshot
9898 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
9899 .min(rename_range.end);
9900 drop(snapshot);
9901
9902 self.change_selections(None, cx, |s| {
9903 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
9904 });
9905 } else {
9906 self.refresh_document_highlights(cx);
9907 }
9908
9909 Some(rename)
9910 }
9911
9912 pub fn pending_rename(&self) -> Option<&RenameState> {
9913 self.pending_rename.as_ref()
9914 }
9915
9916 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9917 let project = match &self.project {
9918 Some(project) => project.clone(),
9919 None => return None,
9920 };
9921
9922 Some(self.perform_format(project, FormatTrigger::Manual, cx))
9923 }
9924
9925 fn perform_format(
9926 &mut self,
9927 project: Model<Project>,
9928 trigger: FormatTrigger,
9929 cx: &mut ViewContext<Self>,
9930 ) -> Task<Result<()>> {
9931 let buffer = self.buffer().clone();
9932 let mut buffers = buffer.read(cx).all_buffers();
9933 if trigger == FormatTrigger::Save {
9934 buffers.retain(|buffer| buffer.read(cx).is_dirty());
9935 }
9936
9937 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
9938 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
9939
9940 cx.spawn(|_, mut cx| async move {
9941 let transaction = futures::select_biased! {
9942 () = timeout => {
9943 log::warn!("timed out waiting for formatting");
9944 None
9945 }
9946 transaction = format.log_err().fuse() => transaction,
9947 };
9948
9949 buffer
9950 .update(&mut cx, |buffer, cx| {
9951 if let Some(transaction) = transaction {
9952 if !buffer.is_singleton() {
9953 buffer.push_transaction(&transaction.0, cx);
9954 }
9955 }
9956
9957 cx.notify();
9958 })
9959 .ok();
9960
9961 Ok(())
9962 })
9963 }
9964
9965 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
9966 if let Some(project) = self.project.clone() {
9967 self.buffer.update(cx, |multi_buffer, cx| {
9968 project.update(cx, |project, cx| {
9969 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
9970 });
9971 })
9972 }
9973 }
9974
9975 fn cancel_language_server_work(
9976 &mut self,
9977 _: &CancelLanguageServerWork,
9978 cx: &mut ViewContext<Self>,
9979 ) {
9980 if let Some(project) = self.project.clone() {
9981 self.buffer.update(cx, |multi_buffer, cx| {
9982 project.update(cx, |project, cx| {
9983 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
9984 });
9985 })
9986 }
9987 }
9988
9989 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
9990 cx.show_character_palette();
9991 }
9992
9993 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
9994 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
9995 let buffer = self.buffer.read(cx).snapshot(cx);
9996 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
9997 let is_valid = buffer
9998 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
9999 .any(|entry| {
10000 entry.diagnostic.is_primary
10001 && !entry.range.is_empty()
10002 && entry.range.start == primary_range_start
10003 && entry.diagnostic.message == active_diagnostics.primary_message
10004 });
10005
10006 if is_valid != active_diagnostics.is_valid {
10007 active_diagnostics.is_valid = is_valid;
10008 let mut new_styles = HashMap::default();
10009 for (block_id, diagnostic) in &active_diagnostics.blocks {
10010 new_styles.insert(
10011 *block_id,
10012 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10013 );
10014 }
10015 self.display_map.update(cx, |display_map, _cx| {
10016 display_map.replace_blocks(new_styles)
10017 });
10018 }
10019 }
10020 }
10021
10022 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10023 self.dismiss_diagnostics(cx);
10024 let snapshot = self.snapshot(cx);
10025 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10026 let buffer = self.buffer.read(cx).snapshot(cx);
10027
10028 let mut primary_range = None;
10029 let mut primary_message = None;
10030 let mut group_end = Point::zero();
10031 let diagnostic_group = buffer
10032 .diagnostic_group::<MultiBufferPoint>(group_id)
10033 .filter_map(|entry| {
10034 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10035 && (entry.range.start.row == entry.range.end.row
10036 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10037 {
10038 return None;
10039 }
10040 if entry.range.end > group_end {
10041 group_end = entry.range.end;
10042 }
10043 if entry.diagnostic.is_primary {
10044 primary_range = Some(entry.range.clone());
10045 primary_message = Some(entry.diagnostic.message.clone());
10046 }
10047 Some(entry)
10048 })
10049 .collect::<Vec<_>>();
10050 let primary_range = primary_range?;
10051 let primary_message = primary_message?;
10052 let primary_range =
10053 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10054
10055 let blocks = display_map
10056 .insert_blocks(
10057 diagnostic_group.iter().map(|entry| {
10058 let diagnostic = entry.diagnostic.clone();
10059 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10060 BlockProperties {
10061 style: BlockStyle::Fixed,
10062 position: buffer.anchor_after(entry.range.start),
10063 height: message_height,
10064 render: diagnostic_block_renderer(diagnostic, None, true, true),
10065 disposition: BlockDisposition::Below,
10066 priority: 0,
10067 }
10068 }),
10069 cx,
10070 )
10071 .into_iter()
10072 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10073 .collect();
10074
10075 Some(ActiveDiagnosticGroup {
10076 primary_range,
10077 primary_message,
10078 group_id,
10079 blocks,
10080 is_valid: true,
10081 })
10082 });
10083 self.active_diagnostics.is_some()
10084 }
10085
10086 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10087 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10088 self.display_map.update(cx, |display_map, cx| {
10089 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10090 });
10091 cx.notify();
10092 }
10093 }
10094
10095 pub fn set_selections_from_remote(
10096 &mut self,
10097 selections: Vec<Selection<Anchor>>,
10098 pending_selection: Option<Selection<Anchor>>,
10099 cx: &mut ViewContext<Self>,
10100 ) {
10101 let old_cursor_position = self.selections.newest_anchor().head();
10102 self.selections.change_with(cx, |s| {
10103 s.select_anchors(selections);
10104 if let Some(pending_selection) = pending_selection {
10105 s.set_pending(pending_selection, SelectMode::Character);
10106 } else {
10107 s.clear_pending();
10108 }
10109 });
10110 self.selections_did_change(false, &old_cursor_position, true, cx);
10111 }
10112
10113 fn push_to_selection_history(&mut self) {
10114 self.selection_history.push(SelectionHistoryEntry {
10115 selections: self.selections.disjoint_anchors(),
10116 select_next_state: self.select_next_state.clone(),
10117 select_prev_state: self.select_prev_state.clone(),
10118 add_selections_state: self.add_selections_state.clone(),
10119 });
10120 }
10121
10122 pub fn transact(
10123 &mut self,
10124 cx: &mut ViewContext<Self>,
10125 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10126 ) -> Option<TransactionId> {
10127 self.start_transaction_at(Instant::now(), cx);
10128 update(self, cx);
10129 self.end_transaction_at(Instant::now(), cx)
10130 }
10131
10132 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10133 self.end_selection(cx);
10134 if let Some(tx_id) = self
10135 .buffer
10136 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10137 {
10138 self.selection_history
10139 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10140 cx.emit(EditorEvent::TransactionBegun {
10141 transaction_id: tx_id,
10142 })
10143 }
10144 }
10145
10146 fn end_transaction_at(
10147 &mut self,
10148 now: Instant,
10149 cx: &mut ViewContext<Self>,
10150 ) -> Option<TransactionId> {
10151 if let Some(transaction_id) = self
10152 .buffer
10153 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10154 {
10155 if let Some((_, end_selections)) =
10156 self.selection_history.transaction_mut(transaction_id)
10157 {
10158 *end_selections = Some(self.selections.disjoint_anchors());
10159 } else {
10160 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10161 }
10162
10163 cx.emit(EditorEvent::Edited { transaction_id });
10164 Some(transaction_id)
10165 } else {
10166 None
10167 }
10168 }
10169
10170 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10171 let mut fold_ranges = Vec::new();
10172
10173 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10174
10175 let selections = self.selections.all_adjusted(cx);
10176 for selection in selections {
10177 let range = selection.range().sorted();
10178 let buffer_start_row = range.start.row;
10179
10180 for row in (0..=range.end.row).rev() {
10181 if let Some((foldable_range, fold_text)) =
10182 display_map.foldable_range(MultiBufferRow(row))
10183 {
10184 if foldable_range.end.row >= buffer_start_row {
10185 fold_ranges.push((foldable_range, fold_text));
10186 if row <= range.start.row {
10187 break;
10188 }
10189 }
10190 }
10191 }
10192 }
10193
10194 self.fold_ranges(fold_ranges, true, cx);
10195 }
10196
10197 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10198 let buffer_row = fold_at.buffer_row;
10199 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10200
10201 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10202 let autoscroll = self
10203 .selections
10204 .all::<Point>(cx)
10205 .iter()
10206 .any(|selection| fold_range.overlaps(&selection.range()));
10207
10208 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10209 }
10210 }
10211
10212 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10213 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10214 let buffer = &display_map.buffer_snapshot;
10215 let selections = self.selections.all::<Point>(cx);
10216 let ranges = selections
10217 .iter()
10218 .map(|s| {
10219 let range = s.display_range(&display_map).sorted();
10220 let mut start = range.start.to_point(&display_map);
10221 let mut end = range.end.to_point(&display_map);
10222 start.column = 0;
10223 end.column = buffer.line_len(MultiBufferRow(end.row));
10224 start..end
10225 })
10226 .collect::<Vec<_>>();
10227
10228 self.unfold_ranges(ranges, true, true, cx);
10229 }
10230
10231 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10232 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10233
10234 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10235 ..Point::new(
10236 unfold_at.buffer_row.0,
10237 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10238 );
10239
10240 let autoscroll = self
10241 .selections
10242 .all::<Point>(cx)
10243 .iter()
10244 .any(|selection| selection.range().overlaps(&intersection_range));
10245
10246 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10247 }
10248
10249 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10250 let selections = self.selections.all::<Point>(cx);
10251 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10252 let line_mode = self.selections.line_mode;
10253 let ranges = selections.into_iter().map(|s| {
10254 if line_mode {
10255 let start = Point::new(s.start.row, 0);
10256 let end = Point::new(
10257 s.end.row,
10258 display_map
10259 .buffer_snapshot
10260 .line_len(MultiBufferRow(s.end.row)),
10261 );
10262 (start..end, display_map.fold_placeholder.clone())
10263 } else {
10264 (s.start..s.end, display_map.fold_placeholder.clone())
10265 }
10266 });
10267 self.fold_ranges(ranges, true, cx);
10268 }
10269
10270 pub fn fold_ranges<T: ToOffset + Clone>(
10271 &mut self,
10272 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10273 auto_scroll: bool,
10274 cx: &mut ViewContext<Self>,
10275 ) {
10276 let mut fold_ranges = Vec::new();
10277 let mut buffers_affected = HashMap::default();
10278 let multi_buffer = self.buffer().read(cx);
10279 for (fold_range, fold_text) in ranges {
10280 if let Some((_, buffer, _)) =
10281 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10282 {
10283 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10284 };
10285 fold_ranges.push((fold_range, fold_text));
10286 }
10287
10288 let mut ranges = fold_ranges.into_iter().peekable();
10289 if ranges.peek().is_some() {
10290 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10291
10292 if auto_scroll {
10293 self.request_autoscroll(Autoscroll::fit(), cx);
10294 }
10295
10296 for buffer in buffers_affected.into_values() {
10297 self.sync_expanded_diff_hunks(buffer, cx);
10298 }
10299
10300 cx.notify();
10301
10302 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10303 // Clear diagnostics block when folding a range that contains it.
10304 let snapshot = self.snapshot(cx);
10305 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10306 drop(snapshot);
10307 self.active_diagnostics = Some(active_diagnostics);
10308 self.dismiss_diagnostics(cx);
10309 } else {
10310 self.active_diagnostics = Some(active_diagnostics);
10311 }
10312 }
10313
10314 self.scrollbar_marker_state.dirty = true;
10315 }
10316 }
10317
10318 pub fn unfold_ranges<T: ToOffset + Clone>(
10319 &mut self,
10320 ranges: impl IntoIterator<Item = Range<T>>,
10321 inclusive: bool,
10322 auto_scroll: bool,
10323 cx: &mut ViewContext<Self>,
10324 ) {
10325 let mut unfold_ranges = Vec::new();
10326 let mut buffers_affected = HashMap::default();
10327 let multi_buffer = self.buffer().read(cx);
10328 for range in ranges {
10329 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10330 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10331 };
10332 unfold_ranges.push(range);
10333 }
10334
10335 let mut ranges = unfold_ranges.into_iter().peekable();
10336 if ranges.peek().is_some() {
10337 self.display_map
10338 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10339 if auto_scroll {
10340 self.request_autoscroll(Autoscroll::fit(), cx);
10341 }
10342
10343 for buffer in buffers_affected.into_values() {
10344 self.sync_expanded_diff_hunks(buffer, cx);
10345 }
10346
10347 cx.notify();
10348 self.scrollbar_marker_state.dirty = true;
10349 self.active_indent_guides_state.dirty = true;
10350 }
10351 }
10352
10353 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10354 if hovered != self.gutter_hovered {
10355 self.gutter_hovered = hovered;
10356 cx.notify();
10357 }
10358 }
10359
10360 pub fn insert_blocks(
10361 &mut self,
10362 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10363 autoscroll: Option<Autoscroll>,
10364 cx: &mut ViewContext<Self>,
10365 ) -> Vec<CustomBlockId> {
10366 let blocks = self
10367 .display_map
10368 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10369 if let Some(autoscroll) = autoscroll {
10370 self.request_autoscroll(autoscroll, cx);
10371 }
10372 cx.notify();
10373 blocks
10374 }
10375
10376 pub fn resize_blocks(
10377 &mut self,
10378 heights: HashMap<CustomBlockId, u32>,
10379 autoscroll: Option<Autoscroll>,
10380 cx: &mut ViewContext<Self>,
10381 ) {
10382 self.display_map
10383 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10384 if let Some(autoscroll) = autoscroll {
10385 self.request_autoscroll(autoscroll, cx);
10386 }
10387 cx.notify();
10388 }
10389
10390 pub fn replace_blocks(
10391 &mut self,
10392 renderers: HashMap<CustomBlockId, RenderBlock>,
10393 autoscroll: Option<Autoscroll>,
10394 cx: &mut ViewContext<Self>,
10395 ) {
10396 self.display_map
10397 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10398 if let Some(autoscroll) = autoscroll {
10399 self.request_autoscroll(autoscroll, cx);
10400 }
10401 cx.notify();
10402 }
10403
10404 pub fn remove_blocks(
10405 &mut self,
10406 block_ids: HashSet<CustomBlockId>,
10407 autoscroll: Option<Autoscroll>,
10408 cx: &mut ViewContext<Self>,
10409 ) {
10410 self.display_map.update(cx, |display_map, cx| {
10411 display_map.remove_blocks(block_ids, cx)
10412 });
10413 if let Some(autoscroll) = autoscroll {
10414 self.request_autoscroll(autoscroll, cx);
10415 }
10416 cx.notify();
10417 }
10418
10419 pub fn row_for_block(
10420 &self,
10421 block_id: CustomBlockId,
10422 cx: &mut ViewContext<Self>,
10423 ) -> Option<DisplayRow> {
10424 self.display_map
10425 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10426 }
10427
10428 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10429 self.focused_block = Some(focused_block);
10430 }
10431
10432 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10433 self.focused_block.take()
10434 }
10435
10436 pub fn insert_creases(
10437 &mut self,
10438 creases: impl IntoIterator<Item = Crease>,
10439 cx: &mut ViewContext<Self>,
10440 ) -> Vec<CreaseId> {
10441 self.display_map
10442 .update(cx, |map, cx| map.insert_creases(creases, cx))
10443 }
10444
10445 pub fn remove_creases(
10446 &mut self,
10447 ids: impl IntoIterator<Item = CreaseId>,
10448 cx: &mut ViewContext<Self>,
10449 ) {
10450 self.display_map
10451 .update(cx, |map, cx| map.remove_creases(ids, cx));
10452 }
10453
10454 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10455 self.display_map
10456 .update(cx, |map, cx| map.snapshot(cx))
10457 .longest_row()
10458 }
10459
10460 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10461 self.display_map
10462 .update(cx, |map, cx| map.snapshot(cx))
10463 .max_point()
10464 }
10465
10466 pub fn text(&self, cx: &AppContext) -> String {
10467 self.buffer.read(cx).read(cx).text()
10468 }
10469
10470 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10471 let text = self.text(cx);
10472 let text = text.trim();
10473
10474 if text.is_empty() {
10475 return None;
10476 }
10477
10478 Some(text.to_string())
10479 }
10480
10481 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10482 self.transact(cx, |this, cx| {
10483 this.buffer
10484 .read(cx)
10485 .as_singleton()
10486 .expect("you can only call set_text on editors for singleton buffers")
10487 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10488 });
10489 }
10490
10491 pub fn display_text(&self, cx: &mut AppContext) -> String {
10492 self.display_map
10493 .update(cx, |map, cx| map.snapshot(cx))
10494 .text()
10495 }
10496
10497 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10498 let mut wrap_guides = smallvec::smallvec![];
10499
10500 if self.show_wrap_guides == Some(false) {
10501 return wrap_guides;
10502 }
10503
10504 let settings = self.buffer.read(cx).settings_at(0, cx);
10505 if settings.show_wrap_guides {
10506 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10507 wrap_guides.push((soft_wrap as usize, true));
10508 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
10509 wrap_guides.push((soft_wrap as usize, true));
10510 }
10511 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10512 }
10513
10514 wrap_guides
10515 }
10516
10517 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10518 let settings = self.buffer.read(cx).settings_at(0, cx);
10519 let mode = self
10520 .soft_wrap_mode_override
10521 .unwrap_or_else(|| settings.soft_wrap);
10522 match mode {
10523 language_settings::SoftWrap::None => SoftWrap::None,
10524 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10525 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10526 language_settings::SoftWrap::PreferredLineLength => {
10527 SoftWrap::Column(settings.preferred_line_length)
10528 }
10529 language_settings::SoftWrap::Bounded => {
10530 SoftWrap::Bounded(settings.preferred_line_length)
10531 }
10532 }
10533 }
10534
10535 pub fn set_soft_wrap_mode(
10536 &mut self,
10537 mode: language_settings::SoftWrap,
10538 cx: &mut ViewContext<Self>,
10539 ) {
10540 self.soft_wrap_mode_override = Some(mode);
10541 cx.notify();
10542 }
10543
10544 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10545 let rem_size = cx.rem_size();
10546 self.display_map.update(cx, |map, cx| {
10547 map.set_font(
10548 style.text.font(),
10549 style.text.font_size.to_pixels(rem_size),
10550 cx,
10551 )
10552 });
10553 self.style = Some(style);
10554 }
10555
10556 pub fn style(&self) -> Option<&EditorStyle> {
10557 self.style.as_ref()
10558 }
10559
10560 // Called by the element. This method is not designed to be called outside of the editor
10561 // element's layout code because it does not notify when rewrapping is computed synchronously.
10562 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10563 self.display_map
10564 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10565 }
10566
10567 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10568 if self.soft_wrap_mode_override.is_some() {
10569 self.soft_wrap_mode_override.take();
10570 } else {
10571 let soft_wrap = match self.soft_wrap_mode(cx) {
10572 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10573 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
10574 language_settings::SoftWrap::PreferLine
10575 }
10576 };
10577 self.soft_wrap_mode_override = Some(soft_wrap);
10578 }
10579 cx.notify();
10580 }
10581
10582 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10583 let Some(workspace) = self.workspace() else {
10584 return;
10585 };
10586 let fs = workspace.read(cx).app_state().fs.clone();
10587 let current_show = TabBarSettings::get_global(cx).show;
10588 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10589 setting.show = Some(!current_show);
10590 });
10591 }
10592
10593 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10594 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10595 self.buffer
10596 .read(cx)
10597 .settings_at(0, cx)
10598 .indent_guides
10599 .enabled
10600 });
10601 self.show_indent_guides = Some(!currently_enabled);
10602 cx.notify();
10603 }
10604
10605 fn should_show_indent_guides(&self) -> Option<bool> {
10606 self.show_indent_guides
10607 }
10608
10609 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10610 let mut editor_settings = EditorSettings::get_global(cx).clone();
10611 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10612 EditorSettings::override_global(editor_settings, cx);
10613 }
10614
10615 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
10616 self.use_relative_line_numbers
10617 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
10618 }
10619
10620 pub fn toggle_relative_line_numbers(
10621 &mut self,
10622 _: &ToggleRelativeLineNumbers,
10623 cx: &mut ViewContext<Self>,
10624 ) {
10625 let is_relative = self.should_use_relative_line_numbers(cx);
10626 self.set_relative_line_number(Some(!is_relative), cx)
10627 }
10628
10629 pub fn set_relative_line_number(
10630 &mut self,
10631 is_relative: Option<bool>,
10632 cx: &mut ViewContext<Self>,
10633 ) {
10634 self.use_relative_line_numbers = is_relative;
10635 cx.notify();
10636 }
10637
10638 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10639 self.show_gutter = show_gutter;
10640 cx.notify();
10641 }
10642
10643 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10644 self.show_line_numbers = Some(show_line_numbers);
10645 cx.notify();
10646 }
10647
10648 pub fn set_show_git_diff_gutter(
10649 &mut self,
10650 show_git_diff_gutter: bool,
10651 cx: &mut ViewContext<Self>,
10652 ) {
10653 self.show_git_diff_gutter = Some(show_git_diff_gutter);
10654 cx.notify();
10655 }
10656
10657 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10658 self.show_code_actions = Some(show_code_actions);
10659 cx.notify();
10660 }
10661
10662 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10663 self.show_runnables = Some(show_runnables);
10664 cx.notify();
10665 }
10666
10667 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
10668 if self.display_map.read(cx).masked != masked {
10669 self.display_map.update(cx, |map, _| map.masked = masked);
10670 }
10671 cx.notify()
10672 }
10673
10674 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10675 self.show_wrap_guides = Some(show_wrap_guides);
10676 cx.notify();
10677 }
10678
10679 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10680 self.show_indent_guides = Some(show_indent_guides);
10681 cx.notify();
10682 }
10683
10684 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10685 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10686 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10687 if let Some(dir) = file.abs_path(cx).parent() {
10688 return Some(dir.to_owned());
10689 }
10690 }
10691
10692 if let Some(project_path) = buffer.read(cx).project_path(cx) {
10693 return Some(project_path.path.to_path_buf());
10694 }
10695 }
10696
10697 None
10698 }
10699
10700 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10701 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10702 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10703 cx.reveal_path(&file.abs_path(cx));
10704 }
10705 }
10706 }
10707
10708 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10709 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10710 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10711 if let Some(path) = file.abs_path(cx).to_str() {
10712 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10713 }
10714 }
10715 }
10716 }
10717
10718 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10719 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10720 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10721 if let Some(path) = file.path().to_str() {
10722 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10723 }
10724 }
10725 }
10726 }
10727
10728 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10729 self.show_git_blame_gutter = !self.show_git_blame_gutter;
10730
10731 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10732 self.start_git_blame(true, cx);
10733 }
10734
10735 cx.notify();
10736 }
10737
10738 pub fn toggle_git_blame_inline(
10739 &mut self,
10740 _: &ToggleGitBlameInline,
10741 cx: &mut ViewContext<Self>,
10742 ) {
10743 self.toggle_git_blame_inline_internal(true, cx);
10744 cx.notify();
10745 }
10746
10747 pub fn git_blame_inline_enabled(&self) -> bool {
10748 self.git_blame_inline_enabled
10749 }
10750
10751 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10752 self.show_selection_menu = self
10753 .show_selection_menu
10754 .map(|show_selections_menu| !show_selections_menu)
10755 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10756
10757 cx.notify();
10758 }
10759
10760 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10761 self.show_selection_menu
10762 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10763 }
10764
10765 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10766 if let Some(project) = self.project.as_ref() {
10767 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10768 return;
10769 };
10770
10771 if buffer.read(cx).file().is_none() {
10772 return;
10773 }
10774
10775 let focused = self.focus_handle(cx).contains_focused(cx);
10776
10777 let project = project.clone();
10778 let blame =
10779 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10780 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10781 self.blame = Some(blame);
10782 }
10783 }
10784
10785 fn toggle_git_blame_inline_internal(
10786 &mut self,
10787 user_triggered: bool,
10788 cx: &mut ViewContext<Self>,
10789 ) {
10790 if self.git_blame_inline_enabled {
10791 self.git_blame_inline_enabled = false;
10792 self.show_git_blame_inline = false;
10793 self.show_git_blame_inline_delay_task.take();
10794 } else {
10795 self.git_blame_inline_enabled = true;
10796 self.start_git_blame_inline(user_triggered, cx);
10797 }
10798
10799 cx.notify();
10800 }
10801
10802 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10803 self.start_git_blame(user_triggered, cx);
10804
10805 if ProjectSettings::get_global(cx)
10806 .git
10807 .inline_blame_delay()
10808 .is_some()
10809 {
10810 self.start_inline_blame_timer(cx);
10811 } else {
10812 self.show_git_blame_inline = true
10813 }
10814 }
10815
10816 pub fn blame(&self) -> Option<&Model<GitBlame>> {
10817 self.blame.as_ref()
10818 }
10819
10820 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10821 self.show_git_blame_gutter && self.has_blame_entries(cx)
10822 }
10823
10824 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10825 self.show_git_blame_inline
10826 && self.focus_handle.is_focused(cx)
10827 && !self.newest_selection_head_on_empty_line(cx)
10828 && self.has_blame_entries(cx)
10829 }
10830
10831 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10832 self.blame()
10833 .map_or(false, |blame| blame.read(cx).has_generated_entries())
10834 }
10835
10836 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10837 let cursor_anchor = self.selections.newest_anchor().head();
10838
10839 let snapshot = self.buffer.read(cx).snapshot(cx);
10840 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10841
10842 snapshot.line_len(buffer_row) == 0
10843 }
10844
10845 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10846 let (path, selection, repo) = maybe!({
10847 let project_handle = self.project.as_ref()?.clone();
10848 let project = project_handle.read(cx);
10849
10850 let selection = self.selections.newest::<Point>(cx);
10851 let selection_range = selection.range();
10852
10853 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10854 (buffer, selection_range.start.row..selection_range.end.row)
10855 } else {
10856 let buffer_ranges = self
10857 .buffer()
10858 .read(cx)
10859 .range_to_buffer_ranges(selection_range, cx);
10860
10861 let (buffer, range, _) = if selection.reversed {
10862 buffer_ranges.first()
10863 } else {
10864 buffer_ranges.last()
10865 }?;
10866
10867 let snapshot = buffer.read(cx).snapshot();
10868 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10869 ..text::ToPoint::to_point(&range.end, &snapshot).row;
10870 (buffer.clone(), selection)
10871 };
10872
10873 let path = buffer
10874 .read(cx)
10875 .file()?
10876 .as_local()?
10877 .path()
10878 .to_str()?
10879 .to_string();
10880 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10881 Some((path, selection, repo))
10882 })
10883 .ok_or_else(|| anyhow!("unable to open git repository"))?;
10884
10885 const REMOTE_NAME: &str = "origin";
10886 let origin_url = repo
10887 .remote_url(REMOTE_NAME)
10888 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10889 let sha = repo
10890 .head_sha()
10891 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10892
10893 let (provider, remote) =
10894 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10895 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10896
10897 Ok(provider.build_permalink(
10898 remote,
10899 BuildPermalinkParams {
10900 sha: &sha,
10901 path: &path,
10902 selection: Some(selection),
10903 },
10904 ))
10905 }
10906
10907 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10908 let permalink = self.get_permalink_to_line(cx);
10909
10910 match permalink {
10911 Ok(permalink) => {
10912 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
10913 }
10914 Err(err) => {
10915 let message = format!("Failed to copy permalink: {err}");
10916
10917 Err::<(), anyhow::Error>(err).log_err();
10918
10919 if let Some(workspace) = self.workspace() {
10920 workspace.update(cx, |workspace, cx| {
10921 struct CopyPermalinkToLine;
10922
10923 workspace.show_toast(
10924 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10925 cx,
10926 )
10927 })
10928 }
10929 }
10930 }
10931 }
10932
10933 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
10934 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10935 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10936 if let Some(path) = file.path().to_str() {
10937 let selection = self.selections.newest::<Point>(cx).start.row + 1;
10938 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
10939 }
10940 }
10941 }
10942 }
10943
10944 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10945 let permalink = self.get_permalink_to_line(cx);
10946
10947 match permalink {
10948 Ok(permalink) => {
10949 cx.open_url(permalink.as_ref());
10950 }
10951 Err(err) => {
10952 let message = format!("Failed to open permalink: {err}");
10953
10954 Err::<(), anyhow::Error>(err).log_err();
10955
10956 if let Some(workspace) = self.workspace() {
10957 workspace.update(cx, |workspace, cx| {
10958 struct OpenPermalinkToLine;
10959
10960 workspace.show_toast(
10961 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
10962 cx,
10963 )
10964 })
10965 }
10966 }
10967 }
10968 }
10969
10970 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
10971 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
10972 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
10973 pub fn highlight_rows<T: 'static>(
10974 &mut self,
10975 rows: RangeInclusive<Anchor>,
10976 color: Option<Hsla>,
10977 should_autoscroll: bool,
10978 cx: &mut ViewContext<Self>,
10979 ) {
10980 let snapshot = self.buffer().read(cx).snapshot(cx);
10981 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
10982 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
10983 highlight
10984 .range
10985 .start()
10986 .cmp(&rows.start(), &snapshot)
10987 .then(highlight.range.end().cmp(&rows.end(), &snapshot))
10988 });
10989 match (color, existing_highlight_index) {
10990 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
10991 ix,
10992 RowHighlight {
10993 index: post_inc(&mut self.highlight_order),
10994 range: rows,
10995 should_autoscroll,
10996 color,
10997 },
10998 ),
10999 (None, Ok(i)) => {
11000 row_highlights.remove(i);
11001 }
11002 }
11003 }
11004
11005 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11006 pub fn clear_row_highlights<T: 'static>(&mut self) {
11007 self.highlighted_rows.remove(&TypeId::of::<T>());
11008 }
11009
11010 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11011 pub fn highlighted_rows<T: 'static>(
11012 &self,
11013 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
11014 Some(
11015 self.highlighted_rows
11016 .get(&TypeId::of::<T>())?
11017 .iter()
11018 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
11019 )
11020 }
11021
11022 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11023 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11024 /// Allows to ignore certain kinds of highlights.
11025 pub fn highlighted_display_rows(
11026 &mut self,
11027 cx: &mut WindowContext,
11028 ) -> BTreeMap<DisplayRow, Hsla> {
11029 let snapshot = self.snapshot(cx);
11030 let mut used_highlight_orders = HashMap::default();
11031 self.highlighted_rows
11032 .iter()
11033 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11034 .fold(
11035 BTreeMap::<DisplayRow, Hsla>::new(),
11036 |mut unique_rows, highlight| {
11037 let start_row = highlight.range.start().to_display_point(&snapshot).row();
11038 let end_row = highlight.range.end().to_display_point(&snapshot).row();
11039 for row in start_row.0..=end_row.0 {
11040 let used_index =
11041 used_highlight_orders.entry(row).or_insert(highlight.index);
11042 if highlight.index >= *used_index {
11043 *used_index = highlight.index;
11044 match highlight.color {
11045 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
11046 None => unique_rows.remove(&DisplayRow(row)),
11047 };
11048 }
11049 }
11050 unique_rows
11051 },
11052 )
11053 }
11054
11055 pub fn highlighted_display_row_for_autoscroll(
11056 &self,
11057 snapshot: &DisplaySnapshot,
11058 ) -> Option<DisplayRow> {
11059 self.highlighted_rows
11060 .values()
11061 .flat_map(|highlighted_rows| highlighted_rows.iter())
11062 .filter_map(|highlight| {
11063 if highlight.color.is_none() || !highlight.should_autoscroll {
11064 return None;
11065 }
11066 Some(highlight.range.start().to_display_point(&snapshot).row())
11067 })
11068 .min()
11069 }
11070
11071 pub fn set_search_within_ranges(
11072 &mut self,
11073 ranges: &[Range<Anchor>],
11074 cx: &mut ViewContext<Self>,
11075 ) {
11076 self.highlight_background::<SearchWithinRange>(
11077 ranges,
11078 |colors| colors.editor_document_highlight_read_background,
11079 cx,
11080 )
11081 }
11082
11083 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11084 self.breadcrumb_header = Some(new_header);
11085 }
11086
11087 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11088 self.clear_background_highlights::<SearchWithinRange>(cx);
11089 }
11090
11091 pub fn highlight_background<T: 'static>(
11092 &mut self,
11093 ranges: &[Range<Anchor>],
11094 color_fetcher: fn(&ThemeColors) -> Hsla,
11095 cx: &mut ViewContext<Self>,
11096 ) {
11097 self.background_highlights
11098 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11099 self.scrollbar_marker_state.dirty = true;
11100 cx.notify();
11101 }
11102
11103 pub fn clear_background_highlights<T: 'static>(
11104 &mut self,
11105 cx: &mut ViewContext<Self>,
11106 ) -> Option<BackgroundHighlight> {
11107 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11108 if !text_highlights.1.is_empty() {
11109 self.scrollbar_marker_state.dirty = true;
11110 cx.notify();
11111 }
11112 Some(text_highlights)
11113 }
11114
11115 pub fn highlight_gutter<T: 'static>(
11116 &mut self,
11117 ranges: &[Range<Anchor>],
11118 color_fetcher: fn(&AppContext) -> Hsla,
11119 cx: &mut ViewContext<Self>,
11120 ) {
11121 self.gutter_highlights
11122 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11123 cx.notify();
11124 }
11125
11126 pub fn clear_gutter_highlights<T: 'static>(
11127 &mut self,
11128 cx: &mut ViewContext<Self>,
11129 ) -> Option<GutterHighlight> {
11130 cx.notify();
11131 self.gutter_highlights.remove(&TypeId::of::<T>())
11132 }
11133
11134 #[cfg(feature = "test-support")]
11135 pub fn all_text_background_highlights(
11136 &mut self,
11137 cx: &mut ViewContext<Self>,
11138 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11139 let snapshot = self.snapshot(cx);
11140 let buffer = &snapshot.buffer_snapshot;
11141 let start = buffer.anchor_before(0);
11142 let end = buffer.anchor_after(buffer.len());
11143 let theme = cx.theme().colors();
11144 self.background_highlights_in_range(start..end, &snapshot, theme)
11145 }
11146
11147 #[cfg(feature = "test-support")]
11148 pub fn search_background_highlights(
11149 &mut self,
11150 cx: &mut ViewContext<Self>,
11151 ) -> Vec<Range<Point>> {
11152 let snapshot = self.buffer().read(cx).snapshot(cx);
11153
11154 let highlights = self
11155 .background_highlights
11156 .get(&TypeId::of::<items::BufferSearchHighlights>());
11157
11158 if let Some((_color, ranges)) = highlights {
11159 ranges
11160 .iter()
11161 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11162 .collect_vec()
11163 } else {
11164 vec![]
11165 }
11166 }
11167
11168 fn document_highlights_for_position<'a>(
11169 &'a self,
11170 position: Anchor,
11171 buffer: &'a MultiBufferSnapshot,
11172 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
11173 let read_highlights = self
11174 .background_highlights
11175 .get(&TypeId::of::<DocumentHighlightRead>())
11176 .map(|h| &h.1);
11177 let write_highlights = self
11178 .background_highlights
11179 .get(&TypeId::of::<DocumentHighlightWrite>())
11180 .map(|h| &h.1);
11181 let left_position = position.bias_left(buffer);
11182 let right_position = position.bias_right(buffer);
11183 read_highlights
11184 .into_iter()
11185 .chain(write_highlights)
11186 .flat_map(move |ranges| {
11187 let start_ix = match ranges.binary_search_by(|probe| {
11188 let cmp = probe.end.cmp(&left_position, buffer);
11189 if cmp.is_ge() {
11190 Ordering::Greater
11191 } else {
11192 Ordering::Less
11193 }
11194 }) {
11195 Ok(i) | Err(i) => i,
11196 };
11197
11198 ranges[start_ix..]
11199 .iter()
11200 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11201 })
11202 }
11203
11204 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11205 self.background_highlights
11206 .get(&TypeId::of::<T>())
11207 .map_or(false, |(_, highlights)| !highlights.is_empty())
11208 }
11209
11210 pub fn background_highlights_in_range(
11211 &self,
11212 search_range: Range<Anchor>,
11213 display_snapshot: &DisplaySnapshot,
11214 theme: &ThemeColors,
11215 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11216 let mut results = Vec::new();
11217 for (color_fetcher, ranges) in self.background_highlights.values() {
11218 let color = color_fetcher(theme);
11219 let start_ix = match ranges.binary_search_by(|probe| {
11220 let cmp = probe
11221 .end
11222 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11223 if cmp.is_gt() {
11224 Ordering::Greater
11225 } else {
11226 Ordering::Less
11227 }
11228 }) {
11229 Ok(i) | Err(i) => i,
11230 };
11231 for range in &ranges[start_ix..] {
11232 if range
11233 .start
11234 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11235 .is_ge()
11236 {
11237 break;
11238 }
11239
11240 let start = range.start.to_display_point(&display_snapshot);
11241 let end = range.end.to_display_point(&display_snapshot);
11242 results.push((start..end, color))
11243 }
11244 }
11245 results
11246 }
11247
11248 pub fn background_highlight_row_ranges<T: 'static>(
11249 &self,
11250 search_range: Range<Anchor>,
11251 display_snapshot: &DisplaySnapshot,
11252 count: usize,
11253 ) -> Vec<RangeInclusive<DisplayPoint>> {
11254 let mut results = Vec::new();
11255 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11256 return vec![];
11257 };
11258
11259 let start_ix = match ranges.binary_search_by(|probe| {
11260 let cmp = probe
11261 .end
11262 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11263 if cmp.is_gt() {
11264 Ordering::Greater
11265 } else {
11266 Ordering::Less
11267 }
11268 }) {
11269 Ok(i) | Err(i) => i,
11270 };
11271 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11272 if let (Some(start_display), Some(end_display)) = (start, end) {
11273 results.push(
11274 start_display.to_display_point(display_snapshot)
11275 ..=end_display.to_display_point(display_snapshot),
11276 );
11277 }
11278 };
11279 let mut start_row: Option<Point> = None;
11280 let mut end_row: Option<Point> = None;
11281 if ranges.len() > count {
11282 return Vec::new();
11283 }
11284 for range in &ranges[start_ix..] {
11285 if range
11286 .start
11287 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11288 .is_ge()
11289 {
11290 break;
11291 }
11292 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11293 if let Some(current_row) = &end_row {
11294 if end.row == current_row.row {
11295 continue;
11296 }
11297 }
11298 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11299 if start_row.is_none() {
11300 assert_eq!(end_row, None);
11301 start_row = Some(start);
11302 end_row = Some(end);
11303 continue;
11304 }
11305 if let Some(current_end) = end_row.as_mut() {
11306 if start.row > current_end.row + 1 {
11307 push_region(start_row, end_row);
11308 start_row = Some(start);
11309 end_row = Some(end);
11310 } else {
11311 // Merge two hunks.
11312 *current_end = end;
11313 }
11314 } else {
11315 unreachable!();
11316 }
11317 }
11318 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11319 push_region(start_row, end_row);
11320 results
11321 }
11322
11323 pub fn gutter_highlights_in_range(
11324 &self,
11325 search_range: Range<Anchor>,
11326 display_snapshot: &DisplaySnapshot,
11327 cx: &AppContext,
11328 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11329 let mut results = Vec::new();
11330 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11331 let color = color_fetcher(cx);
11332 let start_ix = match ranges.binary_search_by(|probe| {
11333 let cmp = probe
11334 .end
11335 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11336 if cmp.is_gt() {
11337 Ordering::Greater
11338 } else {
11339 Ordering::Less
11340 }
11341 }) {
11342 Ok(i) | Err(i) => i,
11343 };
11344 for range in &ranges[start_ix..] {
11345 if range
11346 .start
11347 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11348 .is_ge()
11349 {
11350 break;
11351 }
11352
11353 let start = range.start.to_display_point(&display_snapshot);
11354 let end = range.end.to_display_point(&display_snapshot);
11355 results.push((start..end, color))
11356 }
11357 }
11358 results
11359 }
11360
11361 /// Get the text ranges corresponding to the redaction query
11362 pub fn redacted_ranges(
11363 &self,
11364 search_range: Range<Anchor>,
11365 display_snapshot: &DisplaySnapshot,
11366 cx: &WindowContext,
11367 ) -> Vec<Range<DisplayPoint>> {
11368 display_snapshot
11369 .buffer_snapshot
11370 .redacted_ranges(search_range, |file| {
11371 if let Some(file) = file {
11372 file.is_private()
11373 && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
11374 } else {
11375 false
11376 }
11377 })
11378 .map(|range| {
11379 range.start.to_display_point(display_snapshot)
11380 ..range.end.to_display_point(display_snapshot)
11381 })
11382 .collect()
11383 }
11384
11385 pub fn highlight_text<T: 'static>(
11386 &mut self,
11387 ranges: Vec<Range<Anchor>>,
11388 style: HighlightStyle,
11389 cx: &mut ViewContext<Self>,
11390 ) {
11391 self.display_map.update(cx, |map, _| {
11392 map.highlight_text(TypeId::of::<T>(), ranges, style)
11393 });
11394 cx.notify();
11395 }
11396
11397 pub(crate) fn highlight_inlays<T: 'static>(
11398 &mut self,
11399 highlights: Vec<InlayHighlight>,
11400 style: HighlightStyle,
11401 cx: &mut ViewContext<Self>,
11402 ) {
11403 self.display_map.update(cx, |map, _| {
11404 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11405 });
11406 cx.notify();
11407 }
11408
11409 pub fn text_highlights<'a, T: 'static>(
11410 &'a self,
11411 cx: &'a AppContext,
11412 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11413 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11414 }
11415
11416 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11417 let cleared = self
11418 .display_map
11419 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11420 if cleared {
11421 cx.notify();
11422 }
11423 }
11424
11425 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11426 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11427 && self.focus_handle.is_focused(cx)
11428 }
11429
11430 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11431 self.show_cursor_when_unfocused = is_enabled;
11432 cx.notify();
11433 }
11434
11435 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11436 cx.notify();
11437 }
11438
11439 fn on_buffer_event(
11440 &mut self,
11441 multibuffer: Model<MultiBuffer>,
11442 event: &multi_buffer::Event,
11443 cx: &mut ViewContext<Self>,
11444 ) {
11445 match event {
11446 multi_buffer::Event::Edited {
11447 singleton_buffer_edited,
11448 } => {
11449 self.scrollbar_marker_state.dirty = true;
11450 self.active_indent_guides_state.dirty = true;
11451 self.refresh_active_diagnostics(cx);
11452 self.refresh_code_actions(cx);
11453 if self.has_active_inline_completion(cx) {
11454 self.update_visible_inline_completion(cx);
11455 }
11456 cx.emit(EditorEvent::BufferEdited);
11457 cx.emit(SearchEvent::MatchesInvalidated);
11458 if *singleton_buffer_edited {
11459 if let Some(project) = &self.project {
11460 let project = project.read(cx);
11461 #[allow(clippy::mutable_key_type)]
11462 let languages_affected = multibuffer
11463 .read(cx)
11464 .all_buffers()
11465 .into_iter()
11466 .filter_map(|buffer| {
11467 let buffer = buffer.read(cx);
11468 let language = buffer.language()?;
11469 if project.is_local_or_ssh()
11470 && project.language_servers_for_buffer(buffer, cx).count() == 0
11471 {
11472 None
11473 } else {
11474 Some(language)
11475 }
11476 })
11477 .cloned()
11478 .collect::<HashSet<_>>();
11479 if !languages_affected.is_empty() {
11480 self.refresh_inlay_hints(
11481 InlayHintRefreshReason::BufferEdited(languages_affected),
11482 cx,
11483 );
11484 }
11485 }
11486 }
11487
11488 let Some(project) = &self.project else { return };
11489 let telemetry = project.read(cx).client().telemetry().clone();
11490 refresh_linked_ranges(self, cx);
11491 telemetry.log_edit_event("editor");
11492 }
11493 multi_buffer::Event::ExcerptsAdded {
11494 buffer,
11495 predecessor,
11496 excerpts,
11497 } => {
11498 self.tasks_update_task = Some(self.refresh_runnables(cx));
11499 cx.emit(EditorEvent::ExcerptsAdded {
11500 buffer: buffer.clone(),
11501 predecessor: *predecessor,
11502 excerpts: excerpts.clone(),
11503 });
11504 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11505 }
11506 multi_buffer::Event::ExcerptsRemoved { ids } => {
11507 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11508 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11509 }
11510 multi_buffer::Event::ExcerptsEdited { ids } => {
11511 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11512 }
11513 multi_buffer::Event::ExcerptsExpanded { ids } => {
11514 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11515 }
11516 multi_buffer::Event::Reparsed(buffer_id) => {
11517 self.tasks_update_task = Some(self.refresh_runnables(cx));
11518
11519 cx.emit(EditorEvent::Reparsed(*buffer_id));
11520 }
11521 multi_buffer::Event::LanguageChanged(buffer_id) => {
11522 linked_editing_ranges::refresh_linked_ranges(self, cx);
11523 cx.emit(EditorEvent::Reparsed(*buffer_id));
11524 cx.notify();
11525 }
11526 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11527 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11528 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11529 cx.emit(EditorEvent::TitleChanged)
11530 }
11531 multi_buffer::Event::DiffBaseChanged => {
11532 self.scrollbar_marker_state.dirty = true;
11533 cx.emit(EditorEvent::DiffBaseChanged);
11534 cx.notify();
11535 }
11536 multi_buffer::Event::DiffUpdated { buffer } => {
11537 self.sync_expanded_diff_hunks(buffer.clone(), cx);
11538 cx.notify();
11539 }
11540 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11541 multi_buffer::Event::DiagnosticsUpdated => {
11542 self.refresh_active_diagnostics(cx);
11543 self.scrollbar_marker_state.dirty = true;
11544 cx.notify();
11545 }
11546 _ => {}
11547 };
11548 }
11549
11550 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11551 cx.notify();
11552 }
11553
11554 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11555 self.tasks_update_task = Some(self.refresh_runnables(cx));
11556 self.refresh_inline_completion(true, false, cx);
11557 self.refresh_inlay_hints(
11558 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11559 self.selections.newest_anchor().head(),
11560 &self.buffer.read(cx).snapshot(cx),
11561 cx,
11562 )),
11563 cx,
11564 );
11565 let editor_settings = EditorSettings::get_global(cx);
11566 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11567 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11568
11569 let project_settings = ProjectSettings::get_global(cx);
11570 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11571
11572 if self.mode == EditorMode::Full {
11573 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11574 if self.git_blame_inline_enabled != inline_blame_enabled {
11575 self.toggle_git_blame_inline_internal(false, cx);
11576 }
11577 }
11578
11579 cx.notify();
11580 }
11581
11582 pub fn set_searchable(&mut self, searchable: bool) {
11583 self.searchable = searchable;
11584 }
11585
11586 pub fn searchable(&self) -> bool {
11587 self.searchable
11588 }
11589
11590 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11591 self.open_excerpts_common(true, cx)
11592 }
11593
11594 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11595 self.open_excerpts_common(false, cx)
11596 }
11597
11598 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11599 let buffer = self.buffer.read(cx);
11600 if buffer.is_singleton() {
11601 cx.propagate();
11602 return;
11603 }
11604
11605 let Some(workspace) = self.workspace() else {
11606 cx.propagate();
11607 return;
11608 };
11609
11610 let mut new_selections_by_buffer = HashMap::default();
11611 for selection in self.selections.all::<usize>(cx) {
11612 for (buffer, mut range, _) in
11613 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11614 {
11615 if selection.reversed {
11616 mem::swap(&mut range.start, &mut range.end);
11617 }
11618 new_selections_by_buffer
11619 .entry(buffer)
11620 .or_insert(Vec::new())
11621 .push(range)
11622 }
11623 }
11624
11625 // We defer the pane interaction because we ourselves are a workspace item
11626 // and activating a new item causes the pane to call a method on us reentrantly,
11627 // which panics if we're on the stack.
11628 cx.window_context().defer(move |cx| {
11629 workspace.update(cx, |workspace, cx| {
11630 let pane = if split {
11631 workspace.adjacent_pane(cx)
11632 } else {
11633 workspace.active_pane().clone()
11634 };
11635
11636 for (buffer, ranges) in new_selections_by_buffer {
11637 let editor =
11638 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
11639 editor.update(cx, |editor, cx| {
11640 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11641 s.select_ranges(ranges);
11642 });
11643 });
11644 }
11645 })
11646 });
11647 }
11648
11649 fn jump(
11650 &mut self,
11651 path: ProjectPath,
11652 position: Point,
11653 anchor: language::Anchor,
11654 offset_from_top: u32,
11655 cx: &mut ViewContext<Self>,
11656 ) {
11657 let workspace = self.workspace();
11658 cx.spawn(|_, mut cx| async move {
11659 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11660 let editor = workspace.update(&mut cx, |workspace, cx| {
11661 // Reset the preview item id before opening the new item
11662 workspace.active_pane().update(cx, |pane, cx| {
11663 pane.set_preview_item_id(None, cx);
11664 });
11665 workspace.open_path_preview(path, None, true, true, cx)
11666 })?;
11667 let editor = editor
11668 .await?
11669 .downcast::<Editor>()
11670 .ok_or_else(|| anyhow!("opened item was not an editor"))?
11671 .downgrade();
11672 editor.update(&mut cx, |editor, cx| {
11673 let buffer = editor
11674 .buffer()
11675 .read(cx)
11676 .as_singleton()
11677 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11678 let buffer = buffer.read(cx);
11679 let cursor = if buffer.can_resolve(&anchor) {
11680 language::ToPoint::to_point(&anchor, buffer)
11681 } else {
11682 buffer.clip_point(position, Bias::Left)
11683 };
11684
11685 let nav_history = editor.nav_history.take();
11686 editor.change_selections(
11687 Some(Autoscroll::top_relative(offset_from_top as usize)),
11688 cx,
11689 |s| {
11690 s.select_ranges([cursor..cursor]);
11691 },
11692 );
11693 editor.nav_history = nav_history;
11694
11695 anyhow::Ok(())
11696 })??;
11697
11698 anyhow::Ok(())
11699 })
11700 .detach_and_log_err(cx);
11701 }
11702
11703 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11704 let snapshot = self.buffer.read(cx).read(cx);
11705 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11706 Some(
11707 ranges
11708 .iter()
11709 .map(move |range| {
11710 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11711 })
11712 .collect(),
11713 )
11714 }
11715
11716 fn selection_replacement_ranges(
11717 &self,
11718 range: Range<OffsetUtf16>,
11719 cx: &AppContext,
11720 ) -> Vec<Range<OffsetUtf16>> {
11721 let selections = self.selections.all::<OffsetUtf16>(cx);
11722 let newest_selection = selections
11723 .iter()
11724 .max_by_key(|selection| selection.id)
11725 .unwrap();
11726 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11727 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11728 let snapshot = self.buffer.read(cx).read(cx);
11729 selections
11730 .into_iter()
11731 .map(|mut selection| {
11732 selection.start.0 =
11733 (selection.start.0 as isize).saturating_add(start_delta) as usize;
11734 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11735 snapshot.clip_offset_utf16(selection.start, Bias::Left)
11736 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11737 })
11738 .collect()
11739 }
11740
11741 fn report_editor_event(
11742 &self,
11743 operation: &'static str,
11744 file_extension: Option<String>,
11745 cx: &AppContext,
11746 ) {
11747 if cfg!(any(test, feature = "test-support")) {
11748 return;
11749 }
11750
11751 let Some(project) = &self.project else { return };
11752
11753 // If None, we are in a file without an extension
11754 let file = self
11755 .buffer
11756 .read(cx)
11757 .as_singleton()
11758 .and_then(|b| b.read(cx).file());
11759 let file_extension = file_extension.or(file
11760 .as_ref()
11761 .and_then(|file| Path::new(file.file_name(cx)).extension())
11762 .and_then(|e| e.to_str())
11763 .map(|a| a.to_string()));
11764
11765 let vim_mode = cx
11766 .global::<SettingsStore>()
11767 .raw_user_settings()
11768 .get("vim_mode")
11769 == Some(&serde_json::Value::Bool(true));
11770
11771 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11772 == language::language_settings::InlineCompletionProvider::Copilot;
11773 let copilot_enabled_for_language = self
11774 .buffer
11775 .read(cx)
11776 .settings_at(0, cx)
11777 .show_inline_completions;
11778
11779 let telemetry = project.read(cx).client().telemetry().clone();
11780 telemetry.report_editor_event(
11781 file_extension,
11782 vim_mode,
11783 operation,
11784 copilot_enabled,
11785 copilot_enabled_for_language,
11786 )
11787 }
11788
11789 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11790 /// with each line being an array of {text, highlight} objects.
11791 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11792 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11793 return;
11794 };
11795
11796 #[derive(Serialize)]
11797 struct Chunk<'a> {
11798 text: String,
11799 highlight: Option<&'a str>,
11800 }
11801
11802 let snapshot = buffer.read(cx).snapshot();
11803 let range = self
11804 .selected_text_range(cx)
11805 .and_then(|selected_range| {
11806 if selected_range.is_empty() {
11807 None
11808 } else {
11809 Some(selected_range)
11810 }
11811 })
11812 .unwrap_or_else(|| 0..snapshot.len());
11813
11814 let chunks = snapshot.chunks(range, true);
11815 let mut lines = Vec::new();
11816 let mut line: VecDeque<Chunk> = VecDeque::new();
11817
11818 let Some(style) = self.style.as_ref() else {
11819 return;
11820 };
11821
11822 for chunk in chunks {
11823 let highlight = chunk
11824 .syntax_highlight_id
11825 .and_then(|id| id.name(&style.syntax));
11826 let mut chunk_lines = chunk.text.split('\n').peekable();
11827 while let Some(text) = chunk_lines.next() {
11828 let mut merged_with_last_token = false;
11829 if let Some(last_token) = line.back_mut() {
11830 if last_token.highlight == highlight {
11831 last_token.text.push_str(text);
11832 merged_with_last_token = true;
11833 }
11834 }
11835
11836 if !merged_with_last_token {
11837 line.push_back(Chunk {
11838 text: text.into(),
11839 highlight,
11840 });
11841 }
11842
11843 if chunk_lines.peek().is_some() {
11844 if line.len() > 1 && line.front().unwrap().text.is_empty() {
11845 line.pop_front();
11846 }
11847 if line.len() > 1 && line.back().unwrap().text.is_empty() {
11848 line.pop_back();
11849 }
11850
11851 lines.push(mem::take(&mut line));
11852 }
11853 }
11854 }
11855
11856 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11857 return;
11858 };
11859 cx.write_to_clipboard(ClipboardItem::new_string(lines));
11860 }
11861
11862 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11863 &self.inlay_hint_cache
11864 }
11865
11866 pub fn replay_insert_event(
11867 &mut self,
11868 text: &str,
11869 relative_utf16_range: Option<Range<isize>>,
11870 cx: &mut ViewContext<Self>,
11871 ) {
11872 if !self.input_enabled {
11873 cx.emit(EditorEvent::InputIgnored { text: text.into() });
11874 return;
11875 }
11876 if let Some(relative_utf16_range) = relative_utf16_range {
11877 let selections = self.selections.all::<OffsetUtf16>(cx);
11878 self.change_selections(None, cx, |s| {
11879 let new_ranges = selections.into_iter().map(|range| {
11880 let start = OffsetUtf16(
11881 range
11882 .head()
11883 .0
11884 .saturating_add_signed(relative_utf16_range.start),
11885 );
11886 let end = OffsetUtf16(
11887 range
11888 .head()
11889 .0
11890 .saturating_add_signed(relative_utf16_range.end),
11891 );
11892 start..end
11893 });
11894 s.select_ranges(new_ranges);
11895 });
11896 }
11897
11898 self.handle_input(text, cx);
11899 }
11900
11901 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11902 let Some(project) = self.project.as_ref() else {
11903 return false;
11904 };
11905 let project = project.read(cx);
11906
11907 let mut supports = false;
11908 self.buffer().read(cx).for_each_buffer(|buffer| {
11909 if !supports {
11910 supports = project
11911 .language_servers_for_buffer(buffer.read(cx), cx)
11912 .any(
11913 |(_, server)| match server.capabilities().inlay_hint_provider {
11914 Some(lsp::OneOf::Left(enabled)) => enabled,
11915 Some(lsp::OneOf::Right(_)) => true,
11916 None => false,
11917 },
11918 )
11919 }
11920 });
11921 supports
11922 }
11923
11924 pub fn focus(&self, cx: &mut WindowContext) {
11925 cx.focus(&self.focus_handle)
11926 }
11927
11928 pub fn is_focused(&self, cx: &WindowContext) -> bool {
11929 self.focus_handle.is_focused(cx)
11930 }
11931
11932 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11933 cx.emit(EditorEvent::Focused);
11934
11935 if let Some(descendant) = self
11936 .last_focused_descendant
11937 .take()
11938 .and_then(|descendant| descendant.upgrade())
11939 {
11940 cx.focus(&descendant);
11941 } else {
11942 if let Some(blame) = self.blame.as_ref() {
11943 blame.update(cx, GitBlame::focus)
11944 }
11945
11946 self.blink_manager.update(cx, BlinkManager::enable);
11947 self.show_cursor_names(cx);
11948 self.buffer.update(cx, |buffer, cx| {
11949 buffer.finalize_last_transaction(cx);
11950 if self.leader_peer_id.is_none() {
11951 buffer.set_active_selections(
11952 &self.selections.disjoint_anchors(),
11953 self.selections.line_mode,
11954 self.cursor_shape,
11955 cx,
11956 );
11957 }
11958 });
11959 }
11960 }
11961
11962 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
11963 cx.emit(EditorEvent::FocusedIn)
11964 }
11965
11966 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
11967 if event.blurred != self.focus_handle {
11968 self.last_focused_descendant = Some(event.blurred);
11969 }
11970 }
11971
11972 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
11973 self.blink_manager.update(cx, BlinkManager::disable);
11974 self.buffer
11975 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
11976
11977 if let Some(blame) = self.blame.as_ref() {
11978 blame.update(cx, GitBlame::blur)
11979 }
11980 if !self.hover_state.focused(cx) {
11981 hide_hover(self, cx);
11982 }
11983
11984 self.hide_context_menu(cx);
11985 cx.emit(EditorEvent::Blurred);
11986 cx.notify();
11987 }
11988
11989 pub fn register_action<A: Action>(
11990 &mut self,
11991 listener: impl Fn(&A, &mut WindowContext) + 'static,
11992 ) -> Subscription {
11993 let id = self.next_editor_action_id.post_inc();
11994 let listener = Arc::new(listener);
11995 self.editor_actions.borrow_mut().insert(
11996 id,
11997 Box::new(move |cx| {
11998 let cx = cx.window_context();
11999 let listener = listener.clone();
12000 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12001 let action = action.downcast_ref().unwrap();
12002 if phase == DispatchPhase::Bubble {
12003 listener(action, cx)
12004 }
12005 })
12006 }),
12007 );
12008
12009 let editor_actions = self.editor_actions.clone();
12010 Subscription::new(move || {
12011 editor_actions.borrow_mut().remove(&id);
12012 })
12013 }
12014
12015 pub fn file_header_size(&self) -> u32 {
12016 self.file_header_size
12017 }
12018
12019 pub fn revert(
12020 &mut self,
12021 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12022 cx: &mut ViewContext<Self>,
12023 ) {
12024 self.buffer().update(cx, |multi_buffer, cx| {
12025 for (buffer_id, changes) in revert_changes {
12026 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12027 buffer.update(cx, |buffer, cx| {
12028 buffer.edit(
12029 changes.into_iter().map(|(range, text)| {
12030 (range, text.to_string().map(Arc::<str>::from))
12031 }),
12032 None,
12033 cx,
12034 );
12035 });
12036 }
12037 }
12038 });
12039 self.change_selections(None, cx, |selections| selections.refresh());
12040 }
12041
12042 pub fn to_pixel_point(
12043 &mut self,
12044 source: multi_buffer::Anchor,
12045 editor_snapshot: &EditorSnapshot,
12046 cx: &mut ViewContext<Self>,
12047 ) -> Option<gpui::Point<Pixels>> {
12048 let source_point = source.to_display_point(editor_snapshot);
12049 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12050 }
12051
12052 pub fn display_to_pixel_point(
12053 &mut self,
12054 source: DisplayPoint,
12055 editor_snapshot: &EditorSnapshot,
12056 cx: &mut ViewContext<Self>,
12057 ) -> Option<gpui::Point<Pixels>> {
12058 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12059 let text_layout_details = self.text_layout_details(cx);
12060 let scroll_top = text_layout_details
12061 .scroll_anchor
12062 .scroll_position(editor_snapshot)
12063 .y;
12064
12065 if source.row().as_f32() < scroll_top.floor() {
12066 return None;
12067 }
12068 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12069 let source_y = line_height * (source.row().as_f32() - scroll_top);
12070 Some(gpui::Point::new(source_x, source_y))
12071 }
12072
12073 fn gutter_bounds(&self) -> Option<Bounds<Pixels>> {
12074 let bounds = self.last_bounds?;
12075 Some(element::gutter_bounds(bounds, self.gutter_dimensions))
12076 }
12077
12078 pub fn has_active_completions_menu(&self) -> bool {
12079 self.context_menu.read().as_ref().map_or(false, |menu| {
12080 menu.visible() && matches!(menu, ContextMenu::Completions(_))
12081 })
12082 }
12083
12084 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12085 self.addons
12086 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12087 }
12088
12089 pub fn unregister_addon<T: Addon>(&mut self) {
12090 self.addons.remove(&std::any::TypeId::of::<T>());
12091 }
12092
12093 pub fn addon<T: Addon>(&self) -> Option<&T> {
12094 let type_id = std::any::TypeId::of::<T>();
12095 self.addons
12096 .get(&type_id)
12097 .and_then(|item| item.to_any().downcast_ref::<T>())
12098 }
12099}
12100
12101fn hunks_for_selections(
12102 multi_buffer_snapshot: &MultiBufferSnapshot,
12103 selections: &[Selection<Anchor>],
12104) -> Vec<DiffHunk<MultiBufferRow>> {
12105 let buffer_rows_for_selections = selections.iter().map(|selection| {
12106 let head = selection.head();
12107 let tail = selection.tail();
12108 let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
12109 let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
12110 if start > end {
12111 end..start
12112 } else {
12113 start..end
12114 }
12115 });
12116
12117 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12118}
12119
12120pub fn hunks_for_rows(
12121 rows: impl Iterator<Item = Range<MultiBufferRow>>,
12122 multi_buffer_snapshot: &MultiBufferSnapshot,
12123) -> Vec<DiffHunk<MultiBufferRow>> {
12124 let mut hunks = Vec::new();
12125 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12126 HashMap::default();
12127 for selected_multi_buffer_rows in rows {
12128 let query_rows =
12129 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12130 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12131 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12132 // when the caret is just above or just below the deleted hunk.
12133 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12134 let related_to_selection = if allow_adjacent {
12135 hunk.associated_range.overlaps(&query_rows)
12136 || hunk.associated_range.start == query_rows.end
12137 || hunk.associated_range.end == query_rows.start
12138 } else {
12139 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12140 // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12141 hunk.associated_range.overlaps(&selected_multi_buffer_rows)
12142 || selected_multi_buffer_rows.end == hunk.associated_range.start
12143 };
12144 if related_to_selection {
12145 if !processed_buffer_rows
12146 .entry(hunk.buffer_id)
12147 .or_default()
12148 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12149 {
12150 continue;
12151 }
12152 hunks.push(hunk);
12153 }
12154 }
12155 }
12156
12157 hunks
12158}
12159
12160pub trait CollaborationHub {
12161 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12162 fn user_participant_indices<'a>(
12163 &self,
12164 cx: &'a AppContext,
12165 ) -> &'a HashMap<u64, ParticipantIndex>;
12166 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12167}
12168
12169impl CollaborationHub for Model<Project> {
12170 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12171 self.read(cx).collaborators()
12172 }
12173
12174 fn user_participant_indices<'a>(
12175 &self,
12176 cx: &'a AppContext,
12177 ) -> &'a HashMap<u64, ParticipantIndex> {
12178 self.read(cx).user_store().read(cx).participant_indices()
12179 }
12180
12181 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12182 let this = self.read(cx);
12183 let user_ids = this.collaborators().values().map(|c| c.user_id);
12184 this.user_store().read_with(cx, |user_store, cx| {
12185 user_store.participant_names(user_ids, cx)
12186 })
12187 }
12188}
12189
12190pub trait CompletionProvider {
12191 fn completions(
12192 &self,
12193 buffer: &Model<Buffer>,
12194 buffer_position: text::Anchor,
12195 trigger: CompletionContext,
12196 cx: &mut ViewContext<Editor>,
12197 ) -> Task<Result<Vec<Completion>>>;
12198
12199 fn resolve_completions(
12200 &self,
12201 buffer: Model<Buffer>,
12202 completion_indices: Vec<usize>,
12203 completions: Arc<RwLock<Box<[Completion]>>>,
12204 cx: &mut ViewContext<Editor>,
12205 ) -> Task<Result<bool>>;
12206
12207 fn apply_additional_edits_for_completion(
12208 &self,
12209 buffer: Model<Buffer>,
12210 completion: Completion,
12211 push_to_history: bool,
12212 cx: &mut ViewContext<Editor>,
12213 ) -> Task<Result<Option<language::Transaction>>>;
12214
12215 fn is_completion_trigger(
12216 &self,
12217 buffer: &Model<Buffer>,
12218 position: language::Anchor,
12219 text: &str,
12220 trigger_in_words: bool,
12221 cx: &mut ViewContext<Editor>,
12222 ) -> bool;
12223
12224 fn sort_completions(&self) -> bool {
12225 true
12226 }
12227}
12228
12229fn snippet_completions(
12230 project: &Project,
12231 buffer: &Model<Buffer>,
12232 buffer_position: text::Anchor,
12233 cx: &mut AppContext,
12234) -> Vec<Completion> {
12235 let language = buffer.read(cx).language_at(buffer_position);
12236 let language_name = language.as_ref().map(|language| language.lsp_id());
12237 let snippet_store = project.snippets().read(cx);
12238 let snippets = snippet_store.snippets_for(language_name, cx);
12239
12240 if snippets.is_empty() {
12241 return vec![];
12242 }
12243 let snapshot = buffer.read(cx).text_snapshot();
12244 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12245
12246 let mut lines = chunks.lines();
12247 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12248 return vec![];
12249 };
12250
12251 let scope = language.map(|language| language.default_scope());
12252 let mut last_word = line_at
12253 .chars()
12254 .rev()
12255 .take_while(|c| char_kind(&scope, *c) == CharKind::Word)
12256 .collect::<String>();
12257 last_word = last_word.chars().rev().collect();
12258 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12259 let to_lsp = |point: &text::Anchor| {
12260 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12261 point_to_lsp(end)
12262 };
12263 let lsp_end = to_lsp(&buffer_position);
12264 snippets
12265 .into_iter()
12266 .filter_map(|snippet| {
12267 let matching_prefix = snippet
12268 .prefix
12269 .iter()
12270 .find(|prefix| prefix.starts_with(&last_word))?;
12271 let start = as_offset - last_word.len();
12272 let start = snapshot.anchor_before(start);
12273 let range = start..buffer_position;
12274 let lsp_start = to_lsp(&start);
12275 let lsp_range = lsp::Range {
12276 start: lsp_start,
12277 end: lsp_end,
12278 };
12279 Some(Completion {
12280 old_range: range,
12281 new_text: snippet.body.clone(),
12282 label: CodeLabel {
12283 text: matching_prefix.clone(),
12284 runs: vec![],
12285 filter_range: 0..matching_prefix.len(),
12286 },
12287 server_id: LanguageServerId(usize::MAX),
12288 documentation: snippet
12289 .description
12290 .clone()
12291 .map(|description| Documentation::SingleLine(description)),
12292 lsp_completion: lsp::CompletionItem {
12293 label: snippet.prefix.first().unwrap().clone(),
12294 kind: Some(CompletionItemKind::SNIPPET),
12295 label_details: snippet.description.as_ref().map(|description| {
12296 lsp::CompletionItemLabelDetails {
12297 detail: Some(description.clone()),
12298 description: None,
12299 }
12300 }),
12301 insert_text_format: Some(InsertTextFormat::SNIPPET),
12302 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12303 lsp::InsertReplaceEdit {
12304 new_text: snippet.body.clone(),
12305 insert: lsp_range,
12306 replace: lsp_range,
12307 },
12308 )),
12309 filter_text: Some(snippet.body.clone()),
12310 sort_text: Some(char::MAX.to_string()),
12311 ..Default::default()
12312 },
12313 confirm: None,
12314 })
12315 })
12316 .collect()
12317}
12318
12319impl CompletionProvider for Model<Project> {
12320 fn completions(
12321 &self,
12322 buffer: &Model<Buffer>,
12323 buffer_position: text::Anchor,
12324 options: CompletionContext,
12325 cx: &mut ViewContext<Editor>,
12326 ) -> Task<Result<Vec<Completion>>> {
12327 self.update(cx, |project, cx| {
12328 let snippets = snippet_completions(project, buffer, buffer_position, cx);
12329 let project_completions = project.completions(&buffer, buffer_position, options, cx);
12330 cx.background_executor().spawn(async move {
12331 let mut completions = project_completions.await?;
12332 //let snippets = snippets.into_iter().;
12333 completions.extend(snippets);
12334 Ok(completions)
12335 })
12336 })
12337 }
12338
12339 fn resolve_completions(
12340 &self,
12341 buffer: Model<Buffer>,
12342 completion_indices: Vec<usize>,
12343 completions: Arc<RwLock<Box<[Completion]>>>,
12344 cx: &mut ViewContext<Editor>,
12345 ) -> Task<Result<bool>> {
12346 self.update(cx, |project, cx| {
12347 project.resolve_completions(buffer, completion_indices, completions, cx)
12348 })
12349 }
12350
12351 fn apply_additional_edits_for_completion(
12352 &self,
12353 buffer: Model<Buffer>,
12354 completion: Completion,
12355 push_to_history: bool,
12356 cx: &mut ViewContext<Editor>,
12357 ) -> Task<Result<Option<language::Transaction>>> {
12358 self.update(cx, |project, cx| {
12359 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12360 })
12361 }
12362
12363 fn is_completion_trigger(
12364 &self,
12365 buffer: &Model<Buffer>,
12366 position: language::Anchor,
12367 text: &str,
12368 trigger_in_words: bool,
12369 cx: &mut ViewContext<Editor>,
12370 ) -> bool {
12371 if !EditorSettings::get_global(cx).show_completions_on_input {
12372 return false;
12373 }
12374
12375 let mut chars = text.chars();
12376 let char = if let Some(char) = chars.next() {
12377 char
12378 } else {
12379 return false;
12380 };
12381 if chars.next().is_some() {
12382 return false;
12383 }
12384
12385 let buffer = buffer.read(cx);
12386 let scope = buffer.snapshot().language_scope_at(position);
12387 if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
12388 return true;
12389 }
12390
12391 buffer
12392 .completion_triggers()
12393 .iter()
12394 .any(|string| string == text)
12395 }
12396}
12397
12398fn inlay_hint_settings(
12399 location: Anchor,
12400 snapshot: &MultiBufferSnapshot,
12401 cx: &mut ViewContext<'_, Editor>,
12402) -> InlayHintSettings {
12403 let file = snapshot.file_at(location);
12404 let language = snapshot.language_at(location);
12405 let settings = all_language_settings(file, cx);
12406 settings
12407 .language(language.map(|l| l.name()).as_deref())
12408 .inlay_hints
12409}
12410
12411fn consume_contiguous_rows(
12412 contiguous_row_selections: &mut Vec<Selection<Point>>,
12413 selection: &Selection<Point>,
12414 display_map: &DisplaySnapshot,
12415 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12416) -> (MultiBufferRow, MultiBufferRow) {
12417 contiguous_row_selections.push(selection.clone());
12418 let start_row = MultiBufferRow(selection.start.row);
12419 let mut end_row = ending_row(selection, display_map);
12420
12421 while let Some(next_selection) = selections.peek() {
12422 if next_selection.start.row <= end_row.0 {
12423 end_row = ending_row(next_selection, display_map);
12424 contiguous_row_selections.push(selections.next().unwrap().clone());
12425 } else {
12426 break;
12427 }
12428 }
12429 (start_row, end_row)
12430}
12431
12432fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12433 if next_selection.end.column > 0 || next_selection.is_empty() {
12434 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12435 } else {
12436 MultiBufferRow(next_selection.end.row)
12437 }
12438}
12439
12440impl EditorSnapshot {
12441 pub fn remote_selections_in_range<'a>(
12442 &'a self,
12443 range: &'a Range<Anchor>,
12444 collaboration_hub: &dyn CollaborationHub,
12445 cx: &'a AppContext,
12446 ) -> impl 'a + Iterator<Item = RemoteSelection> {
12447 let participant_names = collaboration_hub.user_names(cx);
12448 let participant_indices = collaboration_hub.user_participant_indices(cx);
12449 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12450 let collaborators_by_replica_id = collaborators_by_peer_id
12451 .iter()
12452 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12453 .collect::<HashMap<_, _>>();
12454 self.buffer_snapshot
12455 .selections_in_range(range, false)
12456 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12457 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12458 let participant_index = participant_indices.get(&collaborator.user_id).copied();
12459 let user_name = participant_names.get(&collaborator.user_id).cloned();
12460 Some(RemoteSelection {
12461 replica_id,
12462 selection,
12463 cursor_shape,
12464 line_mode,
12465 participant_index,
12466 peer_id: collaborator.peer_id,
12467 user_name,
12468 })
12469 })
12470 }
12471
12472 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12473 self.display_snapshot.buffer_snapshot.language_at(position)
12474 }
12475
12476 pub fn is_focused(&self) -> bool {
12477 self.is_focused
12478 }
12479
12480 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12481 self.placeholder_text.as_ref()
12482 }
12483
12484 pub fn scroll_position(&self) -> gpui::Point<f32> {
12485 self.scroll_anchor.scroll_position(&self.display_snapshot)
12486 }
12487
12488 fn gutter_dimensions(
12489 &self,
12490 font_id: FontId,
12491 font_size: Pixels,
12492 em_width: Pixels,
12493 max_line_number_width: Pixels,
12494 cx: &AppContext,
12495 ) -> GutterDimensions {
12496 if !self.show_gutter {
12497 return GutterDimensions::default();
12498 }
12499 let descent = cx.text_system().descent(font_id, font_size);
12500
12501 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12502 matches!(
12503 ProjectSettings::get_global(cx).git.git_gutter,
12504 Some(GitGutterSetting::TrackedFiles)
12505 )
12506 });
12507 let gutter_settings = EditorSettings::get_global(cx).gutter;
12508 let show_line_numbers = self
12509 .show_line_numbers
12510 .unwrap_or(gutter_settings.line_numbers);
12511 let line_gutter_width = if show_line_numbers {
12512 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12513 let min_width_for_number_on_gutter = em_width * 4.0;
12514 max_line_number_width.max(min_width_for_number_on_gutter)
12515 } else {
12516 0.0.into()
12517 };
12518
12519 let show_code_actions = self
12520 .show_code_actions
12521 .unwrap_or(gutter_settings.code_actions);
12522
12523 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12524
12525 let git_blame_entries_width = self
12526 .render_git_blame_gutter
12527 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12528
12529 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12530 left_padding += if show_code_actions || show_runnables {
12531 em_width * 3.0
12532 } else if show_git_gutter && show_line_numbers {
12533 em_width * 2.0
12534 } else if show_git_gutter || show_line_numbers {
12535 em_width
12536 } else {
12537 px(0.)
12538 };
12539
12540 let right_padding = if gutter_settings.folds && show_line_numbers {
12541 em_width * 4.0
12542 } else if gutter_settings.folds {
12543 em_width * 3.0
12544 } else if show_line_numbers {
12545 em_width
12546 } else {
12547 px(0.)
12548 };
12549
12550 GutterDimensions {
12551 left_padding,
12552 right_padding,
12553 width: line_gutter_width + left_padding + right_padding,
12554 margin: -descent,
12555 git_blame_entries_width,
12556 }
12557 }
12558
12559 pub fn render_fold_toggle(
12560 &self,
12561 buffer_row: MultiBufferRow,
12562 row_contains_cursor: bool,
12563 editor: View<Editor>,
12564 cx: &mut WindowContext,
12565 ) -> Option<AnyElement> {
12566 let folded = self.is_line_folded(buffer_row);
12567
12568 if let Some(crease) = self
12569 .crease_snapshot
12570 .query_row(buffer_row, &self.buffer_snapshot)
12571 {
12572 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12573 if folded {
12574 editor.update(cx, |editor, cx| {
12575 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12576 });
12577 } else {
12578 editor.update(cx, |editor, cx| {
12579 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12580 });
12581 }
12582 });
12583
12584 Some((crease.render_toggle)(
12585 buffer_row,
12586 folded,
12587 toggle_callback,
12588 cx,
12589 ))
12590 } else if folded
12591 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12592 {
12593 Some(
12594 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12595 .selected(folded)
12596 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12597 if folded {
12598 this.unfold_at(&UnfoldAt { buffer_row }, cx);
12599 } else {
12600 this.fold_at(&FoldAt { buffer_row }, cx);
12601 }
12602 }))
12603 .into_any_element(),
12604 )
12605 } else {
12606 None
12607 }
12608 }
12609
12610 pub fn render_crease_trailer(
12611 &self,
12612 buffer_row: MultiBufferRow,
12613 cx: &mut WindowContext,
12614 ) -> Option<AnyElement> {
12615 let folded = self.is_line_folded(buffer_row);
12616 let crease = self
12617 .crease_snapshot
12618 .query_row(buffer_row, &self.buffer_snapshot)?;
12619 Some((crease.render_trailer)(buffer_row, folded, cx))
12620 }
12621}
12622
12623impl Deref for EditorSnapshot {
12624 type Target = DisplaySnapshot;
12625
12626 fn deref(&self) -> &Self::Target {
12627 &self.display_snapshot
12628 }
12629}
12630
12631#[derive(Clone, Debug, PartialEq, Eq)]
12632pub enum EditorEvent {
12633 InputIgnored {
12634 text: Arc<str>,
12635 },
12636 InputHandled {
12637 utf16_range_to_replace: Option<Range<isize>>,
12638 text: Arc<str>,
12639 },
12640 ExcerptsAdded {
12641 buffer: Model<Buffer>,
12642 predecessor: ExcerptId,
12643 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12644 },
12645 ExcerptsRemoved {
12646 ids: Vec<ExcerptId>,
12647 },
12648 ExcerptsEdited {
12649 ids: Vec<ExcerptId>,
12650 },
12651 ExcerptsExpanded {
12652 ids: Vec<ExcerptId>,
12653 },
12654 BufferEdited,
12655 Edited {
12656 transaction_id: clock::Lamport,
12657 },
12658 Reparsed(BufferId),
12659 Focused,
12660 FocusedIn,
12661 Blurred,
12662 DirtyChanged,
12663 Saved,
12664 TitleChanged,
12665 DiffBaseChanged,
12666 SelectionsChanged {
12667 local: bool,
12668 },
12669 ScrollPositionChanged {
12670 local: bool,
12671 autoscroll: bool,
12672 },
12673 Closed,
12674 TransactionUndone {
12675 transaction_id: clock::Lamport,
12676 },
12677 TransactionBegun {
12678 transaction_id: clock::Lamport,
12679 },
12680}
12681
12682impl EventEmitter<EditorEvent> for Editor {}
12683
12684impl FocusableView for Editor {
12685 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12686 self.focus_handle.clone()
12687 }
12688}
12689
12690impl Render for Editor {
12691 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12692 let settings = ThemeSettings::get_global(cx);
12693
12694 let text_style = match self.mode {
12695 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12696 color: cx.theme().colors().editor_foreground,
12697 font_family: settings.ui_font.family.clone(),
12698 font_features: settings.ui_font.features.clone(),
12699 font_fallbacks: settings.ui_font.fallbacks.clone(),
12700 font_size: rems(0.875).into(),
12701 font_weight: settings.ui_font.weight,
12702 line_height: relative(settings.buffer_line_height.value()),
12703 ..Default::default()
12704 },
12705 EditorMode::Full => TextStyle {
12706 color: cx.theme().colors().editor_foreground,
12707 font_family: settings.buffer_font.family.clone(),
12708 font_features: settings.buffer_font.features.clone(),
12709 font_fallbacks: settings.buffer_font.fallbacks.clone(),
12710 font_size: settings.buffer_font_size(cx).into(),
12711 font_weight: settings.buffer_font.weight,
12712 line_height: relative(settings.buffer_line_height.value()),
12713 ..Default::default()
12714 },
12715 };
12716
12717 let background = match self.mode {
12718 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12719 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12720 EditorMode::Full => cx.theme().colors().editor_background,
12721 };
12722
12723 EditorElement::new(
12724 cx.view(),
12725 EditorStyle {
12726 background,
12727 local_player: cx.theme().players().local(),
12728 text: text_style,
12729 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12730 syntax: cx.theme().syntax().clone(),
12731 status: cx.theme().status().clone(),
12732 inlay_hints_style: HighlightStyle {
12733 color: Some(cx.theme().status().hint),
12734 ..HighlightStyle::default()
12735 },
12736 suggestions_style: HighlightStyle {
12737 color: Some(cx.theme().status().predictive),
12738 ..HighlightStyle::default()
12739 },
12740 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
12741 },
12742 )
12743 }
12744}
12745
12746impl ViewInputHandler for Editor {
12747 fn text_for_range(
12748 &mut self,
12749 range_utf16: Range<usize>,
12750 cx: &mut ViewContext<Self>,
12751 ) -> Option<String> {
12752 Some(
12753 self.buffer
12754 .read(cx)
12755 .read(cx)
12756 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12757 .collect(),
12758 )
12759 }
12760
12761 fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12762 // Prevent the IME menu from appearing when holding down an alphabetic key
12763 // while input is disabled.
12764 if !self.input_enabled {
12765 return None;
12766 }
12767
12768 let range = self.selections.newest::<OffsetUtf16>(cx).range();
12769 Some(range.start.0..range.end.0)
12770 }
12771
12772 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12773 let snapshot = self.buffer.read(cx).read(cx);
12774 let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
12775 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12776 }
12777
12778 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12779 self.clear_highlights::<InputComposition>(cx);
12780 self.ime_transaction.take();
12781 }
12782
12783 fn replace_text_in_range(
12784 &mut self,
12785 range_utf16: Option<Range<usize>>,
12786 text: &str,
12787 cx: &mut ViewContext<Self>,
12788 ) {
12789 if !self.input_enabled {
12790 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12791 return;
12792 }
12793
12794 self.transact(cx, |this, cx| {
12795 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12796 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12797 Some(this.selection_replacement_ranges(range_utf16, cx))
12798 } else {
12799 this.marked_text_ranges(cx)
12800 };
12801
12802 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12803 let newest_selection_id = this.selections.newest_anchor().id;
12804 this.selections
12805 .all::<OffsetUtf16>(cx)
12806 .iter()
12807 .zip(ranges_to_replace.iter())
12808 .find_map(|(selection, range)| {
12809 if selection.id == newest_selection_id {
12810 Some(
12811 (range.start.0 as isize - selection.head().0 as isize)
12812 ..(range.end.0 as isize - selection.head().0 as isize),
12813 )
12814 } else {
12815 None
12816 }
12817 })
12818 });
12819
12820 cx.emit(EditorEvent::InputHandled {
12821 utf16_range_to_replace: range_to_replace,
12822 text: text.into(),
12823 });
12824
12825 if let Some(new_selected_ranges) = new_selected_ranges {
12826 this.change_selections(None, cx, |selections| {
12827 selections.select_ranges(new_selected_ranges)
12828 });
12829 this.backspace(&Default::default(), cx);
12830 }
12831
12832 this.handle_input(text, cx);
12833 });
12834
12835 if let Some(transaction) = self.ime_transaction {
12836 self.buffer.update(cx, |buffer, cx| {
12837 buffer.group_until_transaction(transaction, cx);
12838 });
12839 }
12840
12841 self.unmark_text(cx);
12842 }
12843
12844 fn replace_and_mark_text_in_range(
12845 &mut self,
12846 range_utf16: Option<Range<usize>>,
12847 text: &str,
12848 new_selected_range_utf16: Option<Range<usize>>,
12849 cx: &mut ViewContext<Self>,
12850 ) {
12851 if !self.input_enabled {
12852 return;
12853 }
12854
12855 let transaction = self.transact(cx, |this, cx| {
12856 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12857 let snapshot = this.buffer.read(cx).read(cx);
12858 if let Some(relative_range_utf16) = range_utf16.as_ref() {
12859 for marked_range in &mut marked_ranges {
12860 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12861 marked_range.start.0 += relative_range_utf16.start;
12862 marked_range.start =
12863 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12864 marked_range.end =
12865 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12866 }
12867 }
12868 Some(marked_ranges)
12869 } else if let Some(range_utf16) = range_utf16 {
12870 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12871 Some(this.selection_replacement_ranges(range_utf16, cx))
12872 } else {
12873 None
12874 };
12875
12876 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12877 let newest_selection_id = this.selections.newest_anchor().id;
12878 this.selections
12879 .all::<OffsetUtf16>(cx)
12880 .iter()
12881 .zip(ranges_to_replace.iter())
12882 .find_map(|(selection, range)| {
12883 if selection.id == newest_selection_id {
12884 Some(
12885 (range.start.0 as isize - selection.head().0 as isize)
12886 ..(range.end.0 as isize - selection.head().0 as isize),
12887 )
12888 } else {
12889 None
12890 }
12891 })
12892 });
12893
12894 cx.emit(EditorEvent::InputHandled {
12895 utf16_range_to_replace: range_to_replace,
12896 text: text.into(),
12897 });
12898
12899 if let Some(ranges) = ranges_to_replace {
12900 this.change_selections(None, cx, |s| s.select_ranges(ranges));
12901 }
12902
12903 let marked_ranges = {
12904 let snapshot = this.buffer.read(cx).read(cx);
12905 this.selections
12906 .disjoint_anchors()
12907 .iter()
12908 .map(|selection| {
12909 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12910 })
12911 .collect::<Vec<_>>()
12912 };
12913
12914 if text.is_empty() {
12915 this.unmark_text(cx);
12916 } else {
12917 this.highlight_text::<InputComposition>(
12918 marked_ranges.clone(),
12919 HighlightStyle {
12920 underline: Some(UnderlineStyle {
12921 thickness: px(1.),
12922 color: None,
12923 wavy: false,
12924 }),
12925 ..Default::default()
12926 },
12927 cx,
12928 );
12929 }
12930
12931 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12932 let use_autoclose = this.use_autoclose;
12933 let use_auto_surround = this.use_auto_surround;
12934 this.set_use_autoclose(false);
12935 this.set_use_auto_surround(false);
12936 this.handle_input(text, cx);
12937 this.set_use_autoclose(use_autoclose);
12938 this.set_use_auto_surround(use_auto_surround);
12939
12940 if let Some(new_selected_range) = new_selected_range_utf16 {
12941 let snapshot = this.buffer.read(cx).read(cx);
12942 let new_selected_ranges = marked_ranges
12943 .into_iter()
12944 .map(|marked_range| {
12945 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
12946 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
12947 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
12948 snapshot.clip_offset_utf16(new_start, Bias::Left)
12949 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
12950 })
12951 .collect::<Vec<_>>();
12952
12953 drop(snapshot);
12954 this.change_selections(None, cx, |selections| {
12955 selections.select_ranges(new_selected_ranges)
12956 });
12957 }
12958 });
12959
12960 self.ime_transaction = self.ime_transaction.or(transaction);
12961 if let Some(transaction) = self.ime_transaction {
12962 self.buffer.update(cx, |buffer, cx| {
12963 buffer.group_until_transaction(transaction, cx);
12964 });
12965 }
12966
12967 if self.text_highlights::<InputComposition>(cx).is_none() {
12968 self.ime_transaction.take();
12969 }
12970 }
12971
12972 fn bounds_for_range(
12973 &mut self,
12974 range_utf16: Range<usize>,
12975 element_bounds: gpui::Bounds<Pixels>,
12976 cx: &mut ViewContext<Self>,
12977 ) -> Option<gpui::Bounds<Pixels>> {
12978 let text_layout_details = self.text_layout_details(cx);
12979 let style = &text_layout_details.editor_style;
12980 let font_id = cx.text_system().resolve_font(&style.text.font());
12981 let font_size = style.text.font_size.to_pixels(cx.rem_size());
12982 let line_height = style.text.line_height_in_pixels(cx.rem_size());
12983
12984 let em_width = cx
12985 .text_system()
12986 .typographic_bounds(font_id, font_size, 'm')
12987 .unwrap()
12988 .size
12989 .width;
12990
12991 let snapshot = self.snapshot(cx);
12992 let scroll_position = snapshot.scroll_position();
12993 let scroll_left = scroll_position.x * em_width;
12994
12995 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
12996 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
12997 + self.gutter_dimensions.width;
12998 let y = line_height * (start.row().as_f32() - scroll_position.y);
12999
13000 Some(Bounds {
13001 origin: element_bounds.origin + point(x, y),
13002 size: size(em_width, line_height),
13003 })
13004 }
13005}
13006
13007trait SelectionExt {
13008 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13009 fn spanned_rows(
13010 &self,
13011 include_end_if_at_line_start: bool,
13012 map: &DisplaySnapshot,
13013 ) -> Range<MultiBufferRow>;
13014}
13015
13016impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
13017 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
13018 let start = self
13019 .start
13020 .to_point(&map.buffer_snapshot)
13021 .to_display_point(map);
13022 let end = self
13023 .end
13024 .to_point(&map.buffer_snapshot)
13025 .to_display_point(map);
13026 if self.reversed {
13027 end..start
13028 } else {
13029 start..end
13030 }
13031 }
13032
13033 fn spanned_rows(
13034 &self,
13035 include_end_if_at_line_start: bool,
13036 map: &DisplaySnapshot,
13037 ) -> Range<MultiBufferRow> {
13038 let start = self.start.to_point(&map.buffer_snapshot);
13039 let mut end = self.end.to_point(&map.buffer_snapshot);
13040 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
13041 end.row -= 1;
13042 }
13043
13044 let buffer_start = map.prev_line_boundary(start).0;
13045 let buffer_end = map.next_line_boundary(end).0;
13046 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
13047 }
13048}
13049
13050impl<T: InvalidationRegion> InvalidationStack<T> {
13051 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
13052 where
13053 S: Clone + ToOffset,
13054 {
13055 while let Some(region) = self.last() {
13056 let all_selections_inside_invalidation_ranges =
13057 if selections.len() == region.ranges().len() {
13058 selections
13059 .iter()
13060 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
13061 .all(|(selection, invalidation_range)| {
13062 let head = selection.head().to_offset(buffer);
13063 invalidation_range.start <= head && invalidation_range.end >= head
13064 })
13065 } else {
13066 false
13067 };
13068
13069 if all_selections_inside_invalidation_ranges {
13070 break;
13071 } else {
13072 self.pop();
13073 }
13074 }
13075 }
13076}
13077
13078impl<T> Default for InvalidationStack<T> {
13079 fn default() -> Self {
13080 Self(Default::default())
13081 }
13082}
13083
13084impl<T> Deref for InvalidationStack<T> {
13085 type Target = Vec<T>;
13086
13087 fn deref(&self) -> &Self::Target {
13088 &self.0
13089 }
13090}
13091
13092impl<T> DerefMut for InvalidationStack<T> {
13093 fn deref_mut(&mut self) -> &mut Self::Target {
13094 &mut self.0
13095 }
13096}
13097
13098impl InvalidationRegion for SnippetState {
13099 fn ranges(&self) -> &[Range<Anchor>] {
13100 &self.ranges[self.active_index]
13101 }
13102}
13103
13104pub fn diagnostic_block_renderer(
13105 diagnostic: Diagnostic,
13106 max_message_rows: Option<u8>,
13107 allow_closing: bool,
13108 _is_valid: bool,
13109) -> RenderBlock {
13110 let (text_without_backticks, code_ranges) =
13111 highlight_diagnostic_message(&diagnostic, max_message_rows);
13112
13113 Box::new(move |cx: &mut BlockContext| {
13114 let group_id: SharedString = cx.block_id.to_string().into();
13115
13116 let mut text_style = cx.text_style().clone();
13117 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13118 let theme_settings = ThemeSettings::get_global(cx);
13119 text_style.font_family = theme_settings.buffer_font.family.clone();
13120 text_style.font_style = theme_settings.buffer_font.style;
13121 text_style.font_features = theme_settings.buffer_font.features.clone();
13122 text_style.font_weight = theme_settings.buffer_font.weight;
13123
13124 let multi_line_diagnostic = diagnostic.message.contains('\n');
13125
13126 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13127 if multi_line_diagnostic {
13128 v_flex()
13129 } else {
13130 h_flex()
13131 }
13132 .when(allow_closing, |div| {
13133 div.children(diagnostic.is_primary.then(|| {
13134 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13135 .icon_color(Color::Muted)
13136 .size(ButtonSize::Compact)
13137 .style(ButtonStyle::Transparent)
13138 .visible_on_hover(group_id.clone())
13139 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13140 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13141 }))
13142 })
13143 .child(
13144 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13145 .icon_color(Color::Muted)
13146 .size(ButtonSize::Compact)
13147 .style(ButtonStyle::Transparent)
13148 .visible_on_hover(group_id.clone())
13149 .on_click({
13150 let message = diagnostic.message.clone();
13151 move |_click, cx| {
13152 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13153 }
13154 })
13155 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13156 )
13157 };
13158
13159 let icon_size = buttons(&diagnostic, cx.block_id)
13160 .into_any_element()
13161 .layout_as_root(AvailableSpace::min_size(), cx);
13162
13163 h_flex()
13164 .id(cx.block_id)
13165 .group(group_id.clone())
13166 .relative()
13167 .size_full()
13168 .pl(cx.gutter_dimensions.width)
13169 .w(cx.max_width + cx.gutter_dimensions.width)
13170 .child(
13171 div()
13172 .flex()
13173 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13174 .flex_shrink(),
13175 )
13176 .child(buttons(&diagnostic, cx.block_id))
13177 .child(div().flex().flex_shrink_0().child(
13178 StyledText::new(text_without_backticks.clone()).with_highlights(
13179 &text_style,
13180 code_ranges.iter().map(|range| {
13181 (
13182 range.clone(),
13183 HighlightStyle {
13184 font_weight: Some(FontWeight::BOLD),
13185 ..Default::default()
13186 },
13187 )
13188 }),
13189 ),
13190 ))
13191 .into_any_element()
13192 })
13193}
13194
13195pub fn highlight_diagnostic_message(
13196 diagnostic: &Diagnostic,
13197 mut max_message_rows: Option<u8>,
13198) -> (SharedString, Vec<Range<usize>>) {
13199 let mut text_without_backticks = String::new();
13200 let mut code_ranges = Vec::new();
13201
13202 if let Some(source) = &diagnostic.source {
13203 text_without_backticks.push_str(&source);
13204 code_ranges.push(0..source.len());
13205 text_without_backticks.push_str(": ");
13206 }
13207
13208 let mut prev_offset = 0;
13209 let mut in_code_block = false;
13210 let has_row_limit = max_message_rows.is_some();
13211 let mut newline_indices = diagnostic
13212 .message
13213 .match_indices('\n')
13214 .filter(|_| has_row_limit)
13215 .map(|(ix, _)| ix)
13216 .fuse()
13217 .peekable();
13218
13219 for (quote_ix, _) in diagnostic
13220 .message
13221 .match_indices('`')
13222 .chain([(diagnostic.message.len(), "")])
13223 {
13224 let mut first_newline_ix = None;
13225 let mut last_newline_ix = None;
13226 while let Some(newline_ix) = newline_indices.peek() {
13227 if *newline_ix < quote_ix {
13228 if first_newline_ix.is_none() {
13229 first_newline_ix = Some(*newline_ix);
13230 }
13231 last_newline_ix = Some(*newline_ix);
13232
13233 if let Some(rows_left) = &mut max_message_rows {
13234 if *rows_left == 0 {
13235 break;
13236 } else {
13237 *rows_left -= 1;
13238 }
13239 }
13240 let _ = newline_indices.next();
13241 } else {
13242 break;
13243 }
13244 }
13245 let prev_len = text_without_backticks.len();
13246 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
13247 text_without_backticks.push_str(new_text);
13248 if in_code_block {
13249 code_ranges.push(prev_len..text_without_backticks.len());
13250 }
13251 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13252 in_code_block = !in_code_block;
13253 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13254 text_without_backticks.push_str("...");
13255 break;
13256 }
13257 }
13258
13259 (text_without_backticks.into(), code_ranges)
13260}
13261
13262fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13263 match severity {
13264 DiagnosticSeverity::ERROR => colors.error,
13265 DiagnosticSeverity::WARNING => colors.warning,
13266 DiagnosticSeverity::INFORMATION => colors.info,
13267 DiagnosticSeverity::HINT => colors.info,
13268 _ => colors.ignored,
13269 }
13270}
13271
13272pub fn styled_runs_for_code_label<'a>(
13273 label: &'a CodeLabel,
13274 syntax_theme: &'a theme::SyntaxTheme,
13275) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13276 let fade_out = HighlightStyle {
13277 fade_out: Some(0.35),
13278 ..Default::default()
13279 };
13280
13281 let mut prev_end = label.filter_range.end;
13282 label
13283 .runs
13284 .iter()
13285 .enumerate()
13286 .flat_map(move |(ix, (range, highlight_id))| {
13287 let style = if let Some(style) = highlight_id.style(syntax_theme) {
13288 style
13289 } else {
13290 return Default::default();
13291 };
13292 let mut muted_style = style;
13293 muted_style.highlight(fade_out);
13294
13295 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13296 if range.start >= label.filter_range.end {
13297 if range.start > prev_end {
13298 runs.push((prev_end..range.start, fade_out));
13299 }
13300 runs.push((range.clone(), muted_style));
13301 } else if range.end <= label.filter_range.end {
13302 runs.push((range.clone(), style));
13303 } else {
13304 runs.push((range.start..label.filter_range.end, style));
13305 runs.push((label.filter_range.end..range.end, muted_style));
13306 }
13307 prev_end = cmp::max(prev_end, range.end);
13308
13309 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13310 runs.push((prev_end..label.text.len(), fade_out));
13311 }
13312
13313 runs
13314 })
13315}
13316
13317pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13318 let mut prev_index = 0;
13319 let mut prev_codepoint: Option<char> = None;
13320 text.char_indices()
13321 .chain([(text.len(), '\0')])
13322 .filter_map(move |(index, codepoint)| {
13323 let prev_codepoint = prev_codepoint.replace(codepoint)?;
13324 let is_boundary = index == text.len()
13325 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13326 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13327 if is_boundary {
13328 let chunk = &text[prev_index..index];
13329 prev_index = index;
13330 Some(chunk)
13331 } else {
13332 None
13333 }
13334 })
13335}
13336
13337pub trait RangeToAnchorExt: Sized {
13338 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13339
13340 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13341 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13342 anchor_range.start.to_display_point(&snapshot)..anchor_range.end.to_display_point(&snapshot)
13343 }
13344}
13345
13346impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13347 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13348 let start_offset = self.start.to_offset(snapshot);
13349 let end_offset = self.end.to_offset(snapshot);
13350 if start_offset == end_offset {
13351 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13352 } else {
13353 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13354 }
13355 }
13356}
13357
13358pub trait RowExt {
13359 fn as_f32(&self) -> f32;
13360
13361 fn next_row(&self) -> Self;
13362
13363 fn previous_row(&self) -> Self;
13364
13365 fn minus(&self, other: Self) -> u32;
13366}
13367
13368impl RowExt for DisplayRow {
13369 fn as_f32(&self) -> f32 {
13370 self.0 as f32
13371 }
13372
13373 fn next_row(&self) -> Self {
13374 Self(self.0 + 1)
13375 }
13376
13377 fn previous_row(&self) -> Self {
13378 Self(self.0.saturating_sub(1))
13379 }
13380
13381 fn minus(&self, other: Self) -> u32 {
13382 self.0 - other.0
13383 }
13384}
13385
13386impl RowExt for MultiBufferRow {
13387 fn as_f32(&self) -> f32 {
13388 self.0 as f32
13389 }
13390
13391 fn next_row(&self) -> Self {
13392 Self(self.0 + 1)
13393 }
13394
13395 fn previous_row(&self) -> Self {
13396 Self(self.0.saturating_sub(1))
13397 }
13398
13399 fn minus(&self, other: Self) -> u32 {
13400 self.0 - other.0
13401 }
13402}
13403
13404trait RowRangeExt {
13405 type Row;
13406
13407 fn len(&self) -> usize;
13408
13409 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13410}
13411
13412impl RowRangeExt for Range<MultiBufferRow> {
13413 type Row = MultiBufferRow;
13414
13415 fn len(&self) -> usize {
13416 (self.end.0 - self.start.0) as usize
13417 }
13418
13419 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13420 (self.start.0..self.end.0).map(MultiBufferRow)
13421 }
13422}
13423
13424impl RowRangeExt for Range<DisplayRow> {
13425 type Row = DisplayRow;
13426
13427 fn len(&self) -> usize {
13428 (self.end.0 - self.start.0) as usize
13429 }
13430
13431 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13432 (self.start.0..self.end.0).map(DisplayRow)
13433 }
13434}
13435
13436fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13437 if hunk.diff_base_byte_range.is_empty() {
13438 DiffHunkStatus::Added
13439 } else if hunk.associated_range.is_empty() {
13440 DiffHunkStatus::Removed
13441 } else {
13442 DiffHunkStatus::Modified
13443 }
13444}
13445
13446/// If select range has more than one line, we
13447/// just point the cursor to range.start.
13448fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
13449 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
13450 range
13451 } else {
13452 range.start..range.start
13453 }
13454}