1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blame_entry_tooltip;
17mod blink_manager;
18mod clangd_ext;
19mod debounced_delay;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod hunk_diff;
29mod indent_guides;
30mod inlay_hint_cache;
31mod inline_completion_provider;
32pub mod items;
33mod linked_editing_ranges;
34mod lsp_ext;
35mod mouse_context_menu;
36pub mod movement;
37mod persistence;
38mod rust_analyzer_ext;
39pub mod scroll;
40mod selections_collection;
41pub mod tasks;
42
43#[cfg(test)]
44mod editor_tests;
45mod signature_help;
46#[cfg(any(test, feature = "test-support"))]
47pub mod test;
48
49use ::git::diff::{DiffHunk, DiffHunkStatus};
50use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
51pub(crate) use actions::*;
52use aho_corasick::AhoCorasick;
53use anyhow::{anyhow, Context as _, Result};
54use blink_manager::BlinkManager;
55use client::{Collaborator, ParticipantIndex};
56use clock::ReplicaId;
57use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
58use convert_case::{Case, Casing};
59use debounced_delay::DebouncedDelay;
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine};
63pub use editor_settings_controls::*;
64use element::LineWithInvisibles;
65pub use element::{
66 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
67};
68use futures::FutureExt;
69use fuzzy::{StringMatch, StringMatchCandidate};
70use git::blame::GitBlame;
71use git::diff_hunk_to_display;
72use gpui::{
73 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
74 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
75 ClipboardItem, Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle,
76 FocusOutEvent, FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText,
77 KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
78 SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
79 UTF16Selection, UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler,
80 VisualContext, WeakFocusHandle, WeakView, WindowContext,
81};
82use highlight_matching_bracket::refresh_matching_bracket_highlights;
83use hover_popover::{hide_hover, HoverState};
84use hunk_diff::ExpandedHunks;
85pub(crate) use hunk_diff::HoveredHunk;
86use indent_guides::ActiveIndentGuidesState;
87use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
88pub use inline_completion_provider::*;
89pub use items::MAX_TAB_TITLE_LEN;
90use itertools::Itertools;
91use language::{
92 char_kind,
93 language_settings::{self, all_language_settings, InlayHintSettings},
94 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
95 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
96 Point, Selection, SelectionGoal, TransactionId,
97};
98use language::{point_to_lsp, BufferRow, Runnable, RunnableRange};
99use linked_editing_ranges::refresh_linked_ranges;
100use task::{ResolvedTask, TaskTemplate, TaskVariables};
101
102use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
103pub use lsp::CompletionContext;
104use lsp::{
105 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
106 LanguageServerId,
107};
108use mouse_context_menu::MouseContextMenu;
109use movement::TextLayoutDetails;
110pub use multi_buffer::{
111 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
112 ToPoint,
113};
114use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
115use ordered_float::OrderedFloat;
116use parking_lot::{Mutex, RwLock};
117use project::project_settings::{GitGutterSetting, ProjectSettings};
118use project::{
119 CodeAction, Completion, CompletionIntent, FormatTrigger, Item, Location, Project, ProjectPath,
120 ProjectTransaction, TaskSourceKind, WorktreeId,
121};
122use rand::prelude::*;
123use rpc::{proto::*, ErrorExt};
124use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
125use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
126use serde::{Deserialize, Serialize};
127use settings::{update_settings_file, Settings, SettingsStore};
128use smallvec::SmallVec;
129use snippet::Snippet;
130use std::{
131 any::TypeId,
132 borrow::Cow,
133 cell::RefCell,
134 cmp::{self, Ordering, Reverse},
135 mem,
136 num::NonZeroU32,
137 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
138 path::{Path, PathBuf},
139 rc::Rc,
140 sync::Arc,
141 time::{Duration, Instant},
142};
143pub use sum_tree::Bias;
144use sum_tree::TreeMap;
145use text::{BufferId, OffsetUtf16, Rope};
146use theme::{
147 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
148 ThemeColors, ThemeSettings,
149};
150use ui::{
151 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
152 ListItem, Popover, Tooltip,
153};
154use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
155use workspace::item::{ItemHandle, PreviewTabsSettings};
156use workspace::notifications::{DetachAndPromptErr, NotificationId};
157use workspace::{
158 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
159};
160use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
161
162use crate::hover_links::find_url;
163use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
164
165pub const FILE_HEADER_HEIGHT: u32 = 1;
166pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
167pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
168pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
169const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
170const MAX_LINE_LEN: usize = 1024;
171const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
172const MAX_SELECTION_HISTORY_LEN: usize = 1024;
173pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
174#[doc(hidden)]
175pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
176#[doc(hidden)]
177pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
178
179pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
180pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
181
182pub fn render_parsed_markdown(
183 element_id: impl Into<ElementId>,
184 parsed: &language::ParsedMarkdown,
185 editor_style: &EditorStyle,
186 workspace: Option<WeakView<Workspace>>,
187 cx: &mut WindowContext,
188) -> InteractiveText {
189 let code_span_background_color = cx
190 .theme()
191 .colors()
192 .editor_document_highlight_read_background;
193
194 let highlights = gpui::combine_highlights(
195 parsed.highlights.iter().filter_map(|(range, highlight)| {
196 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
197 Some((range.clone(), highlight))
198 }),
199 parsed
200 .regions
201 .iter()
202 .zip(&parsed.region_ranges)
203 .filter_map(|(region, range)| {
204 if region.code {
205 Some((
206 range.clone(),
207 HighlightStyle {
208 background_color: Some(code_span_background_color),
209 ..Default::default()
210 },
211 ))
212 } else {
213 None
214 }
215 }),
216 );
217
218 let mut links = Vec::new();
219 let mut link_ranges = Vec::new();
220 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
221 if let Some(link) = region.link.clone() {
222 links.push(link);
223 link_ranges.push(range.clone());
224 }
225 }
226
227 InteractiveText::new(
228 element_id,
229 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
230 )
231 .on_click(link_ranges, move |clicked_range_ix, cx| {
232 match &links[clicked_range_ix] {
233 markdown::Link::Web { url } => cx.open_url(url),
234 markdown::Link::Path { path } => {
235 if let Some(workspace) = &workspace {
236 _ = workspace.update(cx, |workspace, cx| {
237 workspace.open_abs_path(path.clone(), false, cx).detach();
238 });
239 }
240 }
241 }
242 })
243}
244
245#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
246pub(crate) enum InlayId {
247 Suggestion(usize),
248 Hint(usize),
249}
250
251impl InlayId {
252 fn id(&self) -> usize {
253 match self {
254 Self::Suggestion(id) => *id,
255 Self::Hint(id) => *id,
256 }
257 }
258}
259
260enum DiffRowHighlight {}
261enum DocumentHighlightRead {}
262enum DocumentHighlightWrite {}
263enum InputComposition {}
264
265#[derive(Copy, Clone, PartialEq, Eq)]
266pub enum Direction {
267 Prev,
268 Next,
269}
270
271#[derive(Debug, Copy, Clone, PartialEq, Eq)]
272pub enum Navigated {
273 Yes,
274 No,
275}
276
277impl Navigated {
278 pub fn from_bool(yes: bool) -> Navigated {
279 if yes {
280 Navigated::Yes
281 } else {
282 Navigated::No
283 }
284 }
285}
286
287pub fn init_settings(cx: &mut AppContext) {
288 EditorSettings::register(cx);
289}
290
291pub fn init(cx: &mut AppContext) {
292 init_settings(cx);
293
294 workspace::register_project_item::<Editor>(cx);
295 workspace::FollowableViewRegistry::register::<Editor>(cx);
296 workspace::register_serializable_item::<Editor>(cx);
297
298 cx.observe_new_views(
299 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
300 workspace.register_action(Editor::new_file);
301 workspace.register_action(Editor::new_file_vertical);
302 workspace.register_action(Editor::new_file_horizontal);
303 },
304 )
305 .detach();
306
307 cx.on_action(move |_: &workspace::NewFile, cx| {
308 let app_state = workspace::AppState::global(cx);
309 if let Some(app_state) = app_state.upgrade() {
310 workspace::open_new(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_override: Option<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_override: None,
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 toggle_inline_completions(
2309 &mut self,
2310 _: &ToggleInlineCompletions,
2311 cx: &mut ViewContext<Self>,
2312 ) {
2313 if self.show_inline_completions_override.is_some() {
2314 self.set_show_inline_completions(None, cx);
2315 } else {
2316 let cursor = self.selections.newest_anchor().head();
2317 if let Some((buffer, cursor_buffer_position)) =
2318 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2319 {
2320 let show_inline_completions =
2321 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2322 self.set_show_inline_completions(Some(show_inline_completions), cx);
2323 }
2324 }
2325 }
2326
2327 pub fn set_show_inline_completions(
2328 &mut self,
2329 show_inline_completions: Option<bool>,
2330 cx: &mut ViewContext<Self>,
2331 ) {
2332 self.show_inline_completions_override = show_inline_completions;
2333 self.refresh_inline_completion(false, true, cx);
2334 }
2335
2336 fn should_show_inline_completions(
2337 &self,
2338 buffer: &Model<Buffer>,
2339 buffer_position: language::Anchor,
2340 cx: &AppContext,
2341 ) -> bool {
2342 if let Some(provider) = self.inline_completion_provider() {
2343 if let Some(show_inline_completions) = self.show_inline_completions_override {
2344 show_inline_completions
2345 } else {
2346 self.mode == EditorMode::Full && provider.is_enabled(&buffer, buffer_position, cx)
2347 }
2348 } else {
2349 false
2350 }
2351 }
2352
2353 pub fn set_use_modal_editing(&mut self, to: bool) {
2354 self.use_modal_editing = to;
2355 }
2356
2357 pub fn use_modal_editing(&self) -> bool {
2358 self.use_modal_editing
2359 }
2360
2361 fn selections_did_change(
2362 &mut self,
2363 local: bool,
2364 old_cursor_position: &Anchor,
2365 show_completions: bool,
2366 cx: &mut ViewContext<Self>,
2367 ) {
2368 cx.invalidate_character_coordinates();
2369
2370 // Copy selections to primary selection buffer
2371 #[cfg(target_os = "linux")]
2372 if local {
2373 let selections = self.selections.all::<usize>(cx);
2374 let buffer_handle = self.buffer.read(cx).read(cx);
2375
2376 let mut text = String::new();
2377 for (index, selection) in selections.iter().enumerate() {
2378 let text_for_selection = buffer_handle
2379 .text_for_range(selection.start..selection.end)
2380 .collect::<String>();
2381
2382 text.push_str(&text_for_selection);
2383 if index != selections.len() - 1 {
2384 text.push('\n');
2385 }
2386 }
2387
2388 if !text.is_empty() {
2389 cx.write_to_primary(ClipboardItem::new_string(text));
2390 }
2391 }
2392
2393 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2394 self.buffer.update(cx, |buffer, cx| {
2395 buffer.set_active_selections(
2396 &self.selections.disjoint_anchors(),
2397 self.selections.line_mode,
2398 self.cursor_shape,
2399 cx,
2400 )
2401 });
2402 }
2403 let display_map = self
2404 .display_map
2405 .update(cx, |display_map, cx| display_map.snapshot(cx));
2406 let buffer = &display_map.buffer_snapshot;
2407 self.add_selections_state = None;
2408 self.select_next_state = None;
2409 self.select_prev_state = None;
2410 self.select_larger_syntax_node_stack.clear();
2411 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2412 self.snippet_stack
2413 .invalidate(&self.selections.disjoint_anchors(), buffer);
2414 self.take_rename(false, cx);
2415
2416 let new_cursor_position = self.selections.newest_anchor().head();
2417
2418 self.push_to_nav_history(
2419 *old_cursor_position,
2420 Some(new_cursor_position.to_point(buffer)),
2421 cx,
2422 );
2423
2424 if local {
2425 let new_cursor_position = self.selections.newest_anchor().head();
2426 let mut context_menu = self.context_menu.write();
2427 let completion_menu = match context_menu.as_ref() {
2428 Some(ContextMenu::Completions(menu)) => Some(menu),
2429
2430 _ => {
2431 *context_menu = None;
2432 None
2433 }
2434 };
2435
2436 if let Some(completion_menu) = completion_menu {
2437 let cursor_position = new_cursor_position.to_offset(buffer);
2438 let (word_range, kind) = buffer.surrounding_word(completion_menu.initial_position);
2439 if kind == Some(CharKind::Word)
2440 && word_range.to_inclusive().contains(&cursor_position)
2441 {
2442 let mut completion_menu = completion_menu.clone();
2443 drop(context_menu);
2444
2445 let query = Self::completion_query(buffer, cursor_position);
2446 cx.spawn(move |this, mut cx| async move {
2447 completion_menu
2448 .filter(query.as_deref(), cx.background_executor().clone())
2449 .await;
2450
2451 this.update(&mut cx, |this, cx| {
2452 let mut context_menu = this.context_menu.write();
2453 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2454 return;
2455 };
2456
2457 if menu.id > completion_menu.id {
2458 return;
2459 }
2460
2461 *context_menu = Some(ContextMenu::Completions(completion_menu));
2462 drop(context_menu);
2463 cx.notify();
2464 })
2465 })
2466 .detach();
2467
2468 if show_completions {
2469 self.show_completions(&ShowCompletions { trigger: None }, cx);
2470 }
2471 } else {
2472 drop(context_menu);
2473 self.hide_context_menu(cx);
2474 }
2475 } else {
2476 drop(context_menu);
2477 }
2478
2479 hide_hover(self, cx);
2480
2481 if old_cursor_position.to_display_point(&display_map).row()
2482 != new_cursor_position.to_display_point(&display_map).row()
2483 {
2484 self.available_code_actions.take();
2485 }
2486 self.refresh_code_actions(cx);
2487 self.refresh_document_highlights(cx);
2488 refresh_matching_bracket_highlights(self, cx);
2489 self.discard_inline_completion(false, cx);
2490 linked_editing_ranges::refresh_linked_ranges(self, cx);
2491 if self.git_blame_inline_enabled {
2492 self.start_inline_blame_timer(cx);
2493 }
2494 }
2495
2496 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2497 cx.emit(EditorEvent::SelectionsChanged { local });
2498
2499 if self.selections.disjoint_anchors().len() == 1 {
2500 cx.emit(SearchEvent::ActiveMatchChanged)
2501 }
2502 cx.notify();
2503 }
2504
2505 pub fn change_selections<R>(
2506 &mut self,
2507 autoscroll: Option<Autoscroll>,
2508 cx: &mut ViewContext<Self>,
2509 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2510 ) -> R {
2511 self.change_selections_inner(autoscroll, true, cx, change)
2512 }
2513
2514 pub fn change_selections_inner<R>(
2515 &mut self,
2516 autoscroll: Option<Autoscroll>,
2517 request_completions: bool,
2518 cx: &mut ViewContext<Self>,
2519 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2520 ) -> R {
2521 let old_cursor_position = self.selections.newest_anchor().head();
2522 self.push_to_selection_history();
2523
2524 let (changed, result) = self.selections.change_with(cx, change);
2525
2526 if changed {
2527 if let Some(autoscroll) = autoscroll {
2528 self.request_autoscroll(autoscroll, cx);
2529 }
2530 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2531
2532 if self.should_open_signature_help_automatically(
2533 &old_cursor_position,
2534 self.signature_help_state.backspace_pressed(),
2535 cx,
2536 ) {
2537 self.show_signature_help(&ShowSignatureHelp, cx);
2538 }
2539 self.signature_help_state.set_backspace_pressed(false);
2540 }
2541
2542 result
2543 }
2544
2545 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2546 where
2547 I: IntoIterator<Item = (Range<S>, T)>,
2548 S: ToOffset,
2549 T: Into<Arc<str>>,
2550 {
2551 if self.read_only(cx) {
2552 return;
2553 }
2554
2555 self.buffer
2556 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2557 }
2558
2559 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2560 where
2561 I: IntoIterator<Item = (Range<S>, T)>,
2562 S: ToOffset,
2563 T: Into<Arc<str>>,
2564 {
2565 if self.read_only(cx) {
2566 return;
2567 }
2568
2569 self.buffer.update(cx, |buffer, cx| {
2570 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2571 });
2572 }
2573
2574 pub fn edit_with_block_indent<I, S, T>(
2575 &mut self,
2576 edits: I,
2577 original_indent_columns: Vec<u32>,
2578 cx: &mut ViewContext<Self>,
2579 ) where
2580 I: IntoIterator<Item = (Range<S>, T)>,
2581 S: ToOffset,
2582 T: Into<Arc<str>>,
2583 {
2584 if self.read_only(cx) {
2585 return;
2586 }
2587
2588 self.buffer.update(cx, |buffer, cx| {
2589 buffer.edit(
2590 edits,
2591 Some(AutoindentMode::Block {
2592 original_indent_columns,
2593 }),
2594 cx,
2595 )
2596 });
2597 }
2598
2599 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2600 self.hide_context_menu(cx);
2601
2602 match phase {
2603 SelectPhase::Begin {
2604 position,
2605 add,
2606 click_count,
2607 } => self.begin_selection(position, add, click_count, cx),
2608 SelectPhase::BeginColumnar {
2609 position,
2610 goal_column,
2611 reset,
2612 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2613 SelectPhase::Extend {
2614 position,
2615 click_count,
2616 } => self.extend_selection(position, click_count, cx),
2617 SelectPhase::Update {
2618 position,
2619 goal_column,
2620 scroll_delta,
2621 } => self.update_selection(position, goal_column, scroll_delta, cx),
2622 SelectPhase::End => self.end_selection(cx),
2623 }
2624 }
2625
2626 fn extend_selection(
2627 &mut self,
2628 position: DisplayPoint,
2629 click_count: usize,
2630 cx: &mut ViewContext<Self>,
2631 ) {
2632 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2633 let tail = self.selections.newest::<usize>(cx).tail();
2634 self.begin_selection(position, false, click_count, cx);
2635
2636 let position = position.to_offset(&display_map, Bias::Left);
2637 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2638
2639 let mut pending_selection = self
2640 .selections
2641 .pending_anchor()
2642 .expect("extend_selection not called with pending selection");
2643 if position >= tail {
2644 pending_selection.start = tail_anchor;
2645 } else {
2646 pending_selection.end = tail_anchor;
2647 pending_selection.reversed = true;
2648 }
2649
2650 let mut pending_mode = self.selections.pending_mode().unwrap();
2651 match &mut pending_mode {
2652 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2653 _ => {}
2654 }
2655
2656 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2657 s.set_pending(pending_selection, pending_mode)
2658 });
2659 }
2660
2661 fn begin_selection(
2662 &mut self,
2663 position: DisplayPoint,
2664 add: bool,
2665 click_count: usize,
2666 cx: &mut ViewContext<Self>,
2667 ) {
2668 if !self.focus_handle.is_focused(cx) {
2669 self.last_focused_descendant = None;
2670 cx.focus(&self.focus_handle);
2671 }
2672
2673 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2674 let buffer = &display_map.buffer_snapshot;
2675 let newest_selection = self.selections.newest_anchor().clone();
2676 let position = display_map.clip_point(position, Bias::Left);
2677
2678 let start;
2679 let end;
2680 let mode;
2681 let auto_scroll;
2682 match click_count {
2683 1 => {
2684 start = buffer.anchor_before(position.to_point(&display_map));
2685 end = start;
2686 mode = SelectMode::Character;
2687 auto_scroll = true;
2688 }
2689 2 => {
2690 let range = movement::surrounding_word(&display_map, position);
2691 start = buffer.anchor_before(range.start.to_point(&display_map));
2692 end = buffer.anchor_before(range.end.to_point(&display_map));
2693 mode = SelectMode::Word(start..end);
2694 auto_scroll = true;
2695 }
2696 3 => {
2697 let position = display_map
2698 .clip_point(position, Bias::Left)
2699 .to_point(&display_map);
2700 let line_start = display_map.prev_line_boundary(position).0;
2701 let next_line_start = buffer.clip_point(
2702 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2703 Bias::Left,
2704 );
2705 start = buffer.anchor_before(line_start);
2706 end = buffer.anchor_before(next_line_start);
2707 mode = SelectMode::Line(start..end);
2708 auto_scroll = true;
2709 }
2710 _ => {
2711 start = buffer.anchor_before(0);
2712 end = buffer.anchor_before(buffer.len());
2713 mode = SelectMode::All;
2714 auto_scroll = false;
2715 }
2716 }
2717
2718 let point_to_delete: Option<usize> = {
2719 let selected_points: Vec<Selection<Point>> =
2720 self.selections.disjoint_in_range(start..end, cx);
2721
2722 if !add || click_count > 1 {
2723 None
2724 } else if selected_points.len() > 0 {
2725 Some(selected_points[0].id)
2726 } else {
2727 let clicked_point_already_selected =
2728 self.selections.disjoint.iter().find(|selection| {
2729 selection.start.to_point(buffer) == start.to_point(buffer)
2730 || selection.end.to_point(buffer) == end.to_point(buffer)
2731 });
2732
2733 if let Some(selection) = clicked_point_already_selected {
2734 Some(selection.id)
2735 } else {
2736 None
2737 }
2738 }
2739 };
2740
2741 let selections_count = self.selections.count();
2742
2743 self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
2744 if let Some(point_to_delete) = point_to_delete {
2745 s.delete(point_to_delete);
2746
2747 if selections_count == 1 {
2748 s.set_pending_anchor_range(start..end, mode);
2749 }
2750 } else {
2751 if !add {
2752 s.clear_disjoint();
2753 } else if click_count > 1 {
2754 s.delete(newest_selection.id)
2755 }
2756
2757 s.set_pending_anchor_range(start..end, mode);
2758 }
2759 });
2760 }
2761
2762 fn begin_columnar_selection(
2763 &mut self,
2764 position: DisplayPoint,
2765 goal_column: u32,
2766 reset: bool,
2767 cx: &mut ViewContext<Self>,
2768 ) {
2769 if !self.focus_handle.is_focused(cx) {
2770 self.last_focused_descendant = None;
2771 cx.focus(&self.focus_handle);
2772 }
2773
2774 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2775
2776 if reset {
2777 let pointer_position = display_map
2778 .buffer_snapshot
2779 .anchor_before(position.to_point(&display_map));
2780
2781 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2782 s.clear_disjoint();
2783 s.set_pending_anchor_range(
2784 pointer_position..pointer_position,
2785 SelectMode::Character,
2786 );
2787 });
2788 }
2789
2790 let tail = self.selections.newest::<Point>(cx).tail();
2791 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2792
2793 if !reset {
2794 self.select_columns(
2795 tail.to_display_point(&display_map),
2796 position,
2797 goal_column,
2798 &display_map,
2799 cx,
2800 );
2801 }
2802 }
2803
2804 fn update_selection(
2805 &mut self,
2806 position: DisplayPoint,
2807 goal_column: u32,
2808 scroll_delta: gpui::Point<f32>,
2809 cx: &mut ViewContext<Self>,
2810 ) {
2811 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2812
2813 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2814 let tail = tail.to_display_point(&display_map);
2815 self.select_columns(tail, position, goal_column, &display_map, cx);
2816 } else if let Some(mut pending) = self.selections.pending_anchor() {
2817 let buffer = self.buffer.read(cx).snapshot(cx);
2818 let head;
2819 let tail;
2820 let mode = self.selections.pending_mode().unwrap();
2821 match &mode {
2822 SelectMode::Character => {
2823 head = position.to_point(&display_map);
2824 tail = pending.tail().to_point(&buffer);
2825 }
2826 SelectMode::Word(original_range) => {
2827 let original_display_range = original_range.start.to_display_point(&display_map)
2828 ..original_range.end.to_display_point(&display_map);
2829 let original_buffer_range = original_display_range.start.to_point(&display_map)
2830 ..original_display_range.end.to_point(&display_map);
2831 if movement::is_inside_word(&display_map, position)
2832 || original_display_range.contains(&position)
2833 {
2834 let word_range = movement::surrounding_word(&display_map, position);
2835 if word_range.start < original_display_range.start {
2836 head = word_range.start.to_point(&display_map);
2837 } else {
2838 head = word_range.end.to_point(&display_map);
2839 }
2840 } else {
2841 head = position.to_point(&display_map);
2842 }
2843
2844 if head <= original_buffer_range.start {
2845 tail = original_buffer_range.end;
2846 } else {
2847 tail = original_buffer_range.start;
2848 }
2849 }
2850 SelectMode::Line(original_range) => {
2851 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2852
2853 let position = display_map
2854 .clip_point(position, Bias::Left)
2855 .to_point(&display_map);
2856 let line_start = display_map.prev_line_boundary(position).0;
2857 let next_line_start = buffer.clip_point(
2858 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2859 Bias::Left,
2860 );
2861
2862 if line_start < original_range.start {
2863 head = line_start
2864 } else {
2865 head = next_line_start
2866 }
2867
2868 if head <= original_range.start {
2869 tail = original_range.end;
2870 } else {
2871 tail = original_range.start;
2872 }
2873 }
2874 SelectMode::All => {
2875 return;
2876 }
2877 };
2878
2879 if head < tail {
2880 pending.start = buffer.anchor_before(head);
2881 pending.end = buffer.anchor_before(tail);
2882 pending.reversed = true;
2883 } else {
2884 pending.start = buffer.anchor_before(tail);
2885 pending.end = buffer.anchor_before(head);
2886 pending.reversed = false;
2887 }
2888
2889 self.change_selections(None, cx, |s| {
2890 s.set_pending(pending, mode);
2891 });
2892 } else {
2893 log::error!("update_selection dispatched with no pending selection");
2894 return;
2895 }
2896
2897 self.apply_scroll_delta(scroll_delta, cx);
2898 cx.notify();
2899 }
2900
2901 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2902 self.columnar_selection_tail.take();
2903 if self.selections.pending_anchor().is_some() {
2904 let selections = self.selections.all::<usize>(cx);
2905 self.change_selections(None, cx, |s| {
2906 s.select(selections);
2907 s.clear_pending();
2908 });
2909 }
2910 }
2911
2912 fn select_columns(
2913 &mut self,
2914 tail: DisplayPoint,
2915 head: DisplayPoint,
2916 goal_column: u32,
2917 display_map: &DisplaySnapshot,
2918 cx: &mut ViewContext<Self>,
2919 ) {
2920 let start_row = cmp::min(tail.row(), head.row());
2921 let end_row = cmp::max(tail.row(), head.row());
2922 let start_column = cmp::min(tail.column(), goal_column);
2923 let end_column = cmp::max(tail.column(), goal_column);
2924 let reversed = start_column < tail.column();
2925
2926 let selection_ranges = (start_row.0..=end_row.0)
2927 .map(DisplayRow)
2928 .filter_map(|row| {
2929 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2930 let start = display_map
2931 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2932 .to_point(display_map);
2933 let end = display_map
2934 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2935 .to_point(display_map);
2936 if reversed {
2937 Some(end..start)
2938 } else {
2939 Some(start..end)
2940 }
2941 } else {
2942 None
2943 }
2944 })
2945 .collect::<Vec<_>>();
2946
2947 self.change_selections(None, cx, |s| {
2948 s.select_ranges(selection_ranges);
2949 });
2950 cx.notify();
2951 }
2952
2953 pub fn has_pending_nonempty_selection(&self) -> bool {
2954 let pending_nonempty_selection = match self.selections.pending_anchor() {
2955 Some(Selection { start, end, .. }) => start != end,
2956 None => false,
2957 };
2958
2959 pending_nonempty_selection
2960 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2961 }
2962
2963 pub fn has_pending_selection(&self) -> bool {
2964 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2965 }
2966
2967 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2968 if self.clear_clicked_diff_hunks(cx) {
2969 cx.notify();
2970 return;
2971 }
2972 if self.dismiss_menus_and_popups(true, cx) {
2973 return;
2974 }
2975
2976 if self.mode == EditorMode::Full {
2977 if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
2978 return;
2979 }
2980 }
2981
2982 cx.propagate();
2983 }
2984
2985 pub fn dismiss_menus_and_popups(
2986 &mut self,
2987 should_report_inline_completion_event: bool,
2988 cx: &mut ViewContext<Self>,
2989 ) -> bool {
2990 if self.take_rename(false, cx).is_some() {
2991 return true;
2992 }
2993
2994 if hide_hover(self, cx) {
2995 return true;
2996 }
2997
2998 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2999 return true;
3000 }
3001
3002 if self.hide_context_menu(cx).is_some() {
3003 return true;
3004 }
3005
3006 if self.mouse_context_menu.take().is_some() {
3007 return true;
3008 }
3009
3010 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3011 return true;
3012 }
3013
3014 if self.snippet_stack.pop().is_some() {
3015 return true;
3016 }
3017
3018 if self.mode == EditorMode::Full {
3019 if self.active_diagnostics.is_some() {
3020 self.dismiss_diagnostics(cx);
3021 return true;
3022 }
3023 }
3024
3025 false
3026 }
3027
3028 fn linked_editing_ranges_for(
3029 &self,
3030 selection: Range<text::Anchor>,
3031 cx: &AppContext,
3032 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3033 if self.linked_edit_ranges.is_empty() {
3034 return None;
3035 }
3036 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3037 selection.end.buffer_id.and_then(|end_buffer_id| {
3038 if selection.start.buffer_id != Some(end_buffer_id) {
3039 return None;
3040 }
3041 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3042 let snapshot = buffer.read(cx).snapshot();
3043 self.linked_edit_ranges
3044 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3045 .map(|ranges| (ranges, snapshot, buffer))
3046 })?;
3047 use text::ToOffset as TO;
3048 // find offset from the start of current range to current cursor position
3049 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3050
3051 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3052 let start_difference = start_offset - start_byte_offset;
3053 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3054 let end_difference = end_offset - start_byte_offset;
3055 // Current range has associated linked ranges.
3056 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3057 for range in linked_ranges.iter() {
3058 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3059 let end_offset = start_offset + end_difference;
3060 let start_offset = start_offset + start_difference;
3061 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3062 continue;
3063 }
3064 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3065 if s.start.buffer_id != selection.start.buffer_id
3066 || s.end.buffer_id != selection.end.buffer_id
3067 {
3068 return false;
3069 }
3070 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3071 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3072 }) {
3073 continue;
3074 }
3075 let start = buffer_snapshot.anchor_after(start_offset);
3076 let end = buffer_snapshot.anchor_after(end_offset);
3077 linked_edits
3078 .entry(buffer.clone())
3079 .or_default()
3080 .push(start..end);
3081 }
3082 Some(linked_edits)
3083 }
3084
3085 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3086 let text: Arc<str> = text.into();
3087
3088 if self.read_only(cx) {
3089 return;
3090 }
3091
3092 let selections = self.selections.all_adjusted(cx);
3093 let mut bracket_inserted = false;
3094 let mut edits = Vec::new();
3095 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3096 let mut new_selections = Vec::with_capacity(selections.len());
3097 let mut new_autoclose_regions = Vec::new();
3098 let snapshot = self.buffer.read(cx).read(cx);
3099
3100 for (selection, autoclose_region) in
3101 self.selections_with_autoclose_regions(selections, &snapshot)
3102 {
3103 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3104 // Determine if the inserted text matches the opening or closing
3105 // bracket of any of this language's bracket pairs.
3106 let mut bracket_pair = None;
3107 let mut is_bracket_pair_start = false;
3108 let mut is_bracket_pair_end = false;
3109 if !text.is_empty() {
3110 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3111 // and they are removing the character that triggered IME popup.
3112 for (pair, enabled) in scope.brackets() {
3113 if !pair.close && !pair.surround {
3114 continue;
3115 }
3116
3117 if enabled && pair.start.ends_with(text.as_ref()) {
3118 bracket_pair = Some(pair.clone());
3119 is_bracket_pair_start = true;
3120 break;
3121 }
3122 if pair.end.as_str() == text.as_ref() {
3123 bracket_pair = Some(pair.clone());
3124 is_bracket_pair_end = true;
3125 break;
3126 }
3127 }
3128 }
3129
3130 if let Some(bracket_pair) = bracket_pair {
3131 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3132 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3133 let auto_surround =
3134 self.use_auto_surround && snapshot_settings.use_auto_surround;
3135 if selection.is_empty() {
3136 if is_bracket_pair_start {
3137 let prefix_len = bracket_pair.start.len() - text.len();
3138
3139 // If the inserted text is a suffix of an opening bracket and the
3140 // selection is preceded by the rest of the opening bracket, then
3141 // insert the closing bracket.
3142 let following_text_allows_autoclose = snapshot
3143 .chars_at(selection.start)
3144 .next()
3145 .map_or(true, |c| scope.should_autoclose_before(c));
3146 let preceding_text_matches_prefix = prefix_len == 0
3147 || (selection.start.column >= (prefix_len as u32)
3148 && snapshot.contains_str_at(
3149 Point::new(
3150 selection.start.row,
3151 selection.start.column - (prefix_len as u32),
3152 ),
3153 &bracket_pair.start[..prefix_len],
3154 ));
3155
3156 if autoclose
3157 && bracket_pair.close
3158 && following_text_allows_autoclose
3159 && preceding_text_matches_prefix
3160 {
3161 let anchor = snapshot.anchor_before(selection.end);
3162 new_selections.push((selection.map(|_| anchor), text.len()));
3163 new_autoclose_regions.push((
3164 anchor,
3165 text.len(),
3166 selection.id,
3167 bracket_pair.clone(),
3168 ));
3169 edits.push((
3170 selection.range(),
3171 format!("{}{}", text, bracket_pair.end).into(),
3172 ));
3173 bracket_inserted = true;
3174 continue;
3175 }
3176 }
3177
3178 if let Some(region) = autoclose_region {
3179 // If the selection is followed by an auto-inserted closing bracket,
3180 // then don't insert that closing bracket again; just move the selection
3181 // past the closing bracket.
3182 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3183 && text.as_ref() == region.pair.end.as_str();
3184 if should_skip {
3185 let anchor = snapshot.anchor_after(selection.end);
3186 new_selections
3187 .push((selection.map(|_| anchor), region.pair.end.len()));
3188 continue;
3189 }
3190 }
3191
3192 let always_treat_brackets_as_autoclosed = snapshot
3193 .settings_at(selection.start, cx)
3194 .always_treat_brackets_as_autoclosed;
3195 if always_treat_brackets_as_autoclosed
3196 && is_bracket_pair_end
3197 && snapshot.contains_str_at(selection.end, text.as_ref())
3198 {
3199 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3200 // and the inserted text is a closing bracket and the selection is followed
3201 // by the closing bracket then move the selection past the closing bracket.
3202 let anchor = snapshot.anchor_after(selection.end);
3203 new_selections.push((selection.map(|_| anchor), text.len()));
3204 continue;
3205 }
3206 }
3207 // If an opening bracket is 1 character long and is typed while
3208 // text is selected, then surround that text with the bracket pair.
3209 else if auto_surround
3210 && bracket_pair.surround
3211 && is_bracket_pair_start
3212 && bracket_pair.start.chars().count() == 1
3213 {
3214 edits.push((selection.start..selection.start, text.clone()));
3215 edits.push((
3216 selection.end..selection.end,
3217 bracket_pair.end.as_str().into(),
3218 ));
3219 bracket_inserted = true;
3220 new_selections.push((
3221 Selection {
3222 id: selection.id,
3223 start: snapshot.anchor_after(selection.start),
3224 end: snapshot.anchor_before(selection.end),
3225 reversed: selection.reversed,
3226 goal: selection.goal,
3227 },
3228 0,
3229 ));
3230 continue;
3231 }
3232 }
3233 }
3234
3235 if self.auto_replace_emoji_shortcode
3236 && selection.is_empty()
3237 && text.as_ref().ends_with(':')
3238 {
3239 if let Some(possible_emoji_short_code) =
3240 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3241 {
3242 if !possible_emoji_short_code.is_empty() {
3243 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3244 let emoji_shortcode_start = Point::new(
3245 selection.start.row,
3246 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3247 );
3248
3249 // Remove shortcode from buffer
3250 edits.push((
3251 emoji_shortcode_start..selection.start,
3252 "".to_string().into(),
3253 ));
3254 new_selections.push((
3255 Selection {
3256 id: selection.id,
3257 start: snapshot.anchor_after(emoji_shortcode_start),
3258 end: snapshot.anchor_before(selection.start),
3259 reversed: selection.reversed,
3260 goal: selection.goal,
3261 },
3262 0,
3263 ));
3264
3265 // Insert emoji
3266 let selection_start_anchor = snapshot.anchor_after(selection.start);
3267 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3268 edits.push((selection.start..selection.end, emoji.to_string().into()));
3269
3270 continue;
3271 }
3272 }
3273 }
3274 }
3275
3276 // If not handling any auto-close operation, then just replace the selected
3277 // text with the given input and move the selection to the end of the
3278 // newly inserted text.
3279 let anchor = snapshot.anchor_after(selection.end);
3280 if !self.linked_edit_ranges.is_empty() {
3281 let start_anchor = snapshot.anchor_before(selection.start);
3282
3283 let is_word_char = text.chars().next().map_or(true, |char| {
3284 let scope = snapshot.language_scope_at(start_anchor.to_offset(&snapshot));
3285 let kind = char_kind(&scope, char);
3286
3287 kind == CharKind::Word
3288 });
3289
3290 if is_word_char {
3291 if let Some(ranges) = self
3292 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3293 {
3294 for (buffer, edits) in ranges {
3295 linked_edits
3296 .entry(buffer.clone())
3297 .or_default()
3298 .extend(edits.into_iter().map(|range| (range, text.clone())));
3299 }
3300 }
3301 }
3302 }
3303
3304 new_selections.push((selection.map(|_| anchor), 0));
3305 edits.push((selection.start..selection.end, text.clone()));
3306 }
3307
3308 drop(snapshot);
3309
3310 self.transact(cx, |this, cx| {
3311 this.buffer.update(cx, |buffer, cx| {
3312 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3313 });
3314 for (buffer, edits) in linked_edits {
3315 buffer.update(cx, |buffer, cx| {
3316 let snapshot = buffer.snapshot();
3317 let edits = edits
3318 .into_iter()
3319 .map(|(range, text)| {
3320 use text::ToPoint as TP;
3321 let end_point = TP::to_point(&range.end, &snapshot);
3322 let start_point = TP::to_point(&range.start, &snapshot);
3323 (start_point..end_point, text)
3324 })
3325 .sorted_by_key(|(range, _)| range.start)
3326 .collect::<Vec<_>>();
3327 buffer.edit(edits, None, cx);
3328 })
3329 }
3330 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3331 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3332 let snapshot = this.buffer.read(cx).read(cx);
3333 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3334 .zip(new_selection_deltas)
3335 .map(|(selection, delta)| Selection {
3336 id: selection.id,
3337 start: selection.start + delta,
3338 end: selection.end + delta,
3339 reversed: selection.reversed,
3340 goal: SelectionGoal::None,
3341 })
3342 .collect::<Vec<_>>();
3343
3344 let mut i = 0;
3345 for (position, delta, selection_id, pair) in new_autoclose_regions {
3346 let position = position.to_offset(&snapshot) + delta;
3347 let start = snapshot.anchor_before(position);
3348 let end = snapshot.anchor_after(position);
3349 while let Some(existing_state) = this.autoclose_regions.get(i) {
3350 match existing_state.range.start.cmp(&start, &snapshot) {
3351 Ordering::Less => i += 1,
3352 Ordering::Greater => break,
3353 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3354 Ordering::Less => i += 1,
3355 Ordering::Equal => break,
3356 Ordering::Greater => break,
3357 },
3358 }
3359 }
3360 this.autoclose_regions.insert(
3361 i,
3362 AutocloseRegion {
3363 selection_id,
3364 range: start..end,
3365 pair,
3366 },
3367 );
3368 }
3369
3370 drop(snapshot);
3371 let had_active_inline_completion = this.has_active_inline_completion(cx);
3372 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3373 s.select(new_selections)
3374 });
3375
3376 if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
3377 if let Some(on_type_format_task) =
3378 this.trigger_on_type_formatting(text.to_string(), cx)
3379 {
3380 on_type_format_task.detach_and_log_err(cx);
3381 }
3382 }
3383
3384 let editor_settings = EditorSettings::get_global(cx);
3385 if bracket_inserted
3386 && (editor_settings.auto_signature_help
3387 || editor_settings.show_signature_help_after_edits)
3388 {
3389 this.show_signature_help(&ShowSignatureHelp, cx);
3390 }
3391
3392 let trigger_in_words = !had_active_inline_completion;
3393 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3394 linked_editing_ranges::refresh_linked_ranges(this, cx);
3395 this.refresh_inline_completion(true, false, cx);
3396 });
3397 }
3398
3399 fn find_possible_emoji_shortcode_at_position(
3400 snapshot: &MultiBufferSnapshot,
3401 position: Point,
3402 ) -> Option<String> {
3403 let mut chars = Vec::new();
3404 let mut found_colon = false;
3405 for char in snapshot.reversed_chars_at(position).take(100) {
3406 // Found a possible emoji shortcode in the middle of the buffer
3407 if found_colon {
3408 if char.is_whitespace() {
3409 chars.reverse();
3410 return Some(chars.iter().collect());
3411 }
3412 // If the previous character is not a whitespace, we are in the middle of a word
3413 // and we only want to complete the shortcode if the word is made up of other emojis
3414 let mut containing_word = String::new();
3415 for ch in snapshot
3416 .reversed_chars_at(position)
3417 .skip(chars.len() + 1)
3418 .take(100)
3419 {
3420 if ch.is_whitespace() {
3421 break;
3422 }
3423 containing_word.push(ch);
3424 }
3425 let containing_word = containing_word.chars().rev().collect::<String>();
3426 if util::word_consists_of_emojis(containing_word.as_str()) {
3427 chars.reverse();
3428 return Some(chars.iter().collect());
3429 }
3430 }
3431
3432 if char.is_whitespace() || !char.is_ascii() {
3433 return None;
3434 }
3435 if char == ':' {
3436 found_colon = true;
3437 } else {
3438 chars.push(char);
3439 }
3440 }
3441 // Found a possible emoji shortcode at the beginning of the buffer
3442 chars.reverse();
3443 Some(chars.iter().collect())
3444 }
3445
3446 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3447 self.transact(cx, |this, cx| {
3448 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3449 let selections = this.selections.all::<usize>(cx);
3450 let multi_buffer = this.buffer.read(cx);
3451 let buffer = multi_buffer.snapshot(cx);
3452 selections
3453 .iter()
3454 .map(|selection| {
3455 let start_point = selection.start.to_point(&buffer);
3456 let mut indent =
3457 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3458 indent.len = cmp::min(indent.len, start_point.column);
3459 let start = selection.start;
3460 let end = selection.end;
3461 let selection_is_empty = start == end;
3462 let language_scope = buffer.language_scope_at(start);
3463 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3464 &language_scope
3465 {
3466 let leading_whitespace_len = buffer
3467 .reversed_chars_at(start)
3468 .take_while(|c| c.is_whitespace() && *c != '\n')
3469 .map(|c| c.len_utf8())
3470 .sum::<usize>();
3471
3472 let trailing_whitespace_len = buffer
3473 .chars_at(end)
3474 .take_while(|c| c.is_whitespace() && *c != '\n')
3475 .map(|c| c.len_utf8())
3476 .sum::<usize>();
3477
3478 let insert_extra_newline =
3479 language.brackets().any(|(pair, enabled)| {
3480 let pair_start = pair.start.trim_end();
3481 let pair_end = pair.end.trim_start();
3482
3483 enabled
3484 && pair.newline
3485 && buffer.contains_str_at(
3486 end + trailing_whitespace_len,
3487 pair_end,
3488 )
3489 && buffer.contains_str_at(
3490 (start - leading_whitespace_len)
3491 .saturating_sub(pair_start.len()),
3492 pair_start,
3493 )
3494 });
3495
3496 // Comment extension on newline is allowed only for cursor selections
3497 let comment_delimiter = maybe!({
3498 if !selection_is_empty {
3499 return None;
3500 }
3501
3502 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3503 return None;
3504 }
3505
3506 let delimiters = language.line_comment_prefixes();
3507 let max_len_of_delimiter =
3508 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3509 let (snapshot, range) =
3510 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3511
3512 let mut index_of_first_non_whitespace = 0;
3513 let comment_candidate = snapshot
3514 .chars_for_range(range)
3515 .skip_while(|c| {
3516 let should_skip = c.is_whitespace();
3517 if should_skip {
3518 index_of_first_non_whitespace += 1;
3519 }
3520 should_skip
3521 })
3522 .take(max_len_of_delimiter)
3523 .collect::<String>();
3524 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3525 comment_candidate.starts_with(comment_prefix.as_ref())
3526 })?;
3527 let cursor_is_placed_after_comment_marker =
3528 index_of_first_non_whitespace + comment_prefix.len()
3529 <= start_point.column as usize;
3530 if cursor_is_placed_after_comment_marker {
3531 Some(comment_prefix.clone())
3532 } else {
3533 None
3534 }
3535 });
3536 (comment_delimiter, insert_extra_newline)
3537 } else {
3538 (None, false)
3539 };
3540
3541 let capacity_for_delimiter = comment_delimiter
3542 .as_deref()
3543 .map(str::len)
3544 .unwrap_or_default();
3545 let mut new_text =
3546 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3547 new_text.push_str("\n");
3548 new_text.extend(indent.chars());
3549 if let Some(delimiter) = &comment_delimiter {
3550 new_text.push_str(&delimiter);
3551 }
3552 if insert_extra_newline {
3553 new_text = new_text.repeat(2);
3554 }
3555
3556 let anchor = buffer.anchor_after(end);
3557 let new_selection = selection.map(|_| anchor);
3558 (
3559 (start..end, new_text),
3560 (insert_extra_newline, new_selection),
3561 )
3562 })
3563 .unzip()
3564 };
3565
3566 this.edit_with_autoindent(edits, cx);
3567 let buffer = this.buffer.read(cx).snapshot(cx);
3568 let new_selections = selection_fixup_info
3569 .into_iter()
3570 .map(|(extra_newline_inserted, new_selection)| {
3571 let mut cursor = new_selection.end.to_point(&buffer);
3572 if extra_newline_inserted {
3573 cursor.row -= 1;
3574 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3575 }
3576 new_selection.map(|_| cursor)
3577 })
3578 .collect();
3579
3580 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3581 this.refresh_inline_completion(true, false, cx);
3582 });
3583 }
3584
3585 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3586 let buffer = self.buffer.read(cx);
3587 let snapshot = buffer.snapshot(cx);
3588
3589 let mut edits = Vec::new();
3590 let mut rows = Vec::new();
3591
3592 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3593 let cursor = selection.head();
3594 let row = cursor.row;
3595
3596 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3597
3598 let newline = "\n".to_string();
3599 edits.push((start_of_line..start_of_line, newline));
3600
3601 rows.push(row + rows_inserted as u32);
3602 }
3603
3604 self.transact(cx, |editor, cx| {
3605 editor.edit(edits, cx);
3606
3607 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3608 let mut index = 0;
3609 s.move_cursors_with(|map, _, _| {
3610 let row = rows[index];
3611 index += 1;
3612
3613 let point = Point::new(row, 0);
3614 let boundary = map.next_line_boundary(point).1;
3615 let clipped = map.clip_point(boundary, Bias::Left);
3616
3617 (clipped, SelectionGoal::None)
3618 });
3619 });
3620
3621 let mut indent_edits = Vec::new();
3622 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3623 for row in rows {
3624 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3625 for (row, indent) in indents {
3626 if indent.len == 0 {
3627 continue;
3628 }
3629
3630 let text = match indent.kind {
3631 IndentKind::Space => " ".repeat(indent.len as usize),
3632 IndentKind::Tab => "\t".repeat(indent.len as usize),
3633 };
3634 let point = Point::new(row.0, 0);
3635 indent_edits.push((point..point, text));
3636 }
3637 }
3638 editor.edit(indent_edits, cx);
3639 });
3640 }
3641
3642 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3643 let buffer = self.buffer.read(cx);
3644 let snapshot = buffer.snapshot(cx);
3645
3646 let mut edits = Vec::new();
3647 let mut rows = Vec::new();
3648 let mut rows_inserted = 0;
3649
3650 for selection in self.selections.all_adjusted(cx) {
3651 let cursor = selection.head();
3652 let row = cursor.row;
3653
3654 let point = Point::new(row + 1, 0);
3655 let start_of_line = snapshot.clip_point(point, Bias::Left);
3656
3657 let newline = "\n".to_string();
3658 edits.push((start_of_line..start_of_line, newline));
3659
3660 rows_inserted += 1;
3661 rows.push(row + rows_inserted);
3662 }
3663
3664 self.transact(cx, |editor, cx| {
3665 editor.edit(edits, cx);
3666
3667 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3668 let mut index = 0;
3669 s.move_cursors_with(|map, _, _| {
3670 let row = rows[index];
3671 index += 1;
3672
3673 let point = Point::new(row, 0);
3674 let boundary = map.next_line_boundary(point).1;
3675 let clipped = map.clip_point(boundary, Bias::Left);
3676
3677 (clipped, SelectionGoal::None)
3678 });
3679 });
3680
3681 let mut indent_edits = Vec::new();
3682 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3683 for row in rows {
3684 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3685 for (row, indent) in indents {
3686 if indent.len == 0 {
3687 continue;
3688 }
3689
3690 let text = match indent.kind {
3691 IndentKind::Space => " ".repeat(indent.len as usize),
3692 IndentKind::Tab => "\t".repeat(indent.len as usize),
3693 };
3694 let point = Point::new(row.0, 0);
3695 indent_edits.push((point..point, text));
3696 }
3697 }
3698 editor.edit(indent_edits, cx);
3699 });
3700 }
3701
3702 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3703 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3704 original_indent_columns: Vec::new(),
3705 });
3706 self.insert_with_autoindent_mode(text, autoindent, cx);
3707 }
3708
3709 fn insert_with_autoindent_mode(
3710 &mut self,
3711 text: &str,
3712 autoindent_mode: Option<AutoindentMode>,
3713 cx: &mut ViewContext<Self>,
3714 ) {
3715 if self.read_only(cx) {
3716 return;
3717 }
3718
3719 let text: Arc<str> = text.into();
3720 self.transact(cx, |this, cx| {
3721 let old_selections = this.selections.all_adjusted(cx);
3722 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3723 let anchors = {
3724 let snapshot = buffer.read(cx);
3725 old_selections
3726 .iter()
3727 .map(|s| {
3728 let anchor = snapshot.anchor_after(s.head());
3729 s.map(|_| anchor)
3730 })
3731 .collect::<Vec<_>>()
3732 };
3733 buffer.edit(
3734 old_selections
3735 .iter()
3736 .map(|s| (s.start..s.end, text.clone())),
3737 autoindent_mode,
3738 cx,
3739 );
3740 anchors
3741 });
3742
3743 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3744 s.select_anchors(selection_anchors);
3745 })
3746 });
3747 }
3748
3749 fn trigger_completion_on_input(
3750 &mut self,
3751 text: &str,
3752 trigger_in_words: bool,
3753 cx: &mut ViewContext<Self>,
3754 ) {
3755 if self.is_completion_trigger(text, trigger_in_words, cx) {
3756 self.show_completions(
3757 &ShowCompletions {
3758 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3759 },
3760 cx,
3761 );
3762 } else {
3763 self.hide_context_menu(cx);
3764 }
3765 }
3766
3767 fn is_completion_trigger(
3768 &self,
3769 text: &str,
3770 trigger_in_words: bool,
3771 cx: &mut ViewContext<Self>,
3772 ) -> bool {
3773 let position = self.selections.newest_anchor().head();
3774 let multibuffer = self.buffer.read(cx);
3775 let Some(buffer) = position
3776 .buffer_id
3777 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3778 else {
3779 return false;
3780 };
3781
3782 if let Some(completion_provider) = &self.completion_provider {
3783 completion_provider.is_completion_trigger(
3784 &buffer,
3785 position.text_anchor,
3786 text,
3787 trigger_in_words,
3788 cx,
3789 )
3790 } else {
3791 false
3792 }
3793 }
3794
3795 /// If any empty selections is touching the start of its innermost containing autoclose
3796 /// region, expand it to select the brackets.
3797 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3798 let selections = self.selections.all::<usize>(cx);
3799 let buffer = self.buffer.read(cx).read(cx);
3800 let new_selections = self
3801 .selections_with_autoclose_regions(selections, &buffer)
3802 .map(|(mut selection, region)| {
3803 if !selection.is_empty() {
3804 return selection;
3805 }
3806
3807 if let Some(region) = region {
3808 let mut range = region.range.to_offset(&buffer);
3809 if selection.start == range.start && range.start >= region.pair.start.len() {
3810 range.start -= region.pair.start.len();
3811 if buffer.contains_str_at(range.start, ®ion.pair.start)
3812 && buffer.contains_str_at(range.end, ®ion.pair.end)
3813 {
3814 range.end += region.pair.end.len();
3815 selection.start = range.start;
3816 selection.end = range.end;
3817
3818 return selection;
3819 }
3820 }
3821 }
3822
3823 let always_treat_brackets_as_autoclosed = buffer
3824 .settings_at(selection.start, cx)
3825 .always_treat_brackets_as_autoclosed;
3826
3827 if !always_treat_brackets_as_autoclosed {
3828 return selection;
3829 }
3830
3831 if let Some(scope) = buffer.language_scope_at(selection.start) {
3832 for (pair, enabled) in scope.brackets() {
3833 if !enabled || !pair.close {
3834 continue;
3835 }
3836
3837 if buffer.contains_str_at(selection.start, &pair.end) {
3838 let pair_start_len = pair.start.len();
3839 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3840 {
3841 selection.start -= pair_start_len;
3842 selection.end += pair.end.len();
3843
3844 return selection;
3845 }
3846 }
3847 }
3848 }
3849
3850 selection
3851 })
3852 .collect();
3853
3854 drop(buffer);
3855 self.change_selections(None, cx, |selections| selections.select(new_selections));
3856 }
3857
3858 /// Iterate the given selections, and for each one, find the smallest surrounding
3859 /// autoclose region. This uses the ordering of the selections and the autoclose
3860 /// regions to avoid repeated comparisons.
3861 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3862 &'a self,
3863 selections: impl IntoIterator<Item = Selection<D>>,
3864 buffer: &'a MultiBufferSnapshot,
3865 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3866 let mut i = 0;
3867 let mut regions = self.autoclose_regions.as_slice();
3868 selections.into_iter().map(move |selection| {
3869 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3870
3871 let mut enclosing = None;
3872 while let Some(pair_state) = regions.get(i) {
3873 if pair_state.range.end.to_offset(buffer) < range.start {
3874 regions = ®ions[i + 1..];
3875 i = 0;
3876 } else if pair_state.range.start.to_offset(buffer) > range.end {
3877 break;
3878 } else {
3879 if pair_state.selection_id == selection.id {
3880 enclosing = Some(pair_state);
3881 }
3882 i += 1;
3883 }
3884 }
3885
3886 (selection.clone(), enclosing)
3887 })
3888 }
3889
3890 /// Remove any autoclose regions that no longer contain their selection.
3891 fn invalidate_autoclose_regions(
3892 &mut self,
3893 mut selections: &[Selection<Anchor>],
3894 buffer: &MultiBufferSnapshot,
3895 ) {
3896 self.autoclose_regions.retain(|state| {
3897 let mut i = 0;
3898 while let Some(selection) = selections.get(i) {
3899 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3900 selections = &selections[1..];
3901 continue;
3902 }
3903 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3904 break;
3905 }
3906 if selection.id == state.selection_id {
3907 return true;
3908 } else {
3909 i += 1;
3910 }
3911 }
3912 false
3913 });
3914 }
3915
3916 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3917 let offset = position.to_offset(buffer);
3918 let (word_range, kind) = buffer.surrounding_word(offset);
3919 if offset > word_range.start && kind == Some(CharKind::Word) {
3920 Some(
3921 buffer
3922 .text_for_range(word_range.start..offset)
3923 .collect::<String>(),
3924 )
3925 } else {
3926 None
3927 }
3928 }
3929
3930 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3931 self.refresh_inlay_hints(
3932 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3933 cx,
3934 );
3935 }
3936
3937 pub fn inlay_hints_enabled(&self) -> bool {
3938 self.inlay_hint_cache.enabled
3939 }
3940
3941 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3942 if self.project.is_none() || self.mode != EditorMode::Full {
3943 return;
3944 }
3945
3946 let reason_description = reason.description();
3947 let ignore_debounce = matches!(
3948 reason,
3949 InlayHintRefreshReason::SettingsChange(_)
3950 | InlayHintRefreshReason::Toggle(_)
3951 | InlayHintRefreshReason::ExcerptsRemoved(_)
3952 );
3953 let (invalidate_cache, required_languages) = match reason {
3954 InlayHintRefreshReason::Toggle(enabled) => {
3955 self.inlay_hint_cache.enabled = enabled;
3956 if enabled {
3957 (InvalidationStrategy::RefreshRequested, None)
3958 } else {
3959 self.inlay_hint_cache.clear();
3960 self.splice_inlays(
3961 self.visible_inlay_hints(cx)
3962 .iter()
3963 .map(|inlay| inlay.id)
3964 .collect(),
3965 Vec::new(),
3966 cx,
3967 );
3968 return;
3969 }
3970 }
3971 InlayHintRefreshReason::SettingsChange(new_settings) => {
3972 match self.inlay_hint_cache.update_settings(
3973 &self.buffer,
3974 new_settings,
3975 self.visible_inlay_hints(cx),
3976 cx,
3977 ) {
3978 ControlFlow::Break(Some(InlaySplice {
3979 to_remove,
3980 to_insert,
3981 })) => {
3982 self.splice_inlays(to_remove, to_insert, cx);
3983 return;
3984 }
3985 ControlFlow::Break(None) => return,
3986 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3987 }
3988 }
3989 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3990 if let Some(InlaySplice {
3991 to_remove,
3992 to_insert,
3993 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3994 {
3995 self.splice_inlays(to_remove, to_insert, cx);
3996 }
3997 return;
3998 }
3999 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4000 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4001 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4002 }
4003 InlayHintRefreshReason::RefreshRequested => {
4004 (InvalidationStrategy::RefreshRequested, None)
4005 }
4006 };
4007
4008 if let Some(InlaySplice {
4009 to_remove,
4010 to_insert,
4011 }) = self.inlay_hint_cache.spawn_hint_refresh(
4012 reason_description,
4013 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4014 invalidate_cache,
4015 ignore_debounce,
4016 cx,
4017 ) {
4018 self.splice_inlays(to_remove, to_insert, cx);
4019 }
4020 }
4021
4022 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4023 self.display_map
4024 .read(cx)
4025 .current_inlays()
4026 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4027 .cloned()
4028 .collect()
4029 }
4030
4031 pub fn excerpts_for_inlay_hints_query(
4032 &self,
4033 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4034 cx: &mut ViewContext<Editor>,
4035 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4036 let Some(project) = self.project.as_ref() else {
4037 return HashMap::default();
4038 };
4039 let project = project.read(cx);
4040 let multi_buffer = self.buffer().read(cx);
4041 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4042 let multi_buffer_visible_start = self
4043 .scroll_manager
4044 .anchor()
4045 .anchor
4046 .to_point(&multi_buffer_snapshot);
4047 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4048 multi_buffer_visible_start
4049 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4050 Bias::Left,
4051 );
4052 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4053 multi_buffer
4054 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4055 .into_iter()
4056 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4057 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4058 let buffer = buffer_handle.read(cx);
4059 let buffer_file = project::File::from_dyn(buffer.file())?;
4060 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4061 let worktree_entry = buffer_worktree
4062 .read(cx)
4063 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4064 if worktree_entry.is_ignored {
4065 return None;
4066 }
4067
4068 let language = buffer.language()?;
4069 if let Some(restrict_to_languages) = restrict_to_languages {
4070 if !restrict_to_languages.contains(language) {
4071 return None;
4072 }
4073 }
4074 Some((
4075 excerpt_id,
4076 (
4077 buffer_handle,
4078 buffer.version().clone(),
4079 excerpt_visible_range,
4080 ),
4081 ))
4082 })
4083 .collect()
4084 }
4085
4086 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4087 TextLayoutDetails {
4088 text_system: cx.text_system().clone(),
4089 editor_style: self.style.clone().unwrap(),
4090 rem_size: cx.rem_size(),
4091 scroll_anchor: self.scroll_manager.anchor(),
4092 visible_rows: self.visible_line_count(),
4093 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4094 }
4095 }
4096
4097 fn splice_inlays(
4098 &self,
4099 to_remove: Vec<InlayId>,
4100 to_insert: Vec<Inlay>,
4101 cx: &mut ViewContext<Self>,
4102 ) {
4103 self.display_map.update(cx, |display_map, cx| {
4104 display_map.splice_inlays(to_remove, to_insert, cx);
4105 });
4106 cx.notify();
4107 }
4108
4109 fn trigger_on_type_formatting(
4110 &self,
4111 input: String,
4112 cx: &mut ViewContext<Self>,
4113 ) -> Option<Task<Result<()>>> {
4114 if input.len() != 1 {
4115 return None;
4116 }
4117
4118 let project = self.project.as_ref()?;
4119 let position = self.selections.newest_anchor().head();
4120 let (buffer, buffer_position) = self
4121 .buffer
4122 .read(cx)
4123 .text_anchor_for_position(position, cx)?;
4124
4125 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4126 // hence we do LSP request & edit on host side only — add formats to host's history.
4127 let push_to_lsp_host_history = true;
4128 // If this is not the host, append its history with new edits.
4129 let push_to_client_history = project.read(cx).is_via_collab();
4130
4131 let on_type_formatting = project.update(cx, |project, cx| {
4132 project.on_type_format(
4133 buffer.clone(),
4134 buffer_position,
4135 input,
4136 push_to_lsp_host_history,
4137 cx,
4138 )
4139 });
4140 Some(cx.spawn(|editor, mut cx| async move {
4141 if let Some(transaction) = on_type_formatting.await? {
4142 if push_to_client_history {
4143 buffer
4144 .update(&mut cx, |buffer, _| {
4145 buffer.push_transaction(transaction, Instant::now());
4146 })
4147 .ok();
4148 }
4149 editor.update(&mut cx, |editor, cx| {
4150 editor.refresh_document_highlights(cx);
4151 })?;
4152 }
4153 Ok(())
4154 }))
4155 }
4156
4157 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4158 if self.pending_rename.is_some() {
4159 return;
4160 }
4161
4162 let Some(provider) = self.completion_provider.as_ref() else {
4163 return;
4164 };
4165
4166 let position = self.selections.newest_anchor().head();
4167 let (buffer, buffer_position) =
4168 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4169 output
4170 } else {
4171 return;
4172 };
4173
4174 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4175 let is_followup_invoke = {
4176 let context_menu_state = self.context_menu.read();
4177 matches!(
4178 context_menu_state.deref(),
4179 Some(ContextMenu::Completions(_))
4180 )
4181 };
4182 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4183 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4184 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(&trigger) => {
4185 CompletionTriggerKind::TRIGGER_CHARACTER
4186 }
4187
4188 _ => CompletionTriggerKind::INVOKED,
4189 };
4190 let completion_context = CompletionContext {
4191 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4192 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4193 Some(String::from(trigger))
4194 } else {
4195 None
4196 }
4197 }),
4198 trigger_kind,
4199 };
4200 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4201 let sort_completions = provider.sort_completions();
4202
4203 let id = post_inc(&mut self.next_completion_id);
4204 let task = cx.spawn(|this, mut cx| {
4205 async move {
4206 this.update(&mut cx, |this, _| {
4207 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4208 })?;
4209 let completions = completions.await.log_err();
4210 let menu = if let Some(completions) = completions {
4211 let mut menu = CompletionsMenu {
4212 id,
4213 sort_completions,
4214 initial_position: position,
4215 match_candidates: completions
4216 .iter()
4217 .enumerate()
4218 .map(|(id, completion)| {
4219 StringMatchCandidate::new(
4220 id,
4221 completion.label.text[completion.label.filter_range.clone()]
4222 .into(),
4223 )
4224 })
4225 .collect(),
4226 buffer: buffer.clone(),
4227 completions: Arc::new(RwLock::new(completions.into())),
4228 matches: Vec::new().into(),
4229 selected_item: 0,
4230 scroll_handle: UniformListScrollHandle::new(),
4231 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4232 DebouncedDelay::new(),
4233 )),
4234 };
4235 menu.filter(query.as_deref(), cx.background_executor().clone())
4236 .await;
4237
4238 if menu.matches.is_empty() {
4239 None
4240 } else {
4241 this.update(&mut cx, |editor, cx| {
4242 let completions = menu.completions.clone();
4243 let matches = menu.matches.clone();
4244
4245 let delay_ms = EditorSettings::get_global(cx)
4246 .completion_documentation_secondary_query_debounce;
4247 let delay = Duration::from_millis(delay_ms);
4248 editor
4249 .completion_documentation_pre_resolve_debounce
4250 .fire_new(delay, cx, |editor, cx| {
4251 CompletionsMenu::pre_resolve_completion_documentation(
4252 buffer,
4253 completions,
4254 matches,
4255 editor,
4256 cx,
4257 )
4258 });
4259 })
4260 .ok();
4261 Some(menu)
4262 }
4263 } else {
4264 None
4265 };
4266
4267 this.update(&mut cx, |this, cx| {
4268 let mut context_menu = this.context_menu.write();
4269 match context_menu.as_ref() {
4270 None => {}
4271
4272 Some(ContextMenu::Completions(prev_menu)) => {
4273 if prev_menu.id > id {
4274 return;
4275 }
4276 }
4277
4278 _ => return,
4279 }
4280
4281 if this.focus_handle.is_focused(cx) && menu.is_some() {
4282 let menu = menu.unwrap();
4283 *context_menu = Some(ContextMenu::Completions(menu));
4284 drop(context_menu);
4285 this.discard_inline_completion(false, cx);
4286 cx.notify();
4287 } else if this.completion_tasks.len() <= 1 {
4288 // If there are no more completion tasks and the last menu was
4289 // empty, we should hide it. If it was already hidden, we should
4290 // also show the copilot completion when available.
4291 drop(context_menu);
4292 if this.hide_context_menu(cx).is_none() {
4293 this.update_visible_inline_completion(cx);
4294 }
4295 }
4296 })?;
4297
4298 Ok::<_, anyhow::Error>(())
4299 }
4300 .log_err()
4301 });
4302
4303 self.completion_tasks.push((id, task));
4304 }
4305
4306 pub fn confirm_completion(
4307 &mut self,
4308 action: &ConfirmCompletion,
4309 cx: &mut ViewContext<Self>,
4310 ) -> Option<Task<Result<()>>> {
4311 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4312 }
4313
4314 pub fn compose_completion(
4315 &mut self,
4316 action: &ComposeCompletion,
4317 cx: &mut ViewContext<Self>,
4318 ) -> Option<Task<Result<()>>> {
4319 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4320 }
4321
4322 fn do_completion(
4323 &mut self,
4324 item_ix: Option<usize>,
4325 intent: CompletionIntent,
4326 cx: &mut ViewContext<Editor>,
4327 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4328 use language::ToOffset as _;
4329
4330 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4331 menu
4332 } else {
4333 return None;
4334 };
4335
4336 let mat = completions_menu
4337 .matches
4338 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4339 let buffer_handle = completions_menu.buffer;
4340 let completions = completions_menu.completions.read();
4341 let completion = completions.get(mat.candidate_id)?;
4342 cx.stop_propagation();
4343
4344 let snippet;
4345 let text;
4346
4347 if completion.is_snippet() {
4348 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4349 text = snippet.as_ref().unwrap().text.clone();
4350 } else {
4351 snippet = None;
4352 text = completion.new_text.clone();
4353 };
4354 let selections = self.selections.all::<usize>(cx);
4355 let buffer = buffer_handle.read(cx);
4356 let old_range = completion.old_range.to_offset(buffer);
4357 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4358
4359 let newest_selection = self.selections.newest_anchor();
4360 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4361 return None;
4362 }
4363
4364 let lookbehind = newest_selection
4365 .start
4366 .text_anchor
4367 .to_offset(buffer)
4368 .saturating_sub(old_range.start);
4369 let lookahead = old_range
4370 .end
4371 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4372 let mut common_prefix_len = old_text
4373 .bytes()
4374 .zip(text.bytes())
4375 .take_while(|(a, b)| a == b)
4376 .count();
4377
4378 let snapshot = self.buffer.read(cx).snapshot(cx);
4379 let mut range_to_replace: Option<Range<isize>> = None;
4380 let mut ranges = Vec::new();
4381 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4382 for selection in &selections {
4383 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4384 let start = selection.start.saturating_sub(lookbehind);
4385 let end = selection.end + lookahead;
4386 if selection.id == newest_selection.id {
4387 range_to_replace = Some(
4388 ((start + common_prefix_len) as isize - selection.start as isize)
4389 ..(end as isize - selection.start as isize),
4390 );
4391 }
4392 ranges.push(start + common_prefix_len..end);
4393 } else {
4394 common_prefix_len = 0;
4395 ranges.clear();
4396 ranges.extend(selections.iter().map(|s| {
4397 if s.id == newest_selection.id {
4398 range_to_replace = Some(
4399 old_range.start.to_offset_utf16(&snapshot).0 as isize
4400 - selection.start as isize
4401 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4402 - selection.start as isize,
4403 );
4404 old_range.clone()
4405 } else {
4406 s.start..s.end
4407 }
4408 }));
4409 break;
4410 }
4411 if !self.linked_edit_ranges.is_empty() {
4412 let start_anchor = snapshot.anchor_before(selection.head());
4413 let end_anchor = snapshot.anchor_after(selection.tail());
4414 if let Some(ranges) = self
4415 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4416 {
4417 for (buffer, edits) in ranges {
4418 linked_edits.entry(buffer.clone()).or_default().extend(
4419 edits
4420 .into_iter()
4421 .map(|range| (range, text[common_prefix_len..].to_owned())),
4422 );
4423 }
4424 }
4425 }
4426 }
4427 let text = &text[common_prefix_len..];
4428
4429 cx.emit(EditorEvent::InputHandled {
4430 utf16_range_to_replace: range_to_replace,
4431 text: text.into(),
4432 });
4433
4434 self.transact(cx, |this, cx| {
4435 if let Some(mut snippet) = snippet {
4436 snippet.text = text.to_string();
4437 for tabstop in snippet.tabstops.iter_mut().flatten() {
4438 tabstop.start -= common_prefix_len as isize;
4439 tabstop.end -= common_prefix_len as isize;
4440 }
4441
4442 this.insert_snippet(&ranges, snippet, cx).log_err();
4443 } else {
4444 this.buffer.update(cx, |buffer, cx| {
4445 buffer.edit(
4446 ranges.iter().map(|range| (range.clone(), text)),
4447 this.autoindent_mode.clone(),
4448 cx,
4449 );
4450 });
4451 }
4452 for (buffer, edits) in linked_edits {
4453 buffer.update(cx, |buffer, cx| {
4454 let snapshot = buffer.snapshot();
4455 let edits = edits
4456 .into_iter()
4457 .map(|(range, text)| {
4458 use text::ToPoint as TP;
4459 let end_point = TP::to_point(&range.end, &snapshot);
4460 let start_point = TP::to_point(&range.start, &snapshot);
4461 (start_point..end_point, text)
4462 })
4463 .sorted_by_key(|(range, _)| range.start)
4464 .collect::<Vec<_>>();
4465 buffer.edit(edits, None, cx);
4466 })
4467 }
4468
4469 this.refresh_inline_completion(true, false, cx);
4470 });
4471
4472 let show_new_completions_on_confirm = completion
4473 .confirm
4474 .as_ref()
4475 .map_or(false, |confirm| confirm(intent, cx));
4476 if show_new_completions_on_confirm {
4477 self.show_completions(&ShowCompletions { trigger: None }, cx);
4478 }
4479
4480 let provider = self.completion_provider.as_ref()?;
4481 let apply_edits = provider.apply_additional_edits_for_completion(
4482 buffer_handle,
4483 completion.clone(),
4484 true,
4485 cx,
4486 );
4487
4488 let editor_settings = EditorSettings::get_global(cx);
4489 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4490 // After the code completion is finished, users often want to know what signatures are needed.
4491 // so we should automatically call signature_help
4492 self.show_signature_help(&ShowSignatureHelp, cx);
4493 }
4494
4495 Some(cx.foreground_executor().spawn(async move {
4496 apply_edits.await?;
4497 Ok(())
4498 }))
4499 }
4500
4501 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4502 let mut context_menu = self.context_menu.write();
4503 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4504 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4505 // Toggle if we're selecting the same one
4506 *context_menu = None;
4507 cx.notify();
4508 return;
4509 } else {
4510 // Otherwise, clear it and start a new one
4511 *context_menu = None;
4512 cx.notify();
4513 }
4514 }
4515 drop(context_menu);
4516 let snapshot = self.snapshot(cx);
4517 let deployed_from_indicator = action.deployed_from_indicator;
4518 let mut task = self.code_actions_task.take();
4519 let action = action.clone();
4520 cx.spawn(|editor, mut cx| async move {
4521 while let Some(prev_task) = task {
4522 prev_task.await;
4523 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4524 }
4525
4526 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4527 if editor.focus_handle.is_focused(cx) {
4528 let multibuffer_point = action
4529 .deployed_from_indicator
4530 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4531 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4532 let (buffer, buffer_row) = snapshot
4533 .buffer_snapshot
4534 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4535 .and_then(|(buffer_snapshot, range)| {
4536 editor
4537 .buffer
4538 .read(cx)
4539 .buffer(buffer_snapshot.remote_id())
4540 .map(|buffer| (buffer, range.start.row))
4541 })?;
4542 let (_, code_actions) = editor
4543 .available_code_actions
4544 .clone()
4545 .and_then(|(location, code_actions)| {
4546 let snapshot = location.buffer.read(cx).snapshot();
4547 let point_range = location.range.to_point(&snapshot);
4548 let point_range = point_range.start.row..=point_range.end.row;
4549 if point_range.contains(&buffer_row) {
4550 Some((location, code_actions))
4551 } else {
4552 None
4553 }
4554 })
4555 .unzip();
4556 let buffer_id = buffer.read(cx).remote_id();
4557 let tasks = editor
4558 .tasks
4559 .get(&(buffer_id, buffer_row))
4560 .map(|t| Arc::new(t.to_owned()));
4561 if tasks.is_none() && code_actions.is_none() {
4562 return None;
4563 }
4564
4565 editor.completion_tasks.clear();
4566 editor.discard_inline_completion(false, cx);
4567 let task_context =
4568 tasks
4569 .as_ref()
4570 .zip(editor.project.clone())
4571 .map(|(tasks, project)| {
4572 let position = Point::new(buffer_row, tasks.column);
4573 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4574 let location = Location {
4575 buffer: buffer.clone(),
4576 range: range_start..range_start,
4577 };
4578 // Fill in the environmental variables from the tree-sitter captures
4579 let mut captured_task_variables = TaskVariables::default();
4580 for (capture_name, value) in tasks.extra_variables.clone() {
4581 captured_task_variables.insert(
4582 task::VariableName::Custom(capture_name.into()),
4583 value.clone(),
4584 );
4585 }
4586 project.update(cx, |project, cx| {
4587 project.task_context_for_location(
4588 captured_task_variables,
4589 location,
4590 cx,
4591 )
4592 })
4593 });
4594
4595 Some(cx.spawn(|editor, mut cx| async move {
4596 let task_context = match task_context {
4597 Some(task_context) => task_context.await,
4598 None => None,
4599 };
4600 let resolved_tasks =
4601 tasks.zip(task_context).map(|(tasks, task_context)| {
4602 Arc::new(ResolvedTasks {
4603 templates: tasks
4604 .templates
4605 .iter()
4606 .filter_map(|(kind, template)| {
4607 template
4608 .resolve_task(&kind.to_id_base(), &task_context)
4609 .map(|task| (kind.clone(), task))
4610 })
4611 .collect(),
4612 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4613 multibuffer_point.row,
4614 tasks.column,
4615 )),
4616 })
4617 });
4618 let spawn_straight_away = resolved_tasks
4619 .as_ref()
4620 .map_or(false, |tasks| tasks.templates.len() == 1)
4621 && code_actions
4622 .as_ref()
4623 .map_or(true, |actions| actions.is_empty());
4624 if let Some(task) = editor
4625 .update(&mut cx, |editor, cx| {
4626 *editor.context_menu.write() =
4627 Some(ContextMenu::CodeActions(CodeActionsMenu {
4628 buffer,
4629 actions: CodeActionContents {
4630 tasks: resolved_tasks,
4631 actions: code_actions,
4632 },
4633 selected_item: Default::default(),
4634 scroll_handle: UniformListScrollHandle::default(),
4635 deployed_from_indicator,
4636 }));
4637 if spawn_straight_away {
4638 if let Some(task) = editor.confirm_code_action(
4639 &ConfirmCodeAction { item_ix: Some(0) },
4640 cx,
4641 ) {
4642 cx.notify();
4643 return task;
4644 }
4645 }
4646 cx.notify();
4647 Task::ready(Ok(()))
4648 })
4649 .ok()
4650 {
4651 task.await
4652 } else {
4653 Ok(())
4654 }
4655 }))
4656 } else {
4657 Some(Task::ready(Ok(())))
4658 }
4659 })?;
4660 if let Some(task) = spawned_test_task {
4661 task.await?;
4662 }
4663
4664 Ok::<_, anyhow::Error>(())
4665 })
4666 .detach_and_log_err(cx);
4667 }
4668
4669 pub fn confirm_code_action(
4670 &mut self,
4671 action: &ConfirmCodeAction,
4672 cx: &mut ViewContext<Self>,
4673 ) -> Option<Task<Result<()>>> {
4674 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4675 menu
4676 } else {
4677 return None;
4678 };
4679 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4680 let action = actions_menu.actions.get(action_ix)?;
4681 let title = action.label();
4682 let buffer = actions_menu.buffer;
4683 let workspace = self.workspace()?;
4684
4685 match action {
4686 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4687 workspace.update(cx, |workspace, cx| {
4688 workspace::tasks::schedule_resolved_task(
4689 workspace,
4690 task_source_kind,
4691 resolved_task,
4692 false,
4693 cx,
4694 );
4695
4696 Some(Task::ready(Ok(())))
4697 })
4698 }
4699 CodeActionsItem::CodeAction(action) => {
4700 let apply_code_actions = workspace
4701 .read(cx)
4702 .project()
4703 .clone()
4704 .update(cx, |project, cx| {
4705 project.apply_code_action(buffer, action, true, cx)
4706 });
4707 let workspace = workspace.downgrade();
4708 Some(cx.spawn(|editor, cx| async move {
4709 let project_transaction = apply_code_actions.await?;
4710 Self::open_project_transaction(
4711 &editor,
4712 workspace,
4713 project_transaction,
4714 title,
4715 cx,
4716 )
4717 .await
4718 }))
4719 }
4720 }
4721 }
4722
4723 pub async fn open_project_transaction(
4724 this: &WeakView<Editor>,
4725 workspace: WeakView<Workspace>,
4726 transaction: ProjectTransaction,
4727 title: String,
4728 mut cx: AsyncWindowContext,
4729 ) -> Result<()> {
4730 let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
4731
4732 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4733 cx.update(|cx| {
4734 entries.sort_unstable_by_key(|(buffer, _)| {
4735 buffer.read(cx).file().map(|f| f.path().clone())
4736 });
4737 })?;
4738
4739 // If the project transaction's edits are all contained within this editor, then
4740 // avoid opening a new editor to display them.
4741
4742 if let Some((buffer, transaction)) = entries.first() {
4743 if entries.len() == 1 {
4744 let excerpt = this.update(&mut cx, |editor, cx| {
4745 editor
4746 .buffer()
4747 .read(cx)
4748 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4749 })?;
4750 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4751 if excerpted_buffer == *buffer {
4752 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4753 let excerpt_range = excerpt_range.to_offset(buffer);
4754 buffer
4755 .edited_ranges_for_transaction::<usize>(transaction)
4756 .all(|range| {
4757 excerpt_range.start <= range.start
4758 && excerpt_range.end >= range.end
4759 })
4760 })?;
4761
4762 if all_edits_within_excerpt {
4763 return Ok(());
4764 }
4765 }
4766 }
4767 }
4768 } else {
4769 return Ok(());
4770 }
4771
4772 let mut ranges_to_highlight = Vec::new();
4773 let excerpt_buffer = cx.new_model(|cx| {
4774 let mut multibuffer =
4775 MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
4776 for (buffer_handle, transaction) in &entries {
4777 let buffer = buffer_handle.read(cx);
4778 ranges_to_highlight.extend(
4779 multibuffer.push_excerpts_with_context_lines(
4780 buffer_handle.clone(),
4781 buffer
4782 .edited_ranges_for_transaction::<usize>(transaction)
4783 .collect(),
4784 DEFAULT_MULTIBUFFER_CONTEXT,
4785 cx,
4786 ),
4787 );
4788 }
4789 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4790 multibuffer
4791 })?;
4792
4793 workspace.update(&mut cx, |workspace, cx| {
4794 let project = workspace.project().clone();
4795 let editor =
4796 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4797 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4798 editor.update(cx, |editor, cx| {
4799 editor.highlight_background::<Self>(
4800 &ranges_to_highlight,
4801 |theme| theme.editor_highlighted_line_background,
4802 cx,
4803 );
4804 });
4805 })?;
4806
4807 Ok(())
4808 }
4809
4810 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4811 let project = self.project.clone()?;
4812 let buffer = self.buffer.read(cx);
4813 let newest_selection = self.selections.newest_anchor().clone();
4814 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4815 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4816 if start_buffer != end_buffer {
4817 return None;
4818 }
4819
4820 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4821 cx.background_executor()
4822 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4823 .await;
4824
4825 let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
4826 project.code_actions(&start_buffer, start..end, cx)
4827 }) {
4828 code_actions.await
4829 } else {
4830 Vec::new()
4831 };
4832
4833 this.update(&mut cx, |this, cx| {
4834 this.available_code_actions = if actions.is_empty() {
4835 None
4836 } else {
4837 Some((
4838 Location {
4839 buffer: start_buffer,
4840 range: start..end,
4841 },
4842 actions.into(),
4843 ))
4844 };
4845 cx.notify();
4846 })
4847 .log_err();
4848 }));
4849 None
4850 }
4851
4852 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4853 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4854 self.show_git_blame_inline = false;
4855
4856 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4857 cx.background_executor().timer(delay).await;
4858
4859 this.update(&mut cx, |this, cx| {
4860 this.show_git_blame_inline = true;
4861 cx.notify();
4862 })
4863 .log_err();
4864 }));
4865 }
4866 }
4867
4868 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4869 if self.pending_rename.is_some() {
4870 return None;
4871 }
4872
4873 let project = self.project.clone()?;
4874 let buffer = self.buffer.read(cx);
4875 let newest_selection = self.selections.newest_anchor().clone();
4876 let cursor_position = newest_selection.head();
4877 let (cursor_buffer, cursor_buffer_position) =
4878 buffer.text_anchor_for_position(cursor_position, cx)?;
4879 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4880 if cursor_buffer != tail_buffer {
4881 return None;
4882 }
4883
4884 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4885 cx.background_executor()
4886 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
4887 .await;
4888
4889 let highlights = if let Some(highlights) = project
4890 .update(&mut cx, |project, cx| {
4891 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4892 })
4893 .log_err()
4894 {
4895 highlights.await.log_err()
4896 } else {
4897 None
4898 };
4899
4900 if let Some(highlights) = highlights {
4901 this.update(&mut cx, |this, cx| {
4902 if this.pending_rename.is_some() {
4903 return;
4904 }
4905
4906 let buffer_id = cursor_position.buffer_id;
4907 let buffer = this.buffer.read(cx);
4908 if !buffer
4909 .text_anchor_for_position(cursor_position, cx)
4910 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4911 {
4912 return;
4913 }
4914
4915 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4916 let mut write_ranges = Vec::new();
4917 let mut read_ranges = Vec::new();
4918 for highlight in highlights {
4919 for (excerpt_id, excerpt_range) in
4920 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4921 {
4922 let start = highlight
4923 .range
4924 .start
4925 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4926 let end = highlight
4927 .range
4928 .end
4929 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4930 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4931 continue;
4932 }
4933
4934 let range = Anchor {
4935 buffer_id,
4936 excerpt_id,
4937 text_anchor: start,
4938 }..Anchor {
4939 buffer_id,
4940 excerpt_id,
4941 text_anchor: end,
4942 };
4943 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4944 write_ranges.push(range);
4945 } else {
4946 read_ranges.push(range);
4947 }
4948 }
4949 }
4950
4951 this.highlight_background::<DocumentHighlightRead>(
4952 &read_ranges,
4953 |theme| theme.editor_document_highlight_read_background,
4954 cx,
4955 );
4956 this.highlight_background::<DocumentHighlightWrite>(
4957 &write_ranges,
4958 |theme| theme.editor_document_highlight_write_background,
4959 cx,
4960 );
4961 cx.notify();
4962 })
4963 .log_err();
4964 }
4965 }));
4966 None
4967 }
4968
4969 pub fn refresh_inline_completion(
4970 &mut self,
4971 debounce: bool,
4972 user_requested: bool,
4973 cx: &mut ViewContext<Self>,
4974 ) -> Option<()> {
4975 let provider = self.inline_completion_provider()?;
4976 let cursor = self.selections.newest_anchor().head();
4977 let (buffer, cursor_buffer_position) =
4978 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4979 if !user_requested
4980 && !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4981 {
4982 self.discard_inline_completion(false, cx);
4983 return None;
4984 }
4985
4986 self.update_visible_inline_completion(cx);
4987 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4988 Some(())
4989 }
4990
4991 fn cycle_inline_completion(
4992 &mut self,
4993 direction: Direction,
4994 cx: &mut ViewContext<Self>,
4995 ) -> Option<()> {
4996 let provider = self.inline_completion_provider()?;
4997 let cursor = self.selections.newest_anchor().head();
4998 let (buffer, cursor_buffer_position) =
4999 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5000 if !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx) {
5001 return None;
5002 }
5003
5004 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5005 self.update_visible_inline_completion(cx);
5006
5007 Some(())
5008 }
5009
5010 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5011 if !self.has_active_inline_completion(cx) {
5012 self.refresh_inline_completion(false, true, cx);
5013 return;
5014 }
5015
5016 self.update_visible_inline_completion(cx);
5017 }
5018
5019 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5020 self.show_cursor_names(cx);
5021 }
5022
5023 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5024 self.show_cursor_names = true;
5025 cx.notify();
5026 cx.spawn(|this, mut cx| async move {
5027 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5028 this.update(&mut cx, |this, cx| {
5029 this.show_cursor_names = false;
5030 cx.notify()
5031 })
5032 .ok()
5033 })
5034 .detach();
5035 }
5036
5037 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5038 if self.has_active_inline_completion(cx) {
5039 self.cycle_inline_completion(Direction::Next, cx);
5040 } else {
5041 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5042 if is_copilot_disabled {
5043 cx.propagate();
5044 }
5045 }
5046 }
5047
5048 pub fn previous_inline_completion(
5049 &mut self,
5050 _: &PreviousInlineCompletion,
5051 cx: &mut ViewContext<Self>,
5052 ) {
5053 if self.has_active_inline_completion(cx) {
5054 self.cycle_inline_completion(Direction::Prev, cx);
5055 } else {
5056 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5057 if is_copilot_disabled {
5058 cx.propagate();
5059 }
5060 }
5061 }
5062
5063 pub fn accept_inline_completion(
5064 &mut self,
5065 _: &AcceptInlineCompletion,
5066 cx: &mut ViewContext<Self>,
5067 ) {
5068 let Some((completion, delete_range)) = self.take_active_inline_completion(cx) else {
5069 return;
5070 };
5071 if let Some(provider) = self.inline_completion_provider() {
5072 provider.accept(cx);
5073 }
5074
5075 cx.emit(EditorEvent::InputHandled {
5076 utf16_range_to_replace: None,
5077 text: completion.text.to_string().into(),
5078 });
5079
5080 if let Some(range) = delete_range {
5081 self.change_selections(None, cx, |s| s.select_ranges([range]))
5082 }
5083 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5084 self.refresh_inline_completion(true, true, cx);
5085 cx.notify();
5086 }
5087
5088 pub fn accept_partial_inline_completion(
5089 &mut self,
5090 _: &AcceptPartialInlineCompletion,
5091 cx: &mut ViewContext<Self>,
5092 ) {
5093 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5094 if let Some((completion, delete_range)) = self.take_active_inline_completion(cx) {
5095 let mut partial_completion = completion
5096 .text
5097 .chars()
5098 .by_ref()
5099 .take_while(|c| c.is_alphabetic())
5100 .collect::<String>();
5101 if partial_completion.is_empty() {
5102 partial_completion = completion
5103 .text
5104 .chars()
5105 .by_ref()
5106 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5107 .collect::<String>();
5108 }
5109
5110 cx.emit(EditorEvent::InputHandled {
5111 utf16_range_to_replace: None,
5112 text: partial_completion.clone().into(),
5113 });
5114
5115 if let Some(range) = delete_range {
5116 self.change_selections(None, cx, |s| s.select_ranges([range]))
5117 }
5118 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5119
5120 self.refresh_inline_completion(true, true, cx);
5121 cx.notify();
5122 }
5123 }
5124 }
5125
5126 fn discard_inline_completion(
5127 &mut self,
5128 should_report_inline_completion_event: bool,
5129 cx: &mut ViewContext<Self>,
5130 ) -> bool {
5131 if let Some(provider) = self.inline_completion_provider() {
5132 provider.discard(should_report_inline_completion_event, cx);
5133 }
5134
5135 self.take_active_inline_completion(cx).is_some()
5136 }
5137
5138 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5139 if let Some(completion) = self.active_inline_completion.as_ref() {
5140 let buffer = self.buffer.read(cx).read(cx);
5141 completion.0.position.is_valid(&buffer)
5142 } else {
5143 false
5144 }
5145 }
5146
5147 fn take_active_inline_completion(
5148 &mut self,
5149 cx: &mut ViewContext<Self>,
5150 ) -> Option<(Inlay, Option<Range<Anchor>>)> {
5151 let completion = self.active_inline_completion.take()?;
5152 self.display_map.update(cx, |map, cx| {
5153 map.splice_inlays(vec![completion.0.id], Default::default(), cx);
5154 });
5155 let buffer = self.buffer.read(cx).read(cx);
5156
5157 if completion.0.position.is_valid(&buffer) {
5158 Some(completion)
5159 } else {
5160 None
5161 }
5162 }
5163
5164 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5165 let selection = self.selections.newest_anchor();
5166 let cursor = selection.head();
5167
5168 let excerpt_id = cursor.excerpt_id;
5169
5170 if self.context_menu.read().is_none()
5171 && self.completion_tasks.is_empty()
5172 && selection.start == selection.end
5173 {
5174 if let Some(provider) = self.inline_completion_provider() {
5175 if let Some((buffer, cursor_buffer_position)) =
5176 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5177 {
5178 if let Some((text, text_anchor_range)) =
5179 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5180 {
5181 let text = Rope::from(text);
5182 let mut to_remove = Vec::new();
5183 if let Some(completion) = self.active_inline_completion.take() {
5184 to_remove.push(completion.0.id);
5185 }
5186
5187 let completion_inlay =
5188 Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
5189
5190 let multibuffer_anchor_range = text_anchor_range.and_then(|range| {
5191 let snapshot = self.buffer.read(cx).snapshot(cx);
5192 Some(
5193 snapshot.anchor_in_excerpt(excerpt_id, range.start)?
5194 ..snapshot.anchor_in_excerpt(excerpt_id, range.end)?,
5195 )
5196 });
5197 self.active_inline_completion =
5198 Some((completion_inlay.clone(), multibuffer_anchor_range));
5199
5200 self.display_map.update(cx, move |map, cx| {
5201 map.splice_inlays(to_remove, vec![completion_inlay], cx)
5202 });
5203 cx.notify();
5204 return;
5205 }
5206 }
5207 }
5208 }
5209
5210 self.discard_inline_completion(false, cx);
5211 }
5212
5213 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5214 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5215 }
5216
5217 fn render_code_actions_indicator(
5218 &self,
5219 _style: &EditorStyle,
5220 row: DisplayRow,
5221 is_active: bool,
5222 cx: &mut ViewContext<Self>,
5223 ) -> Option<IconButton> {
5224 if self.available_code_actions.is_some() {
5225 Some(
5226 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5227 .shape(ui::IconButtonShape::Square)
5228 .icon_size(IconSize::XSmall)
5229 .icon_color(Color::Muted)
5230 .selected(is_active)
5231 .on_click(cx.listener(move |editor, _e, cx| {
5232 editor.focus(cx);
5233 editor.toggle_code_actions(
5234 &ToggleCodeActions {
5235 deployed_from_indicator: Some(row),
5236 },
5237 cx,
5238 );
5239 })),
5240 )
5241 } else {
5242 None
5243 }
5244 }
5245
5246 fn clear_tasks(&mut self) {
5247 self.tasks.clear()
5248 }
5249
5250 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5251 if let Some(_) = self.tasks.insert(key, value) {
5252 // This case should hopefully be rare, but just in case...
5253 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5254 }
5255 }
5256
5257 fn render_run_indicator(
5258 &self,
5259 _style: &EditorStyle,
5260 is_active: bool,
5261 row: DisplayRow,
5262 cx: &mut ViewContext<Self>,
5263 ) -> IconButton {
5264 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5265 .shape(ui::IconButtonShape::Square)
5266 .icon_size(IconSize::XSmall)
5267 .icon_color(Color::Muted)
5268 .selected(is_active)
5269 .on_click(cx.listener(move |editor, _e, cx| {
5270 editor.focus(cx);
5271 editor.toggle_code_actions(
5272 &ToggleCodeActions {
5273 deployed_from_indicator: Some(row),
5274 },
5275 cx,
5276 );
5277 }))
5278 }
5279
5280 fn close_hunk_diff_button(
5281 &self,
5282 hunk: HoveredHunk,
5283 row: DisplayRow,
5284 cx: &mut ViewContext<Self>,
5285 ) -> IconButton {
5286 IconButton::new(
5287 ("close_hunk_diff_indicator", row.0 as usize),
5288 ui::IconName::Close,
5289 )
5290 .shape(ui::IconButtonShape::Square)
5291 .icon_size(IconSize::XSmall)
5292 .icon_color(Color::Muted)
5293 .tooltip(|cx| Tooltip::for_action("Close hunk diff", &ToggleHunkDiff, cx))
5294 .on_click(cx.listener(move |editor, _e, cx| editor.toggle_hovered_hunk(&hunk, cx)))
5295 }
5296
5297 pub fn context_menu_visible(&self) -> bool {
5298 self.context_menu
5299 .read()
5300 .as_ref()
5301 .map_or(false, |menu| menu.visible())
5302 }
5303
5304 fn render_context_menu(
5305 &self,
5306 cursor_position: DisplayPoint,
5307 style: &EditorStyle,
5308 max_height: Pixels,
5309 cx: &mut ViewContext<Editor>,
5310 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5311 self.context_menu.read().as_ref().map(|menu| {
5312 menu.render(
5313 cursor_position,
5314 style,
5315 max_height,
5316 self.workspace.as_ref().map(|(w, _)| w.clone()),
5317 cx,
5318 )
5319 })
5320 }
5321
5322 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5323 cx.notify();
5324 self.completion_tasks.clear();
5325 let context_menu = self.context_menu.write().take();
5326 if context_menu.is_some() {
5327 self.update_visible_inline_completion(cx);
5328 }
5329 context_menu
5330 }
5331
5332 pub fn insert_snippet(
5333 &mut self,
5334 insertion_ranges: &[Range<usize>],
5335 snippet: Snippet,
5336 cx: &mut ViewContext<Self>,
5337 ) -> Result<()> {
5338 struct Tabstop<T> {
5339 is_end_tabstop: bool,
5340 ranges: Vec<Range<T>>,
5341 }
5342
5343 let tabstops = self.buffer.update(cx, |buffer, cx| {
5344 let snippet_text: Arc<str> = snippet.text.clone().into();
5345 buffer.edit(
5346 insertion_ranges
5347 .iter()
5348 .cloned()
5349 .map(|range| (range, snippet_text.clone())),
5350 Some(AutoindentMode::EachLine),
5351 cx,
5352 );
5353
5354 let snapshot = &*buffer.read(cx);
5355 let snippet = &snippet;
5356 snippet
5357 .tabstops
5358 .iter()
5359 .map(|tabstop| {
5360 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5361 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5362 });
5363 let mut tabstop_ranges = tabstop
5364 .iter()
5365 .flat_map(|tabstop_range| {
5366 let mut delta = 0_isize;
5367 insertion_ranges.iter().map(move |insertion_range| {
5368 let insertion_start = insertion_range.start as isize + delta;
5369 delta +=
5370 snippet.text.len() as isize - insertion_range.len() as isize;
5371
5372 let start = ((insertion_start + tabstop_range.start) as usize)
5373 .min(snapshot.len());
5374 let end = ((insertion_start + tabstop_range.end) as usize)
5375 .min(snapshot.len());
5376 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5377 })
5378 })
5379 .collect::<Vec<_>>();
5380 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5381
5382 Tabstop {
5383 is_end_tabstop,
5384 ranges: tabstop_ranges,
5385 }
5386 })
5387 .collect::<Vec<_>>()
5388 });
5389 if let Some(tabstop) = tabstops.first() {
5390 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5391 s.select_ranges(tabstop.ranges.iter().cloned());
5392 });
5393
5394 // If we're already at the last tabstop and it's at the end of the snippet,
5395 // we're done, we don't need to keep the state around.
5396 if !tabstop.is_end_tabstop {
5397 let ranges = tabstops
5398 .into_iter()
5399 .map(|tabstop| tabstop.ranges)
5400 .collect::<Vec<_>>();
5401 self.snippet_stack.push(SnippetState {
5402 active_index: 0,
5403 ranges,
5404 });
5405 }
5406
5407 // Check whether the just-entered snippet ends with an auto-closable bracket.
5408 if self.autoclose_regions.is_empty() {
5409 let snapshot = self.buffer.read(cx).snapshot(cx);
5410 for selection in &mut self.selections.all::<Point>(cx) {
5411 let selection_head = selection.head();
5412 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5413 continue;
5414 };
5415
5416 let mut bracket_pair = None;
5417 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5418 let prev_chars = snapshot
5419 .reversed_chars_at(selection_head)
5420 .collect::<String>();
5421 for (pair, enabled) in scope.brackets() {
5422 if enabled
5423 && pair.close
5424 && prev_chars.starts_with(pair.start.as_str())
5425 && next_chars.starts_with(pair.end.as_str())
5426 {
5427 bracket_pair = Some(pair.clone());
5428 break;
5429 }
5430 }
5431 if let Some(pair) = bracket_pair {
5432 let start = snapshot.anchor_after(selection_head);
5433 let end = snapshot.anchor_after(selection_head);
5434 self.autoclose_regions.push(AutocloseRegion {
5435 selection_id: selection.id,
5436 range: start..end,
5437 pair,
5438 });
5439 }
5440 }
5441 }
5442 }
5443 Ok(())
5444 }
5445
5446 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5447 self.move_to_snippet_tabstop(Bias::Right, cx)
5448 }
5449
5450 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5451 self.move_to_snippet_tabstop(Bias::Left, cx)
5452 }
5453
5454 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5455 if let Some(mut snippet) = self.snippet_stack.pop() {
5456 match bias {
5457 Bias::Left => {
5458 if snippet.active_index > 0 {
5459 snippet.active_index -= 1;
5460 } else {
5461 self.snippet_stack.push(snippet);
5462 return false;
5463 }
5464 }
5465 Bias::Right => {
5466 if snippet.active_index + 1 < snippet.ranges.len() {
5467 snippet.active_index += 1;
5468 } else {
5469 self.snippet_stack.push(snippet);
5470 return false;
5471 }
5472 }
5473 }
5474 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5475 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5476 s.select_anchor_ranges(current_ranges.iter().cloned())
5477 });
5478 // If snippet state is not at the last tabstop, push it back on the stack
5479 if snippet.active_index + 1 < snippet.ranges.len() {
5480 self.snippet_stack.push(snippet);
5481 }
5482 return true;
5483 }
5484 }
5485
5486 false
5487 }
5488
5489 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5490 self.transact(cx, |this, cx| {
5491 this.select_all(&SelectAll, cx);
5492 this.insert("", cx);
5493 });
5494 }
5495
5496 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5497 self.transact(cx, |this, cx| {
5498 this.select_autoclose_pair(cx);
5499 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5500 if !this.linked_edit_ranges.is_empty() {
5501 let selections = this.selections.all::<MultiBufferPoint>(cx);
5502 let snapshot = this.buffer.read(cx).snapshot(cx);
5503
5504 for selection in selections.iter() {
5505 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5506 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5507 if selection_start.buffer_id != selection_end.buffer_id {
5508 continue;
5509 }
5510 if let Some(ranges) =
5511 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5512 {
5513 for (buffer, entries) in ranges {
5514 linked_ranges.entry(buffer).or_default().extend(entries);
5515 }
5516 }
5517 }
5518 }
5519
5520 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5521 if !this.selections.line_mode {
5522 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5523 for selection in &mut selections {
5524 if selection.is_empty() {
5525 let old_head = selection.head();
5526 let mut new_head =
5527 movement::left(&display_map, old_head.to_display_point(&display_map))
5528 .to_point(&display_map);
5529 if let Some((buffer, line_buffer_range)) = display_map
5530 .buffer_snapshot
5531 .buffer_line_for_row(MultiBufferRow(old_head.row))
5532 {
5533 let indent_size =
5534 buffer.indent_size_for_line(line_buffer_range.start.row);
5535 let indent_len = match indent_size.kind {
5536 IndentKind::Space => {
5537 buffer.settings_at(line_buffer_range.start, cx).tab_size
5538 }
5539 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5540 };
5541 if old_head.column <= indent_size.len && old_head.column > 0 {
5542 let indent_len = indent_len.get();
5543 new_head = cmp::min(
5544 new_head,
5545 MultiBufferPoint::new(
5546 old_head.row,
5547 ((old_head.column - 1) / indent_len) * indent_len,
5548 ),
5549 );
5550 }
5551 }
5552
5553 selection.set_head(new_head, SelectionGoal::None);
5554 }
5555 }
5556 }
5557
5558 this.signature_help_state.set_backspace_pressed(true);
5559 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5560 this.insert("", cx);
5561 let empty_str: Arc<str> = Arc::from("");
5562 for (buffer, edits) in linked_ranges {
5563 let snapshot = buffer.read(cx).snapshot();
5564 use text::ToPoint as TP;
5565
5566 let edits = edits
5567 .into_iter()
5568 .map(|range| {
5569 let end_point = TP::to_point(&range.end, &snapshot);
5570 let mut start_point = TP::to_point(&range.start, &snapshot);
5571
5572 if end_point == start_point {
5573 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5574 .saturating_sub(1);
5575 start_point = TP::to_point(&offset, &snapshot);
5576 };
5577
5578 (start_point..end_point, empty_str.clone())
5579 })
5580 .sorted_by_key(|(range, _)| range.start)
5581 .collect::<Vec<_>>();
5582 buffer.update(cx, |this, cx| {
5583 this.edit(edits, None, cx);
5584 })
5585 }
5586 this.refresh_inline_completion(true, false, cx);
5587 linked_editing_ranges::refresh_linked_ranges(this, cx);
5588 });
5589 }
5590
5591 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5592 self.transact(cx, |this, cx| {
5593 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5594 let line_mode = s.line_mode;
5595 s.move_with(|map, selection| {
5596 if selection.is_empty() && !line_mode {
5597 let cursor = movement::right(map, selection.head());
5598 selection.end = cursor;
5599 selection.reversed = true;
5600 selection.goal = SelectionGoal::None;
5601 }
5602 })
5603 });
5604 this.insert("", cx);
5605 this.refresh_inline_completion(true, false, cx);
5606 });
5607 }
5608
5609 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5610 if self.move_to_prev_snippet_tabstop(cx) {
5611 return;
5612 }
5613
5614 self.outdent(&Outdent, cx);
5615 }
5616
5617 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5618 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5619 return;
5620 }
5621
5622 let mut selections = self.selections.all_adjusted(cx);
5623 let buffer = self.buffer.read(cx);
5624 let snapshot = buffer.snapshot(cx);
5625 let rows_iter = selections.iter().map(|s| s.head().row);
5626 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5627
5628 let mut edits = Vec::new();
5629 let mut prev_edited_row = 0;
5630 let mut row_delta = 0;
5631 for selection in &mut selections {
5632 if selection.start.row != prev_edited_row {
5633 row_delta = 0;
5634 }
5635 prev_edited_row = selection.end.row;
5636
5637 // If the selection is non-empty, then increase the indentation of the selected lines.
5638 if !selection.is_empty() {
5639 row_delta =
5640 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5641 continue;
5642 }
5643
5644 // If the selection is empty and the cursor is in the leading whitespace before the
5645 // suggested indentation, then auto-indent the line.
5646 let cursor = selection.head();
5647 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5648 if let Some(suggested_indent) =
5649 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5650 {
5651 if cursor.column < suggested_indent.len
5652 && cursor.column <= current_indent.len
5653 && current_indent.len <= suggested_indent.len
5654 {
5655 selection.start = Point::new(cursor.row, suggested_indent.len);
5656 selection.end = selection.start;
5657 if row_delta == 0 {
5658 edits.extend(Buffer::edit_for_indent_size_adjustment(
5659 cursor.row,
5660 current_indent,
5661 suggested_indent,
5662 ));
5663 row_delta = suggested_indent.len - current_indent.len;
5664 }
5665 continue;
5666 }
5667 }
5668
5669 // Otherwise, insert a hard or soft tab.
5670 let settings = buffer.settings_at(cursor, cx);
5671 let tab_size = if settings.hard_tabs {
5672 IndentSize::tab()
5673 } else {
5674 let tab_size = settings.tab_size.get();
5675 let char_column = snapshot
5676 .text_for_range(Point::new(cursor.row, 0)..cursor)
5677 .flat_map(str::chars)
5678 .count()
5679 + row_delta as usize;
5680 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5681 IndentSize::spaces(chars_to_next_tab_stop)
5682 };
5683 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5684 selection.end = selection.start;
5685 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5686 row_delta += tab_size.len;
5687 }
5688
5689 self.transact(cx, |this, cx| {
5690 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5691 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5692 this.refresh_inline_completion(true, false, cx);
5693 });
5694 }
5695
5696 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5697 if self.read_only(cx) {
5698 return;
5699 }
5700 let mut selections = self.selections.all::<Point>(cx);
5701 let mut prev_edited_row = 0;
5702 let mut row_delta = 0;
5703 let mut edits = Vec::new();
5704 let buffer = self.buffer.read(cx);
5705 let snapshot = buffer.snapshot(cx);
5706 for selection in &mut selections {
5707 if selection.start.row != prev_edited_row {
5708 row_delta = 0;
5709 }
5710 prev_edited_row = selection.end.row;
5711
5712 row_delta =
5713 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5714 }
5715
5716 self.transact(cx, |this, cx| {
5717 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5718 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5719 });
5720 }
5721
5722 fn indent_selection(
5723 buffer: &MultiBuffer,
5724 snapshot: &MultiBufferSnapshot,
5725 selection: &mut Selection<Point>,
5726 edits: &mut Vec<(Range<Point>, String)>,
5727 delta_for_start_row: u32,
5728 cx: &AppContext,
5729 ) -> u32 {
5730 let settings = buffer.settings_at(selection.start, cx);
5731 let tab_size = settings.tab_size.get();
5732 let indent_kind = if settings.hard_tabs {
5733 IndentKind::Tab
5734 } else {
5735 IndentKind::Space
5736 };
5737 let mut start_row = selection.start.row;
5738 let mut end_row = selection.end.row + 1;
5739
5740 // If a selection ends at the beginning of a line, don't indent
5741 // that last line.
5742 if selection.end.column == 0 && selection.end.row > selection.start.row {
5743 end_row -= 1;
5744 }
5745
5746 // Avoid re-indenting a row that has already been indented by a
5747 // previous selection, but still update this selection's column
5748 // to reflect that indentation.
5749 if delta_for_start_row > 0 {
5750 start_row += 1;
5751 selection.start.column += delta_for_start_row;
5752 if selection.end.row == selection.start.row {
5753 selection.end.column += delta_for_start_row;
5754 }
5755 }
5756
5757 let mut delta_for_end_row = 0;
5758 let has_multiple_rows = start_row + 1 != end_row;
5759 for row in start_row..end_row {
5760 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5761 let indent_delta = match (current_indent.kind, indent_kind) {
5762 (IndentKind::Space, IndentKind::Space) => {
5763 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5764 IndentSize::spaces(columns_to_next_tab_stop)
5765 }
5766 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5767 (_, IndentKind::Tab) => IndentSize::tab(),
5768 };
5769
5770 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5771 0
5772 } else {
5773 selection.start.column
5774 };
5775 let row_start = Point::new(row, start);
5776 edits.push((
5777 row_start..row_start,
5778 indent_delta.chars().collect::<String>(),
5779 ));
5780
5781 // Update this selection's endpoints to reflect the indentation.
5782 if row == selection.start.row {
5783 selection.start.column += indent_delta.len;
5784 }
5785 if row == selection.end.row {
5786 selection.end.column += indent_delta.len;
5787 delta_for_end_row = indent_delta.len;
5788 }
5789 }
5790
5791 if selection.start.row == selection.end.row {
5792 delta_for_start_row + delta_for_end_row
5793 } else {
5794 delta_for_end_row
5795 }
5796 }
5797
5798 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5799 if self.read_only(cx) {
5800 return;
5801 }
5802 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5803 let selections = self.selections.all::<Point>(cx);
5804 let mut deletion_ranges = Vec::new();
5805 let mut last_outdent = None;
5806 {
5807 let buffer = self.buffer.read(cx);
5808 let snapshot = buffer.snapshot(cx);
5809 for selection in &selections {
5810 let settings = buffer.settings_at(selection.start, cx);
5811 let tab_size = settings.tab_size.get();
5812 let mut rows = selection.spanned_rows(false, &display_map);
5813
5814 // Avoid re-outdenting a row that has already been outdented by a
5815 // previous selection.
5816 if let Some(last_row) = last_outdent {
5817 if last_row == rows.start {
5818 rows.start = rows.start.next_row();
5819 }
5820 }
5821 let has_multiple_rows = rows.len() > 1;
5822 for row in rows.iter_rows() {
5823 let indent_size = snapshot.indent_size_for_line(row);
5824 if indent_size.len > 0 {
5825 let deletion_len = match indent_size.kind {
5826 IndentKind::Space => {
5827 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5828 if columns_to_prev_tab_stop == 0 {
5829 tab_size
5830 } else {
5831 columns_to_prev_tab_stop
5832 }
5833 }
5834 IndentKind::Tab => 1,
5835 };
5836 let start = if has_multiple_rows
5837 || deletion_len > selection.start.column
5838 || indent_size.len < selection.start.column
5839 {
5840 0
5841 } else {
5842 selection.start.column - deletion_len
5843 };
5844 deletion_ranges.push(
5845 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5846 );
5847 last_outdent = Some(row);
5848 }
5849 }
5850 }
5851 }
5852
5853 self.transact(cx, |this, cx| {
5854 this.buffer.update(cx, |buffer, cx| {
5855 let empty_str: Arc<str> = Arc::default();
5856 buffer.edit(
5857 deletion_ranges
5858 .into_iter()
5859 .map(|range| (range, empty_str.clone())),
5860 None,
5861 cx,
5862 );
5863 });
5864 let selections = this.selections.all::<usize>(cx);
5865 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5866 });
5867 }
5868
5869 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5870 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5871 let selections = self.selections.all::<Point>(cx);
5872
5873 let mut new_cursors = Vec::new();
5874 let mut edit_ranges = Vec::new();
5875 let mut selections = selections.iter().peekable();
5876 while let Some(selection) = selections.next() {
5877 let mut rows = selection.spanned_rows(false, &display_map);
5878 let goal_display_column = selection.head().to_display_point(&display_map).column();
5879
5880 // Accumulate contiguous regions of rows that we want to delete.
5881 while let Some(next_selection) = selections.peek() {
5882 let next_rows = next_selection.spanned_rows(false, &display_map);
5883 if next_rows.start <= rows.end {
5884 rows.end = next_rows.end;
5885 selections.next().unwrap();
5886 } else {
5887 break;
5888 }
5889 }
5890
5891 let buffer = &display_map.buffer_snapshot;
5892 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5893 let edit_end;
5894 let cursor_buffer_row;
5895 if buffer.max_point().row >= rows.end.0 {
5896 // If there's a line after the range, delete the \n from the end of the row range
5897 // and position the cursor on the next line.
5898 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5899 cursor_buffer_row = rows.end;
5900 } else {
5901 // If there isn't a line after the range, delete the \n from the line before the
5902 // start of the row range and position the cursor there.
5903 edit_start = edit_start.saturating_sub(1);
5904 edit_end = buffer.len();
5905 cursor_buffer_row = rows.start.previous_row();
5906 }
5907
5908 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5909 *cursor.column_mut() =
5910 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5911
5912 new_cursors.push((
5913 selection.id,
5914 buffer.anchor_after(cursor.to_point(&display_map)),
5915 ));
5916 edit_ranges.push(edit_start..edit_end);
5917 }
5918
5919 self.transact(cx, |this, cx| {
5920 let buffer = this.buffer.update(cx, |buffer, cx| {
5921 let empty_str: Arc<str> = Arc::default();
5922 buffer.edit(
5923 edit_ranges
5924 .into_iter()
5925 .map(|range| (range, empty_str.clone())),
5926 None,
5927 cx,
5928 );
5929 buffer.snapshot(cx)
5930 });
5931 let new_selections = new_cursors
5932 .into_iter()
5933 .map(|(id, cursor)| {
5934 let cursor = cursor.to_point(&buffer);
5935 Selection {
5936 id,
5937 start: cursor,
5938 end: cursor,
5939 reversed: false,
5940 goal: SelectionGoal::None,
5941 }
5942 })
5943 .collect();
5944
5945 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5946 s.select(new_selections);
5947 });
5948 });
5949 }
5950
5951 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5952 if self.read_only(cx) {
5953 return;
5954 }
5955 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5956 for selection in self.selections.all::<Point>(cx) {
5957 let start = MultiBufferRow(selection.start.row);
5958 let end = if selection.start.row == selection.end.row {
5959 MultiBufferRow(selection.start.row + 1)
5960 } else {
5961 MultiBufferRow(selection.end.row)
5962 };
5963
5964 if let Some(last_row_range) = row_ranges.last_mut() {
5965 if start <= last_row_range.end {
5966 last_row_range.end = end;
5967 continue;
5968 }
5969 }
5970 row_ranges.push(start..end);
5971 }
5972
5973 let snapshot = self.buffer.read(cx).snapshot(cx);
5974 let mut cursor_positions = Vec::new();
5975 for row_range in &row_ranges {
5976 let anchor = snapshot.anchor_before(Point::new(
5977 row_range.end.previous_row().0,
5978 snapshot.line_len(row_range.end.previous_row()),
5979 ));
5980 cursor_positions.push(anchor..anchor);
5981 }
5982
5983 self.transact(cx, |this, cx| {
5984 for row_range in row_ranges.into_iter().rev() {
5985 for row in row_range.iter_rows().rev() {
5986 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5987 let next_line_row = row.next_row();
5988 let indent = snapshot.indent_size_for_line(next_line_row);
5989 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5990
5991 let replace = if snapshot.line_len(next_line_row) > indent.len {
5992 " "
5993 } else {
5994 ""
5995 };
5996
5997 this.buffer.update(cx, |buffer, cx| {
5998 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5999 });
6000 }
6001 }
6002
6003 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6004 s.select_anchor_ranges(cursor_positions)
6005 });
6006 });
6007 }
6008
6009 pub fn sort_lines_case_sensitive(
6010 &mut self,
6011 _: &SortLinesCaseSensitive,
6012 cx: &mut ViewContext<Self>,
6013 ) {
6014 self.manipulate_lines(cx, |lines| lines.sort())
6015 }
6016
6017 pub fn sort_lines_case_insensitive(
6018 &mut self,
6019 _: &SortLinesCaseInsensitive,
6020 cx: &mut ViewContext<Self>,
6021 ) {
6022 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6023 }
6024
6025 pub fn unique_lines_case_insensitive(
6026 &mut self,
6027 _: &UniqueLinesCaseInsensitive,
6028 cx: &mut ViewContext<Self>,
6029 ) {
6030 self.manipulate_lines(cx, |lines| {
6031 let mut seen = HashSet::default();
6032 lines.retain(|line| seen.insert(line.to_lowercase()));
6033 })
6034 }
6035
6036 pub fn unique_lines_case_sensitive(
6037 &mut self,
6038 _: &UniqueLinesCaseSensitive,
6039 cx: &mut ViewContext<Self>,
6040 ) {
6041 self.manipulate_lines(cx, |lines| {
6042 let mut seen = HashSet::default();
6043 lines.retain(|line| seen.insert(*line));
6044 })
6045 }
6046
6047 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6048 let mut revert_changes = HashMap::default();
6049 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6050 for hunk in hunks_for_rows(
6051 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6052 &multi_buffer_snapshot,
6053 ) {
6054 Self::prepare_revert_change(&mut revert_changes, &self.buffer(), &hunk, cx);
6055 }
6056 if !revert_changes.is_empty() {
6057 self.transact(cx, |editor, cx| {
6058 editor.revert(revert_changes, cx);
6059 });
6060 }
6061 }
6062
6063 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6064 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6065 if !revert_changes.is_empty() {
6066 self.transact(cx, |editor, cx| {
6067 editor.revert(revert_changes, cx);
6068 });
6069 }
6070 }
6071
6072 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6073 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6074 let project_path = buffer.read(cx).project_path(cx)?;
6075 let project = self.project.as_ref()?.read(cx);
6076 let entry = project.entry_for_path(&project_path, cx)?;
6077 let abs_path = project.absolute_path(&project_path, cx)?;
6078 let parent = if entry.is_symlink {
6079 abs_path.canonicalize().ok()?
6080 } else {
6081 abs_path
6082 }
6083 .parent()?
6084 .to_path_buf();
6085 Some(parent)
6086 }) {
6087 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6088 }
6089 }
6090
6091 fn gather_revert_changes(
6092 &mut self,
6093 selections: &[Selection<Anchor>],
6094 cx: &mut ViewContext<'_, Editor>,
6095 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6096 let mut revert_changes = HashMap::default();
6097 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6098 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6099 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6100 }
6101 revert_changes
6102 }
6103
6104 pub fn prepare_revert_change(
6105 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6106 multi_buffer: &Model<MultiBuffer>,
6107 hunk: &DiffHunk<MultiBufferRow>,
6108 cx: &AppContext,
6109 ) -> Option<()> {
6110 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6111 let buffer = buffer.read(cx);
6112 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6113 let buffer_snapshot = buffer.snapshot();
6114 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6115 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6116 probe
6117 .0
6118 .start
6119 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6120 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6121 }) {
6122 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6123 Some(())
6124 } else {
6125 None
6126 }
6127 }
6128
6129 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6130 self.manipulate_lines(cx, |lines| lines.reverse())
6131 }
6132
6133 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6134 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6135 }
6136
6137 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6138 where
6139 Fn: FnMut(&mut Vec<&str>),
6140 {
6141 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6142 let buffer = self.buffer.read(cx).snapshot(cx);
6143
6144 let mut edits = Vec::new();
6145
6146 let selections = self.selections.all::<Point>(cx);
6147 let mut selections = selections.iter().peekable();
6148 let mut contiguous_row_selections = Vec::new();
6149 let mut new_selections = Vec::new();
6150 let mut added_lines = 0;
6151 let mut removed_lines = 0;
6152
6153 while let Some(selection) = selections.next() {
6154 let (start_row, end_row) = consume_contiguous_rows(
6155 &mut contiguous_row_selections,
6156 selection,
6157 &display_map,
6158 &mut selections,
6159 );
6160
6161 let start_point = Point::new(start_row.0, 0);
6162 let end_point = Point::new(
6163 end_row.previous_row().0,
6164 buffer.line_len(end_row.previous_row()),
6165 );
6166 let text = buffer
6167 .text_for_range(start_point..end_point)
6168 .collect::<String>();
6169
6170 let mut lines = text.split('\n').collect_vec();
6171
6172 let lines_before = lines.len();
6173 callback(&mut lines);
6174 let lines_after = lines.len();
6175
6176 edits.push((start_point..end_point, lines.join("\n")));
6177
6178 // Selections must change based on added and removed line count
6179 let start_row =
6180 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6181 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6182 new_selections.push(Selection {
6183 id: selection.id,
6184 start: start_row,
6185 end: end_row,
6186 goal: SelectionGoal::None,
6187 reversed: selection.reversed,
6188 });
6189
6190 if lines_after > lines_before {
6191 added_lines += lines_after - lines_before;
6192 } else if lines_before > lines_after {
6193 removed_lines += lines_before - lines_after;
6194 }
6195 }
6196
6197 self.transact(cx, |this, cx| {
6198 let buffer = this.buffer.update(cx, |buffer, cx| {
6199 buffer.edit(edits, None, cx);
6200 buffer.snapshot(cx)
6201 });
6202
6203 // Recalculate offsets on newly edited buffer
6204 let new_selections = new_selections
6205 .iter()
6206 .map(|s| {
6207 let start_point = Point::new(s.start.0, 0);
6208 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6209 Selection {
6210 id: s.id,
6211 start: buffer.point_to_offset(start_point),
6212 end: buffer.point_to_offset(end_point),
6213 goal: s.goal,
6214 reversed: s.reversed,
6215 }
6216 })
6217 .collect();
6218
6219 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6220 s.select(new_selections);
6221 });
6222
6223 this.request_autoscroll(Autoscroll::fit(), cx);
6224 });
6225 }
6226
6227 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6228 self.manipulate_text(cx, |text| text.to_uppercase())
6229 }
6230
6231 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6232 self.manipulate_text(cx, |text| text.to_lowercase())
6233 }
6234
6235 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6236 self.manipulate_text(cx, |text| {
6237 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6238 // https://github.com/rutrum/convert-case/issues/16
6239 text.split('\n')
6240 .map(|line| line.to_case(Case::Title))
6241 .join("\n")
6242 })
6243 }
6244
6245 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6246 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6247 }
6248
6249 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6250 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6251 }
6252
6253 pub fn convert_to_upper_camel_case(
6254 &mut self,
6255 _: &ConvertToUpperCamelCase,
6256 cx: &mut ViewContext<Self>,
6257 ) {
6258 self.manipulate_text(cx, |text| {
6259 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6260 // https://github.com/rutrum/convert-case/issues/16
6261 text.split('\n')
6262 .map(|line| line.to_case(Case::UpperCamel))
6263 .join("\n")
6264 })
6265 }
6266
6267 pub fn convert_to_lower_camel_case(
6268 &mut self,
6269 _: &ConvertToLowerCamelCase,
6270 cx: &mut ViewContext<Self>,
6271 ) {
6272 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6273 }
6274
6275 pub fn convert_to_opposite_case(
6276 &mut self,
6277 _: &ConvertToOppositeCase,
6278 cx: &mut ViewContext<Self>,
6279 ) {
6280 self.manipulate_text(cx, |text| {
6281 text.chars()
6282 .fold(String::with_capacity(text.len()), |mut t, c| {
6283 if c.is_uppercase() {
6284 t.extend(c.to_lowercase());
6285 } else {
6286 t.extend(c.to_uppercase());
6287 }
6288 t
6289 })
6290 })
6291 }
6292
6293 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6294 where
6295 Fn: FnMut(&str) -> String,
6296 {
6297 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6298 let buffer = self.buffer.read(cx).snapshot(cx);
6299
6300 let mut new_selections = Vec::new();
6301 let mut edits = Vec::new();
6302 let mut selection_adjustment = 0i32;
6303
6304 for selection in self.selections.all::<usize>(cx) {
6305 let selection_is_empty = selection.is_empty();
6306
6307 let (start, end) = if selection_is_empty {
6308 let word_range = movement::surrounding_word(
6309 &display_map,
6310 selection.start.to_display_point(&display_map),
6311 );
6312 let start = word_range.start.to_offset(&display_map, Bias::Left);
6313 let end = word_range.end.to_offset(&display_map, Bias::Left);
6314 (start, end)
6315 } else {
6316 (selection.start, selection.end)
6317 };
6318
6319 let text = buffer.text_for_range(start..end).collect::<String>();
6320 let old_length = text.len() as i32;
6321 let text = callback(&text);
6322
6323 new_selections.push(Selection {
6324 start: (start as i32 - selection_adjustment) as usize,
6325 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6326 goal: SelectionGoal::None,
6327 ..selection
6328 });
6329
6330 selection_adjustment += old_length - text.len() as i32;
6331
6332 edits.push((start..end, text));
6333 }
6334
6335 self.transact(cx, |this, cx| {
6336 this.buffer.update(cx, |buffer, cx| {
6337 buffer.edit(edits, None, cx);
6338 });
6339
6340 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6341 s.select(new_selections);
6342 });
6343
6344 this.request_autoscroll(Autoscroll::fit(), cx);
6345 });
6346 }
6347
6348 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6349 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6350 let buffer = &display_map.buffer_snapshot;
6351 let selections = self.selections.all::<Point>(cx);
6352
6353 let mut edits = Vec::new();
6354 let mut selections_iter = selections.iter().peekable();
6355 while let Some(selection) = selections_iter.next() {
6356 // Avoid duplicating the same lines twice.
6357 let mut rows = selection.spanned_rows(false, &display_map);
6358
6359 while let Some(next_selection) = selections_iter.peek() {
6360 let next_rows = next_selection.spanned_rows(false, &display_map);
6361 if next_rows.start < rows.end {
6362 rows.end = next_rows.end;
6363 selections_iter.next().unwrap();
6364 } else {
6365 break;
6366 }
6367 }
6368
6369 // Copy the text from the selected row region and splice it either at the start
6370 // or end of the region.
6371 let start = Point::new(rows.start.0, 0);
6372 let end = Point::new(
6373 rows.end.previous_row().0,
6374 buffer.line_len(rows.end.previous_row()),
6375 );
6376 let text = buffer
6377 .text_for_range(start..end)
6378 .chain(Some("\n"))
6379 .collect::<String>();
6380 let insert_location = if upwards {
6381 Point::new(rows.end.0, 0)
6382 } else {
6383 start
6384 };
6385 edits.push((insert_location..insert_location, text));
6386 }
6387
6388 self.transact(cx, |this, cx| {
6389 this.buffer.update(cx, |buffer, cx| {
6390 buffer.edit(edits, None, cx);
6391 });
6392
6393 this.request_autoscroll(Autoscroll::fit(), cx);
6394 });
6395 }
6396
6397 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6398 self.duplicate_line(true, cx);
6399 }
6400
6401 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6402 self.duplicate_line(false, cx);
6403 }
6404
6405 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6406 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6407 let buffer = self.buffer.read(cx).snapshot(cx);
6408
6409 let mut edits = Vec::new();
6410 let mut unfold_ranges = Vec::new();
6411 let mut refold_ranges = Vec::new();
6412
6413 let selections = self.selections.all::<Point>(cx);
6414 let mut selections = selections.iter().peekable();
6415 let mut contiguous_row_selections = Vec::new();
6416 let mut new_selections = Vec::new();
6417
6418 while let Some(selection) = selections.next() {
6419 // Find all the selections that span a contiguous row range
6420 let (start_row, end_row) = consume_contiguous_rows(
6421 &mut contiguous_row_selections,
6422 selection,
6423 &display_map,
6424 &mut selections,
6425 );
6426
6427 // Move the text spanned by the row range to be before the line preceding the row range
6428 if start_row.0 > 0 {
6429 let range_to_move = Point::new(
6430 start_row.previous_row().0,
6431 buffer.line_len(start_row.previous_row()),
6432 )
6433 ..Point::new(
6434 end_row.previous_row().0,
6435 buffer.line_len(end_row.previous_row()),
6436 );
6437 let insertion_point = display_map
6438 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6439 .0;
6440
6441 // Don't move lines across excerpts
6442 if buffer
6443 .excerpt_boundaries_in_range((
6444 Bound::Excluded(insertion_point),
6445 Bound::Included(range_to_move.end),
6446 ))
6447 .next()
6448 .is_none()
6449 {
6450 let text = buffer
6451 .text_for_range(range_to_move.clone())
6452 .flat_map(|s| s.chars())
6453 .skip(1)
6454 .chain(['\n'])
6455 .collect::<String>();
6456
6457 edits.push((
6458 buffer.anchor_after(range_to_move.start)
6459 ..buffer.anchor_before(range_to_move.end),
6460 String::new(),
6461 ));
6462 let insertion_anchor = buffer.anchor_after(insertion_point);
6463 edits.push((insertion_anchor..insertion_anchor, text));
6464
6465 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6466
6467 // Move selections up
6468 new_selections.extend(contiguous_row_selections.drain(..).map(
6469 |mut selection| {
6470 selection.start.row -= row_delta;
6471 selection.end.row -= row_delta;
6472 selection
6473 },
6474 ));
6475
6476 // Move folds up
6477 unfold_ranges.push(range_to_move.clone());
6478 for fold in display_map.folds_in_range(
6479 buffer.anchor_before(range_to_move.start)
6480 ..buffer.anchor_after(range_to_move.end),
6481 ) {
6482 let mut start = fold.range.start.to_point(&buffer);
6483 let mut end = fold.range.end.to_point(&buffer);
6484 start.row -= row_delta;
6485 end.row -= row_delta;
6486 refold_ranges.push((start..end, fold.placeholder.clone()));
6487 }
6488 }
6489 }
6490
6491 // If we didn't move line(s), preserve the existing selections
6492 new_selections.append(&mut contiguous_row_selections);
6493 }
6494
6495 self.transact(cx, |this, cx| {
6496 this.unfold_ranges(unfold_ranges, true, true, cx);
6497 this.buffer.update(cx, |buffer, cx| {
6498 for (range, text) in edits {
6499 buffer.edit([(range, text)], None, cx);
6500 }
6501 });
6502 this.fold_ranges(refold_ranges, true, cx);
6503 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6504 s.select(new_selections);
6505 })
6506 });
6507 }
6508
6509 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6510 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6511 let buffer = self.buffer.read(cx).snapshot(cx);
6512
6513 let mut edits = Vec::new();
6514 let mut unfold_ranges = Vec::new();
6515 let mut refold_ranges = Vec::new();
6516
6517 let selections = self.selections.all::<Point>(cx);
6518 let mut selections = selections.iter().peekable();
6519 let mut contiguous_row_selections = Vec::new();
6520 let mut new_selections = Vec::new();
6521
6522 while let Some(selection) = selections.next() {
6523 // Find all the selections that span a contiguous row range
6524 let (start_row, end_row) = consume_contiguous_rows(
6525 &mut contiguous_row_selections,
6526 selection,
6527 &display_map,
6528 &mut selections,
6529 );
6530
6531 // Move the text spanned by the row range to be after the last line of the row range
6532 if end_row.0 <= buffer.max_point().row {
6533 let range_to_move =
6534 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6535 let insertion_point = display_map
6536 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6537 .0;
6538
6539 // Don't move lines across excerpt boundaries
6540 if buffer
6541 .excerpt_boundaries_in_range((
6542 Bound::Excluded(range_to_move.start),
6543 Bound::Included(insertion_point),
6544 ))
6545 .next()
6546 .is_none()
6547 {
6548 let mut text = String::from("\n");
6549 text.extend(buffer.text_for_range(range_to_move.clone()));
6550 text.pop(); // Drop trailing newline
6551 edits.push((
6552 buffer.anchor_after(range_to_move.start)
6553 ..buffer.anchor_before(range_to_move.end),
6554 String::new(),
6555 ));
6556 let insertion_anchor = buffer.anchor_after(insertion_point);
6557 edits.push((insertion_anchor..insertion_anchor, text));
6558
6559 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6560
6561 // Move selections down
6562 new_selections.extend(contiguous_row_selections.drain(..).map(
6563 |mut selection| {
6564 selection.start.row += row_delta;
6565 selection.end.row += row_delta;
6566 selection
6567 },
6568 ));
6569
6570 // Move folds down
6571 unfold_ranges.push(range_to_move.clone());
6572 for fold in display_map.folds_in_range(
6573 buffer.anchor_before(range_to_move.start)
6574 ..buffer.anchor_after(range_to_move.end),
6575 ) {
6576 let mut start = fold.range.start.to_point(&buffer);
6577 let mut end = fold.range.end.to_point(&buffer);
6578 start.row += row_delta;
6579 end.row += row_delta;
6580 refold_ranges.push((start..end, fold.placeholder.clone()));
6581 }
6582 }
6583 }
6584
6585 // If we didn't move line(s), preserve the existing selections
6586 new_selections.append(&mut contiguous_row_selections);
6587 }
6588
6589 self.transact(cx, |this, cx| {
6590 this.unfold_ranges(unfold_ranges, true, true, cx);
6591 this.buffer.update(cx, |buffer, cx| {
6592 for (range, text) in edits {
6593 buffer.edit([(range, text)], None, cx);
6594 }
6595 });
6596 this.fold_ranges(refold_ranges, true, cx);
6597 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6598 });
6599 }
6600
6601 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6602 let text_layout_details = &self.text_layout_details(cx);
6603 self.transact(cx, |this, cx| {
6604 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6605 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6606 let line_mode = s.line_mode;
6607 s.move_with(|display_map, selection| {
6608 if !selection.is_empty() || line_mode {
6609 return;
6610 }
6611
6612 let mut head = selection.head();
6613 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6614 if head.column() == display_map.line_len(head.row()) {
6615 transpose_offset = display_map
6616 .buffer_snapshot
6617 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6618 }
6619
6620 if transpose_offset == 0 {
6621 return;
6622 }
6623
6624 *head.column_mut() += 1;
6625 head = display_map.clip_point(head, Bias::Right);
6626 let goal = SelectionGoal::HorizontalPosition(
6627 display_map
6628 .x_for_display_point(head, &text_layout_details)
6629 .into(),
6630 );
6631 selection.collapse_to(head, goal);
6632
6633 let transpose_start = display_map
6634 .buffer_snapshot
6635 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6636 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6637 let transpose_end = display_map
6638 .buffer_snapshot
6639 .clip_offset(transpose_offset + 1, Bias::Right);
6640 if let Some(ch) =
6641 display_map.buffer_snapshot.chars_at(transpose_start).next()
6642 {
6643 edits.push((transpose_start..transpose_offset, String::new()));
6644 edits.push((transpose_end..transpose_end, ch.to_string()));
6645 }
6646 }
6647 });
6648 edits
6649 });
6650 this.buffer
6651 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6652 let selections = this.selections.all::<usize>(cx);
6653 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6654 s.select(selections);
6655 });
6656 });
6657 }
6658
6659 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6660 let mut text = String::new();
6661 let buffer = self.buffer.read(cx).snapshot(cx);
6662 let mut selections = self.selections.all::<Point>(cx);
6663 let mut clipboard_selections = Vec::with_capacity(selections.len());
6664 {
6665 let max_point = buffer.max_point();
6666 let mut is_first = true;
6667 for selection in &mut selections {
6668 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6669 if is_entire_line {
6670 selection.start = Point::new(selection.start.row, 0);
6671 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6672 selection.goal = SelectionGoal::None;
6673 }
6674 if is_first {
6675 is_first = false;
6676 } else {
6677 text += "\n";
6678 }
6679 let mut len = 0;
6680 for chunk in buffer.text_for_range(selection.start..selection.end) {
6681 text.push_str(chunk);
6682 len += chunk.len();
6683 }
6684 clipboard_selections.push(ClipboardSelection {
6685 len,
6686 is_entire_line,
6687 first_line_indent: buffer
6688 .indent_size_for_line(MultiBufferRow(selection.start.row))
6689 .len,
6690 });
6691 }
6692 }
6693
6694 self.transact(cx, |this, cx| {
6695 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6696 s.select(selections);
6697 });
6698 this.insert("", cx);
6699 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6700 text,
6701 clipboard_selections,
6702 ));
6703 });
6704 }
6705
6706 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6707 let selections = self.selections.all::<Point>(cx);
6708 let buffer = self.buffer.read(cx).read(cx);
6709 let mut text = String::new();
6710
6711 let mut clipboard_selections = Vec::with_capacity(selections.len());
6712 {
6713 let max_point = buffer.max_point();
6714 let mut is_first = true;
6715 for selection in selections.iter() {
6716 let mut start = selection.start;
6717 let mut end = selection.end;
6718 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6719 if is_entire_line {
6720 start = Point::new(start.row, 0);
6721 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6722 }
6723 if is_first {
6724 is_first = false;
6725 } else {
6726 text += "\n";
6727 }
6728 let mut len = 0;
6729 for chunk in buffer.text_for_range(start..end) {
6730 text.push_str(chunk);
6731 len += chunk.len();
6732 }
6733 clipboard_selections.push(ClipboardSelection {
6734 len,
6735 is_entire_line,
6736 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6737 });
6738 }
6739 }
6740
6741 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6742 text,
6743 clipboard_selections,
6744 ));
6745 }
6746
6747 pub fn do_paste(
6748 &mut self,
6749 text: &String,
6750 clipboard_selections: Option<Vec<ClipboardSelection>>,
6751 handle_entire_lines: bool,
6752 cx: &mut ViewContext<Self>,
6753 ) {
6754 if self.read_only(cx) {
6755 return;
6756 }
6757
6758 let clipboard_text = Cow::Borrowed(text);
6759
6760 self.transact(cx, |this, cx| {
6761 if let Some(mut clipboard_selections) = clipboard_selections {
6762 let old_selections = this.selections.all::<usize>(cx);
6763 let all_selections_were_entire_line =
6764 clipboard_selections.iter().all(|s| s.is_entire_line);
6765 let first_selection_indent_column =
6766 clipboard_selections.first().map(|s| s.first_line_indent);
6767 if clipboard_selections.len() != old_selections.len() {
6768 clipboard_selections.drain(..);
6769 }
6770
6771 this.buffer.update(cx, |buffer, cx| {
6772 let snapshot = buffer.read(cx);
6773 let mut start_offset = 0;
6774 let mut edits = Vec::new();
6775 let mut original_indent_columns = Vec::new();
6776 for (ix, selection) in old_selections.iter().enumerate() {
6777 let to_insert;
6778 let entire_line;
6779 let original_indent_column;
6780 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6781 let end_offset = start_offset + clipboard_selection.len;
6782 to_insert = &clipboard_text[start_offset..end_offset];
6783 entire_line = clipboard_selection.is_entire_line;
6784 start_offset = end_offset + 1;
6785 original_indent_column = Some(clipboard_selection.first_line_indent);
6786 } else {
6787 to_insert = clipboard_text.as_str();
6788 entire_line = all_selections_were_entire_line;
6789 original_indent_column = first_selection_indent_column
6790 }
6791
6792 // If the corresponding selection was empty when this slice of the
6793 // clipboard text was written, then the entire line containing the
6794 // selection was copied. If this selection is also currently empty,
6795 // then paste the line before the current line of the buffer.
6796 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6797 let column = selection.start.to_point(&snapshot).column as usize;
6798 let line_start = selection.start - column;
6799 line_start..line_start
6800 } else {
6801 selection.range()
6802 };
6803
6804 edits.push((range, to_insert));
6805 original_indent_columns.extend(original_indent_column);
6806 }
6807 drop(snapshot);
6808
6809 buffer.edit(
6810 edits,
6811 Some(AutoindentMode::Block {
6812 original_indent_columns,
6813 }),
6814 cx,
6815 );
6816 });
6817
6818 let selections = this.selections.all::<usize>(cx);
6819 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6820 } else {
6821 this.insert(&clipboard_text, cx);
6822 }
6823 });
6824 }
6825
6826 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
6827 if let Some(item) = cx.read_from_clipboard() {
6828 let entries = item.entries();
6829
6830 match entries.first() {
6831 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
6832 // of all the pasted entries.
6833 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
6834 .do_paste(
6835 clipboard_string.text(),
6836 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
6837 true,
6838 cx,
6839 ),
6840 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
6841 }
6842 }
6843 }
6844
6845 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
6846 if self.read_only(cx) {
6847 return;
6848 }
6849
6850 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
6851 if let Some((selections, _)) =
6852 self.selection_history.transaction(transaction_id).cloned()
6853 {
6854 self.change_selections(None, cx, |s| {
6855 s.select_anchors(selections.to_vec());
6856 });
6857 }
6858 self.request_autoscroll(Autoscroll::fit(), cx);
6859 self.unmark_text(cx);
6860 self.refresh_inline_completion(true, false, cx);
6861 cx.emit(EditorEvent::Edited { transaction_id });
6862 cx.emit(EditorEvent::TransactionUndone { transaction_id });
6863 }
6864 }
6865
6866 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
6867 if self.read_only(cx) {
6868 return;
6869 }
6870
6871 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
6872 if let Some((_, Some(selections))) =
6873 self.selection_history.transaction(transaction_id).cloned()
6874 {
6875 self.change_selections(None, cx, |s| {
6876 s.select_anchors(selections.to_vec());
6877 });
6878 }
6879 self.request_autoscroll(Autoscroll::fit(), cx);
6880 self.unmark_text(cx);
6881 self.refresh_inline_completion(true, false, cx);
6882 cx.emit(EditorEvent::Edited { transaction_id });
6883 }
6884 }
6885
6886 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
6887 self.buffer
6888 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
6889 }
6890
6891 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
6892 self.buffer
6893 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
6894 }
6895
6896 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
6897 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6898 let line_mode = s.line_mode;
6899 s.move_with(|map, selection| {
6900 let cursor = if selection.is_empty() && !line_mode {
6901 movement::left(map, selection.start)
6902 } else {
6903 selection.start
6904 };
6905 selection.collapse_to(cursor, SelectionGoal::None);
6906 });
6907 })
6908 }
6909
6910 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
6911 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6912 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
6913 })
6914 }
6915
6916 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
6917 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6918 let line_mode = s.line_mode;
6919 s.move_with(|map, selection| {
6920 let cursor = if selection.is_empty() && !line_mode {
6921 movement::right(map, selection.end)
6922 } else {
6923 selection.end
6924 };
6925 selection.collapse_to(cursor, SelectionGoal::None)
6926 });
6927 })
6928 }
6929
6930 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
6931 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6932 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
6933 })
6934 }
6935
6936 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
6937 if self.take_rename(true, cx).is_some() {
6938 return;
6939 }
6940
6941 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6942 cx.propagate();
6943 return;
6944 }
6945
6946 let text_layout_details = &self.text_layout_details(cx);
6947 let selection_count = self.selections.count();
6948 let first_selection = self.selections.first_anchor();
6949
6950 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6951 let line_mode = s.line_mode;
6952 s.move_with(|map, selection| {
6953 if !selection.is_empty() && !line_mode {
6954 selection.goal = SelectionGoal::None;
6955 }
6956 let (cursor, goal) = movement::up(
6957 map,
6958 selection.start,
6959 selection.goal,
6960 false,
6961 &text_layout_details,
6962 );
6963 selection.collapse_to(cursor, goal);
6964 });
6965 });
6966
6967 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
6968 {
6969 cx.propagate();
6970 }
6971 }
6972
6973 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
6974 if self.take_rename(true, cx).is_some() {
6975 return;
6976 }
6977
6978 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6979 cx.propagate();
6980 return;
6981 }
6982
6983 let text_layout_details = &self.text_layout_details(cx);
6984
6985 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6986 let line_mode = s.line_mode;
6987 s.move_with(|map, selection| {
6988 if !selection.is_empty() && !line_mode {
6989 selection.goal = SelectionGoal::None;
6990 }
6991 let (cursor, goal) = movement::up_by_rows(
6992 map,
6993 selection.start,
6994 action.lines,
6995 selection.goal,
6996 false,
6997 &text_layout_details,
6998 );
6999 selection.collapse_to(cursor, goal);
7000 });
7001 })
7002 }
7003
7004 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7005 if self.take_rename(true, cx).is_some() {
7006 return;
7007 }
7008
7009 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7010 cx.propagate();
7011 return;
7012 }
7013
7014 let text_layout_details = &self.text_layout_details(cx);
7015
7016 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7017 let line_mode = s.line_mode;
7018 s.move_with(|map, selection| {
7019 if !selection.is_empty() && !line_mode {
7020 selection.goal = SelectionGoal::None;
7021 }
7022 let (cursor, goal) = movement::down_by_rows(
7023 map,
7024 selection.start,
7025 action.lines,
7026 selection.goal,
7027 false,
7028 &text_layout_details,
7029 );
7030 selection.collapse_to(cursor, goal);
7031 });
7032 })
7033 }
7034
7035 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7036 let text_layout_details = &self.text_layout_details(cx);
7037 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7038 s.move_heads_with(|map, head, goal| {
7039 movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
7040 })
7041 })
7042 }
7043
7044 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7045 let text_layout_details = &self.text_layout_details(cx);
7046 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7047 s.move_heads_with(|map, head, goal| {
7048 movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
7049 })
7050 })
7051 }
7052
7053 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7054 let Some(row_count) = self.visible_row_count() else {
7055 return;
7056 };
7057
7058 let text_layout_details = &self.text_layout_details(cx);
7059
7060 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7061 s.move_heads_with(|map, head, goal| {
7062 movement::up_by_rows(map, head, row_count, goal, false, &text_layout_details)
7063 })
7064 })
7065 }
7066
7067 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7068 if self.take_rename(true, cx).is_some() {
7069 return;
7070 }
7071
7072 if self
7073 .context_menu
7074 .write()
7075 .as_mut()
7076 .map(|menu| menu.select_first(self.project.as_ref(), cx))
7077 .unwrap_or(false)
7078 {
7079 return;
7080 }
7081
7082 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7083 cx.propagate();
7084 return;
7085 }
7086
7087 let Some(row_count) = self.visible_row_count() else {
7088 return;
7089 };
7090
7091 let autoscroll = if action.center_cursor {
7092 Autoscroll::center()
7093 } else {
7094 Autoscroll::fit()
7095 };
7096
7097 let text_layout_details = &self.text_layout_details(cx);
7098
7099 self.change_selections(Some(autoscroll), 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::up_by_rows(
7106 map,
7107 selection.end,
7108 row_count,
7109 selection.goal,
7110 false,
7111 &text_layout_details,
7112 );
7113 selection.collapse_to(cursor, goal);
7114 });
7115 });
7116 }
7117
7118 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7119 let text_layout_details = &self.text_layout_details(cx);
7120 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7121 s.move_heads_with(|map, head, goal| {
7122 movement::up(map, head, goal, false, &text_layout_details)
7123 })
7124 })
7125 }
7126
7127 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7128 self.take_rename(true, cx);
7129
7130 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7131 cx.propagate();
7132 return;
7133 }
7134
7135 let text_layout_details = &self.text_layout_details(cx);
7136 let selection_count = self.selections.count();
7137 let first_selection = self.selections.first_anchor();
7138
7139 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7140 let line_mode = s.line_mode;
7141 s.move_with(|map, selection| {
7142 if !selection.is_empty() && !line_mode {
7143 selection.goal = SelectionGoal::None;
7144 }
7145 let (cursor, goal) = movement::down(
7146 map,
7147 selection.end,
7148 selection.goal,
7149 false,
7150 &text_layout_details,
7151 );
7152 selection.collapse_to(cursor, goal);
7153 });
7154 });
7155
7156 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7157 {
7158 cx.propagate();
7159 }
7160 }
7161
7162 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7163 let Some(row_count) = self.visible_row_count() else {
7164 return;
7165 };
7166
7167 let text_layout_details = &self.text_layout_details(cx);
7168
7169 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7170 s.move_heads_with(|map, head, goal| {
7171 movement::down_by_rows(map, head, row_count, goal, false, &text_layout_details)
7172 })
7173 })
7174 }
7175
7176 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7177 if self.take_rename(true, cx).is_some() {
7178 return;
7179 }
7180
7181 if self
7182 .context_menu
7183 .write()
7184 .as_mut()
7185 .map(|menu| menu.select_last(self.project.as_ref(), cx))
7186 .unwrap_or(false)
7187 {
7188 return;
7189 }
7190
7191 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7192 cx.propagate();
7193 return;
7194 }
7195
7196 let Some(row_count) = self.visible_row_count() else {
7197 return;
7198 };
7199
7200 let autoscroll = if action.center_cursor {
7201 Autoscroll::center()
7202 } else {
7203 Autoscroll::fit()
7204 };
7205
7206 let text_layout_details = &self.text_layout_details(cx);
7207 self.change_selections(Some(autoscroll), cx, |s| {
7208 let line_mode = s.line_mode;
7209 s.move_with(|map, selection| {
7210 if !selection.is_empty() && !line_mode {
7211 selection.goal = SelectionGoal::None;
7212 }
7213 let (cursor, goal) = movement::down_by_rows(
7214 map,
7215 selection.end,
7216 row_count,
7217 selection.goal,
7218 false,
7219 &text_layout_details,
7220 );
7221 selection.collapse_to(cursor, goal);
7222 });
7223 });
7224 }
7225
7226 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7227 let text_layout_details = &self.text_layout_details(cx);
7228 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7229 s.move_heads_with(|map, head, goal| {
7230 movement::down(map, head, goal, false, &text_layout_details)
7231 })
7232 });
7233 }
7234
7235 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7236 if let Some(context_menu) = self.context_menu.write().as_mut() {
7237 context_menu.select_first(self.project.as_ref(), cx);
7238 }
7239 }
7240
7241 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7242 if let Some(context_menu) = self.context_menu.write().as_mut() {
7243 context_menu.select_prev(self.project.as_ref(), cx);
7244 }
7245 }
7246
7247 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7248 if let Some(context_menu) = self.context_menu.write().as_mut() {
7249 context_menu.select_next(self.project.as_ref(), cx);
7250 }
7251 }
7252
7253 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7254 if let Some(context_menu) = self.context_menu.write().as_mut() {
7255 context_menu.select_last(self.project.as_ref(), cx);
7256 }
7257 }
7258
7259 pub fn move_to_previous_word_start(
7260 &mut self,
7261 _: &MoveToPreviousWordStart,
7262 cx: &mut ViewContext<Self>,
7263 ) {
7264 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7265 s.move_cursors_with(|map, head, _| {
7266 (
7267 movement::previous_word_start(map, head),
7268 SelectionGoal::None,
7269 )
7270 });
7271 })
7272 }
7273
7274 pub fn move_to_previous_subword_start(
7275 &mut self,
7276 _: &MoveToPreviousSubwordStart,
7277 cx: &mut ViewContext<Self>,
7278 ) {
7279 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7280 s.move_cursors_with(|map, head, _| {
7281 (
7282 movement::previous_subword_start(map, head),
7283 SelectionGoal::None,
7284 )
7285 });
7286 })
7287 }
7288
7289 pub fn select_to_previous_word_start(
7290 &mut self,
7291 _: &SelectToPreviousWordStart,
7292 cx: &mut ViewContext<Self>,
7293 ) {
7294 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7295 s.move_heads_with(|map, head, _| {
7296 (
7297 movement::previous_word_start(map, head),
7298 SelectionGoal::None,
7299 )
7300 });
7301 })
7302 }
7303
7304 pub fn select_to_previous_subword_start(
7305 &mut self,
7306 _: &SelectToPreviousSubwordStart,
7307 cx: &mut ViewContext<Self>,
7308 ) {
7309 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7310 s.move_heads_with(|map, head, _| {
7311 (
7312 movement::previous_subword_start(map, head),
7313 SelectionGoal::None,
7314 )
7315 });
7316 })
7317 }
7318
7319 pub fn delete_to_previous_word_start(
7320 &mut self,
7321 _: &DeleteToPreviousWordStart,
7322 cx: &mut ViewContext<Self>,
7323 ) {
7324 self.transact(cx, |this, cx| {
7325 this.select_autoclose_pair(cx);
7326 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7327 let line_mode = s.line_mode;
7328 s.move_with(|map, selection| {
7329 if selection.is_empty() && !line_mode {
7330 let cursor = movement::previous_word_start(map, selection.head());
7331 selection.set_head(cursor, SelectionGoal::None);
7332 }
7333 });
7334 });
7335 this.insert("", cx);
7336 });
7337 }
7338
7339 pub fn delete_to_previous_subword_start(
7340 &mut self,
7341 _: &DeleteToPreviousSubwordStart,
7342 cx: &mut ViewContext<Self>,
7343 ) {
7344 self.transact(cx, |this, cx| {
7345 this.select_autoclose_pair(cx);
7346 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7347 let line_mode = s.line_mode;
7348 s.move_with(|map, selection| {
7349 if selection.is_empty() && !line_mode {
7350 let cursor = movement::previous_subword_start(map, selection.head());
7351 selection.set_head(cursor, SelectionGoal::None);
7352 }
7353 });
7354 });
7355 this.insert("", cx);
7356 });
7357 }
7358
7359 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7360 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7361 s.move_cursors_with(|map, head, _| {
7362 (movement::next_word_end(map, head), SelectionGoal::None)
7363 });
7364 })
7365 }
7366
7367 pub fn move_to_next_subword_end(
7368 &mut self,
7369 _: &MoveToNextSubwordEnd,
7370 cx: &mut ViewContext<Self>,
7371 ) {
7372 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7373 s.move_cursors_with(|map, head, _| {
7374 (movement::next_subword_end(map, head), SelectionGoal::None)
7375 });
7376 })
7377 }
7378
7379 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7380 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7381 s.move_heads_with(|map, head, _| {
7382 (movement::next_word_end(map, head), SelectionGoal::None)
7383 });
7384 })
7385 }
7386
7387 pub fn select_to_next_subword_end(
7388 &mut self,
7389 _: &SelectToNextSubwordEnd,
7390 cx: &mut ViewContext<Self>,
7391 ) {
7392 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7393 s.move_heads_with(|map, head, _| {
7394 (movement::next_subword_end(map, head), SelectionGoal::None)
7395 });
7396 })
7397 }
7398
7399 pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
7400 self.transact(cx, |this, cx| {
7401 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7402 let line_mode = s.line_mode;
7403 s.move_with(|map, selection| {
7404 if selection.is_empty() && !line_mode {
7405 let cursor = movement::next_word_end(map, selection.head());
7406 selection.set_head(cursor, SelectionGoal::None);
7407 }
7408 });
7409 });
7410 this.insert("", cx);
7411 });
7412 }
7413
7414 pub fn delete_to_next_subword_end(
7415 &mut self,
7416 _: &DeleteToNextSubwordEnd,
7417 cx: &mut ViewContext<Self>,
7418 ) {
7419 self.transact(cx, |this, cx| {
7420 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7421 s.move_with(|map, selection| {
7422 if selection.is_empty() {
7423 let cursor = movement::next_subword_end(map, selection.head());
7424 selection.set_head(cursor, SelectionGoal::None);
7425 }
7426 });
7427 });
7428 this.insert("", cx);
7429 });
7430 }
7431
7432 pub fn move_to_beginning_of_line(
7433 &mut self,
7434 action: &MoveToBeginningOfLine,
7435 cx: &mut ViewContext<Self>,
7436 ) {
7437 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7438 s.move_cursors_with(|map, head, _| {
7439 (
7440 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7441 SelectionGoal::None,
7442 )
7443 });
7444 })
7445 }
7446
7447 pub fn select_to_beginning_of_line(
7448 &mut self,
7449 action: &SelectToBeginningOfLine,
7450 cx: &mut ViewContext<Self>,
7451 ) {
7452 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7453 s.move_heads_with(|map, head, _| {
7454 (
7455 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7456 SelectionGoal::None,
7457 )
7458 });
7459 });
7460 }
7461
7462 pub fn delete_to_beginning_of_line(
7463 &mut self,
7464 _: &DeleteToBeginningOfLine,
7465 cx: &mut ViewContext<Self>,
7466 ) {
7467 self.transact(cx, |this, cx| {
7468 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7469 s.move_with(|_, selection| {
7470 selection.reversed = true;
7471 });
7472 });
7473
7474 this.select_to_beginning_of_line(
7475 &SelectToBeginningOfLine {
7476 stop_at_soft_wraps: false,
7477 },
7478 cx,
7479 );
7480 this.backspace(&Backspace, cx);
7481 });
7482 }
7483
7484 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7485 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7486 s.move_cursors_with(|map, head, _| {
7487 (
7488 movement::line_end(map, head, action.stop_at_soft_wraps),
7489 SelectionGoal::None,
7490 )
7491 });
7492 })
7493 }
7494
7495 pub fn select_to_end_of_line(
7496 &mut self,
7497 action: &SelectToEndOfLine,
7498 cx: &mut ViewContext<Self>,
7499 ) {
7500 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7501 s.move_heads_with(|map, head, _| {
7502 (
7503 movement::line_end(map, head, action.stop_at_soft_wraps),
7504 SelectionGoal::None,
7505 )
7506 });
7507 })
7508 }
7509
7510 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7511 self.transact(cx, |this, cx| {
7512 this.select_to_end_of_line(
7513 &SelectToEndOfLine {
7514 stop_at_soft_wraps: false,
7515 },
7516 cx,
7517 );
7518 this.delete(&Delete, cx);
7519 });
7520 }
7521
7522 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7523 self.transact(cx, |this, cx| {
7524 this.select_to_end_of_line(
7525 &SelectToEndOfLine {
7526 stop_at_soft_wraps: false,
7527 },
7528 cx,
7529 );
7530 this.cut(&Cut, cx);
7531 });
7532 }
7533
7534 pub fn move_to_start_of_paragraph(
7535 &mut self,
7536 _: &MoveToStartOfParagraph,
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_with(|map, selection| {
7546 selection.collapse_to(
7547 movement::start_of_paragraph(map, selection.head(), 1),
7548 SelectionGoal::None,
7549 )
7550 });
7551 })
7552 }
7553
7554 pub fn move_to_end_of_paragraph(
7555 &mut self,
7556 _: &MoveToEndOfParagraph,
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_with(|map, selection| {
7566 selection.collapse_to(
7567 movement::end_of_paragraph(map, selection.head(), 1),
7568 SelectionGoal::None,
7569 )
7570 });
7571 })
7572 }
7573
7574 pub fn select_to_start_of_paragraph(
7575 &mut self,
7576 _: &SelectToStartOfParagraph,
7577 cx: &mut ViewContext<Self>,
7578 ) {
7579 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7580 cx.propagate();
7581 return;
7582 }
7583
7584 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7585 s.move_heads_with(|map, head, _| {
7586 (
7587 movement::start_of_paragraph(map, head, 1),
7588 SelectionGoal::None,
7589 )
7590 });
7591 })
7592 }
7593
7594 pub fn select_to_end_of_paragraph(
7595 &mut self,
7596 _: &SelectToEndOfParagraph,
7597 cx: &mut ViewContext<Self>,
7598 ) {
7599 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7600 cx.propagate();
7601 return;
7602 }
7603
7604 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7605 s.move_heads_with(|map, head, _| {
7606 (
7607 movement::end_of_paragraph(map, head, 1),
7608 SelectionGoal::None,
7609 )
7610 });
7611 })
7612 }
7613
7614 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7615 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7616 cx.propagate();
7617 return;
7618 }
7619
7620 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7621 s.select_ranges(vec![0..0]);
7622 });
7623 }
7624
7625 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7626 let mut selection = self.selections.last::<Point>(cx);
7627 selection.set_head(Point::zero(), SelectionGoal::None);
7628
7629 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7630 s.select(vec![selection]);
7631 });
7632 }
7633
7634 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7635 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7636 cx.propagate();
7637 return;
7638 }
7639
7640 let cursor = self.buffer.read(cx).read(cx).len();
7641 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7642 s.select_ranges(vec![cursor..cursor])
7643 });
7644 }
7645
7646 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7647 self.nav_history = nav_history;
7648 }
7649
7650 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7651 self.nav_history.as_ref()
7652 }
7653
7654 fn push_to_nav_history(
7655 &mut self,
7656 cursor_anchor: Anchor,
7657 new_position: Option<Point>,
7658 cx: &mut ViewContext<Self>,
7659 ) {
7660 if let Some(nav_history) = self.nav_history.as_mut() {
7661 let buffer = self.buffer.read(cx).read(cx);
7662 let cursor_position = cursor_anchor.to_point(&buffer);
7663 let scroll_state = self.scroll_manager.anchor();
7664 let scroll_top_row = scroll_state.top_row(&buffer);
7665 drop(buffer);
7666
7667 if let Some(new_position) = new_position {
7668 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7669 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7670 return;
7671 }
7672 }
7673
7674 nav_history.push(
7675 Some(NavigationData {
7676 cursor_anchor,
7677 cursor_position,
7678 scroll_anchor: scroll_state,
7679 scroll_top_row,
7680 }),
7681 cx,
7682 );
7683 }
7684 }
7685
7686 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7687 let buffer = self.buffer.read(cx).snapshot(cx);
7688 let mut selection = self.selections.first::<usize>(cx);
7689 selection.set_head(buffer.len(), SelectionGoal::None);
7690 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7691 s.select(vec![selection]);
7692 });
7693 }
7694
7695 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7696 let end = self.buffer.read(cx).read(cx).len();
7697 self.change_selections(None, cx, |s| {
7698 s.select_ranges(vec![0..end]);
7699 });
7700 }
7701
7702 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7703 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7704 let mut selections = self.selections.all::<Point>(cx);
7705 let max_point = display_map.buffer_snapshot.max_point();
7706 for selection in &mut selections {
7707 let rows = selection.spanned_rows(true, &display_map);
7708 selection.start = Point::new(rows.start.0, 0);
7709 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7710 selection.reversed = false;
7711 }
7712 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7713 s.select(selections);
7714 });
7715 }
7716
7717 pub fn split_selection_into_lines(
7718 &mut self,
7719 _: &SplitSelectionIntoLines,
7720 cx: &mut ViewContext<Self>,
7721 ) {
7722 let mut to_unfold = Vec::new();
7723 let mut new_selection_ranges = Vec::new();
7724 {
7725 let selections = self.selections.all::<Point>(cx);
7726 let buffer = self.buffer.read(cx).read(cx);
7727 for selection in selections {
7728 for row in selection.start.row..selection.end.row {
7729 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7730 new_selection_ranges.push(cursor..cursor);
7731 }
7732 new_selection_ranges.push(selection.end..selection.end);
7733 to_unfold.push(selection.start..selection.end);
7734 }
7735 }
7736 self.unfold_ranges(to_unfold, true, true, cx);
7737 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7738 s.select_ranges(new_selection_ranges);
7739 });
7740 }
7741
7742 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7743 self.add_selection(true, cx);
7744 }
7745
7746 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7747 self.add_selection(false, cx);
7748 }
7749
7750 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7751 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7752 let mut selections = self.selections.all::<Point>(cx);
7753 let text_layout_details = self.text_layout_details(cx);
7754 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7755 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7756 let range = oldest_selection.display_range(&display_map).sorted();
7757
7758 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7759 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7760 let positions = start_x.min(end_x)..start_x.max(end_x);
7761
7762 selections.clear();
7763 let mut stack = Vec::new();
7764 for row in range.start.row().0..=range.end.row().0 {
7765 if let Some(selection) = self.selections.build_columnar_selection(
7766 &display_map,
7767 DisplayRow(row),
7768 &positions,
7769 oldest_selection.reversed,
7770 &text_layout_details,
7771 ) {
7772 stack.push(selection.id);
7773 selections.push(selection);
7774 }
7775 }
7776
7777 if above {
7778 stack.reverse();
7779 }
7780
7781 AddSelectionsState { above, stack }
7782 });
7783
7784 let last_added_selection = *state.stack.last().unwrap();
7785 let mut new_selections = Vec::new();
7786 if above == state.above {
7787 let end_row = if above {
7788 DisplayRow(0)
7789 } else {
7790 display_map.max_point().row()
7791 };
7792
7793 'outer: for selection in selections {
7794 if selection.id == last_added_selection {
7795 let range = selection.display_range(&display_map).sorted();
7796 debug_assert_eq!(range.start.row(), range.end.row());
7797 let mut row = range.start.row();
7798 let positions =
7799 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7800 px(start)..px(end)
7801 } else {
7802 let start_x =
7803 display_map.x_for_display_point(range.start, &text_layout_details);
7804 let end_x =
7805 display_map.x_for_display_point(range.end, &text_layout_details);
7806 start_x.min(end_x)..start_x.max(end_x)
7807 };
7808
7809 while row != end_row {
7810 if above {
7811 row.0 -= 1;
7812 } else {
7813 row.0 += 1;
7814 }
7815
7816 if let Some(new_selection) = self.selections.build_columnar_selection(
7817 &display_map,
7818 row,
7819 &positions,
7820 selection.reversed,
7821 &text_layout_details,
7822 ) {
7823 state.stack.push(new_selection.id);
7824 if above {
7825 new_selections.push(new_selection);
7826 new_selections.push(selection);
7827 } else {
7828 new_selections.push(selection);
7829 new_selections.push(new_selection);
7830 }
7831
7832 continue 'outer;
7833 }
7834 }
7835 }
7836
7837 new_selections.push(selection);
7838 }
7839 } else {
7840 new_selections = selections;
7841 new_selections.retain(|s| s.id != last_added_selection);
7842 state.stack.pop();
7843 }
7844
7845 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7846 s.select(new_selections);
7847 });
7848 if state.stack.len() > 1 {
7849 self.add_selections_state = Some(state);
7850 }
7851 }
7852
7853 pub fn select_next_match_internal(
7854 &mut self,
7855 display_map: &DisplaySnapshot,
7856 replace_newest: bool,
7857 autoscroll: Option<Autoscroll>,
7858 cx: &mut ViewContext<Self>,
7859 ) -> Result<()> {
7860 fn select_next_match_ranges(
7861 this: &mut Editor,
7862 range: Range<usize>,
7863 replace_newest: bool,
7864 auto_scroll: Option<Autoscroll>,
7865 cx: &mut ViewContext<Editor>,
7866 ) {
7867 this.unfold_ranges([range.clone()], false, true, cx);
7868 this.change_selections(auto_scroll, cx, |s| {
7869 if replace_newest {
7870 s.delete(s.newest_anchor().id);
7871 }
7872 s.insert_range(range.clone());
7873 });
7874 }
7875
7876 let buffer = &display_map.buffer_snapshot;
7877 let mut selections = self.selections.all::<usize>(cx);
7878 if let Some(mut select_next_state) = self.select_next_state.take() {
7879 let query = &select_next_state.query;
7880 if !select_next_state.done {
7881 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7882 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7883 let mut next_selected_range = None;
7884
7885 let bytes_after_last_selection =
7886 buffer.bytes_in_range(last_selection.end..buffer.len());
7887 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
7888 let query_matches = query
7889 .stream_find_iter(bytes_after_last_selection)
7890 .map(|result| (last_selection.end, result))
7891 .chain(
7892 query
7893 .stream_find_iter(bytes_before_first_selection)
7894 .map(|result| (0, result)),
7895 );
7896
7897 for (start_offset, query_match) in query_matches {
7898 let query_match = query_match.unwrap(); // can only fail due to I/O
7899 let offset_range =
7900 start_offset + query_match.start()..start_offset + query_match.end();
7901 let display_range = offset_range.start.to_display_point(&display_map)
7902 ..offset_range.end.to_display_point(&display_map);
7903
7904 if !select_next_state.wordwise
7905 || (!movement::is_inside_word(&display_map, display_range.start)
7906 && !movement::is_inside_word(&display_map, display_range.end))
7907 {
7908 // TODO: This is n^2, because we might check all the selections
7909 if !selections
7910 .iter()
7911 .any(|selection| selection.range().overlaps(&offset_range))
7912 {
7913 next_selected_range = Some(offset_range);
7914 break;
7915 }
7916 }
7917 }
7918
7919 if let Some(next_selected_range) = next_selected_range {
7920 select_next_match_ranges(
7921 self,
7922 next_selected_range,
7923 replace_newest,
7924 autoscroll,
7925 cx,
7926 );
7927 } else {
7928 select_next_state.done = true;
7929 }
7930 }
7931
7932 self.select_next_state = Some(select_next_state);
7933 } else {
7934 let mut only_carets = true;
7935 let mut same_text_selected = true;
7936 let mut selected_text = None;
7937
7938 let mut selections_iter = selections.iter().peekable();
7939 while let Some(selection) = selections_iter.next() {
7940 if selection.start != selection.end {
7941 only_carets = false;
7942 }
7943
7944 if same_text_selected {
7945 if selected_text.is_none() {
7946 selected_text =
7947 Some(buffer.text_for_range(selection.range()).collect::<String>());
7948 }
7949
7950 if let Some(next_selection) = selections_iter.peek() {
7951 if next_selection.range().len() == selection.range().len() {
7952 let next_selected_text = buffer
7953 .text_for_range(next_selection.range())
7954 .collect::<String>();
7955 if Some(next_selected_text) != selected_text {
7956 same_text_selected = false;
7957 selected_text = None;
7958 }
7959 } else {
7960 same_text_selected = false;
7961 selected_text = None;
7962 }
7963 }
7964 }
7965 }
7966
7967 if only_carets {
7968 for selection in &mut selections {
7969 let word_range = movement::surrounding_word(
7970 &display_map,
7971 selection.start.to_display_point(&display_map),
7972 );
7973 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
7974 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
7975 selection.goal = SelectionGoal::None;
7976 selection.reversed = false;
7977 select_next_match_ranges(
7978 self,
7979 selection.start..selection.end,
7980 replace_newest,
7981 autoscroll,
7982 cx,
7983 );
7984 }
7985
7986 if selections.len() == 1 {
7987 let selection = selections
7988 .last()
7989 .expect("ensured that there's only one selection");
7990 let query = buffer
7991 .text_for_range(selection.start..selection.end)
7992 .collect::<String>();
7993 let is_empty = query.is_empty();
7994 let select_state = SelectNextState {
7995 query: AhoCorasick::new(&[query])?,
7996 wordwise: true,
7997 done: is_empty,
7998 };
7999 self.select_next_state = Some(select_state);
8000 } else {
8001 self.select_next_state = None;
8002 }
8003 } else if let Some(selected_text) = selected_text {
8004 self.select_next_state = Some(SelectNextState {
8005 query: AhoCorasick::new(&[selected_text])?,
8006 wordwise: false,
8007 done: false,
8008 });
8009 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8010 }
8011 }
8012 Ok(())
8013 }
8014
8015 pub fn select_all_matches(
8016 &mut self,
8017 _action: &SelectAllMatches,
8018 cx: &mut ViewContext<Self>,
8019 ) -> Result<()> {
8020 self.push_to_selection_history();
8021 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8022
8023 self.select_next_match_internal(&display_map, false, None, cx)?;
8024 let Some(select_next_state) = self.select_next_state.as_mut() else {
8025 return Ok(());
8026 };
8027 if select_next_state.done {
8028 return Ok(());
8029 }
8030
8031 let mut new_selections = self.selections.all::<usize>(cx);
8032
8033 let buffer = &display_map.buffer_snapshot;
8034 let query_matches = select_next_state
8035 .query
8036 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8037
8038 for query_match in query_matches {
8039 let query_match = query_match.unwrap(); // can only fail due to I/O
8040 let offset_range = query_match.start()..query_match.end();
8041 let display_range = offset_range.start.to_display_point(&display_map)
8042 ..offset_range.end.to_display_point(&display_map);
8043
8044 if !select_next_state.wordwise
8045 || (!movement::is_inside_word(&display_map, display_range.start)
8046 && !movement::is_inside_word(&display_map, display_range.end))
8047 {
8048 self.selections.change_with(cx, |selections| {
8049 new_selections.push(Selection {
8050 id: selections.new_selection_id(),
8051 start: offset_range.start,
8052 end: offset_range.end,
8053 reversed: false,
8054 goal: SelectionGoal::None,
8055 });
8056 });
8057 }
8058 }
8059
8060 new_selections.sort_by_key(|selection| selection.start);
8061 let mut ix = 0;
8062 while ix + 1 < new_selections.len() {
8063 let current_selection = &new_selections[ix];
8064 let next_selection = &new_selections[ix + 1];
8065 if current_selection.range().overlaps(&next_selection.range()) {
8066 if current_selection.id < next_selection.id {
8067 new_selections.remove(ix + 1);
8068 } else {
8069 new_selections.remove(ix);
8070 }
8071 } else {
8072 ix += 1;
8073 }
8074 }
8075
8076 select_next_state.done = true;
8077 self.unfold_ranges(
8078 new_selections.iter().map(|selection| selection.range()),
8079 false,
8080 false,
8081 cx,
8082 );
8083 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8084 selections.select(new_selections)
8085 });
8086
8087 Ok(())
8088 }
8089
8090 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8091 self.push_to_selection_history();
8092 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8093 self.select_next_match_internal(
8094 &display_map,
8095 action.replace_newest,
8096 Some(Autoscroll::newest()),
8097 cx,
8098 )?;
8099 Ok(())
8100 }
8101
8102 pub fn select_previous(
8103 &mut self,
8104 action: &SelectPrevious,
8105 cx: &mut ViewContext<Self>,
8106 ) -> Result<()> {
8107 self.push_to_selection_history();
8108 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8109 let buffer = &display_map.buffer_snapshot;
8110 let mut selections = self.selections.all::<usize>(cx);
8111 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8112 let query = &select_prev_state.query;
8113 if !select_prev_state.done {
8114 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8115 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8116 let mut next_selected_range = None;
8117 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8118 let bytes_before_last_selection =
8119 buffer.reversed_bytes_in_range(0..last_selection.start);
8120 let bytes_after_first_selection =
8121 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8122 let query_matches = query
8123 .stream_find_iter(bytes_before_last_selection)
8124 .map(|result| (last_selection.start, result))
8125 .chain(
8126 query
8127 .stream_find_iter(bytes_after_first_selection)
8128 .map(|result| (buffer.len(), result)),
8129 );
8130 for (end_offset, query_match) in query_matches {
8131 let query_match = query_match.unwrap(); // can only fail due to I/O
8132 let offset_range =
8133 end_offset - query_match.end()..end_offset - query_match.start();
8134 let display_range = offset_range.start.to_display_point(&display_map)
8135 ..offset_range.end.to_display_point(&display_map);
8136
8137 if !select_prev_state.wordwise
8138 || (!movement::is_inside_word(&display_map, display_range.start)
8139 && !movement::is_inside_word(&display_map, display_range.end))
8140 {
8141 next_selected_range = Some(offset_range);
8142 break;
8143 }
8144 }
8145
8146 if let Some(next_selected_range) = next_selected_range {
8147 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8148 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8149 if action.replace_newest {
8150 s.delete(s.newest_anchor().id);
8151 }
8152 s.insert_range(next_selected_range);
8153 });
8154 } else {
8155 select_prev_state.done = true;
8156 }
8157 }
8158
8159 self.select_prev_state = Some(select_prev_state);
8160 } else {
8161 let mut only_carets = true;
8162 let mut same_text_selected = true;
8163 let mut selected_text = None;
8164
8165 let mut selections_iter = selections.iter().peekable();
8166 while let Some(selection) = selections_iter.next() {
8167 if selection.start != selection.end {
8168 only_carets = false;
8169 }
8170
8171 if same_text_selected {
8172 if selected_text.is_none() {
8173 selected_text =
8174 Some(buffer.text_for_range(selection.range()).collect::<String>());
8175 }
8176
8177 if let Some(next_selection) = selections_iter.peek() {
8178 if next_selection.range().len() == selection.range().len() {
8179 let next_selected_text = buffer
8180 .text_for_range(next_selection.range())
8181 .collect::<String>();
8182 if Some(next_selected_text) != selected_text {
8183 same_text_selected = false;
8184 selected_text = None;
8185 }
8186 } else {
8187 same_text_selected = false;
8188 selected_text = None;
8189 }
8190 }
8191 }
8192 }
8193
8194 if only_carets {
8195 for selection in &mut selections {
8196 let word_range = movement::surrounding_word(
8197 &display_map,
8198 selection.start.to_display_point(&display_map),
8199 );
8200 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8201 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8202 selection.goal = SelectionGoal::None;
8203 selection.reversed = false;
8204 }
8205 if selections.len() == 1 {
8206 let selection = selections
8207 .last()
8208 .expect("ensured that there's only one selection");
8209 let query = buffer
8210 .text_for_range(selection.start..selection.end)
8211 .collect::<String>();
8212 let is_empty = query.is_empty();
8213 let select_state = SelectNextState {
8214 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8215 wordwise: true,
8216 done: is_empty,
8217 };
8218 self.select_prev_state = Some(select_state);
8219 } else {
8220 self.select_prev_state = None;
8221 }
8222
8223 self.unfold_ranges(
8224 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8225 false,
8226 true,
8227 cx,
8228 );
8229 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8230 s.select(selections);
8231 });
8232 } else if let Some(selected_text) = selected_text {
8233 self.select_prev_state = Some(SelectNextState {
8234 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8235 wordwise: false,
8236 done: false,
8237 });
8238 self.select_previous(action, cx)?;
8239 }
8240 }
8241 Ok(())
8242 }
8243
8244 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8245 let text_layout_details = &self.text_layout_details(cx);
8246 self.transact(cx, |this, cx| {
8247 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8248 let mut edits = Vec::new();
8249 let mut selection_edit_ranges = Vec::new();
8250 let mut last_toggled_row = None;
8251 let snapshot = this.buffer.read(cx).read(cx);
8252 let empty_str: Arc<str> = Arc::default();
8253 let mut suffixes_inserted = Vec::new();
8254
8255 fn comment_prefix_range(
8256 snapshot: &MultiBufferSnapshot,
8257 row: MultiBufferRow,
8258 comment_prefix: &str,
8259 comment_prefix_whitespace: &str,
8260 ) -> Range<Point> {
8261 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8262
8263 let mut line_bytes = snapshot
8264 .bytes_in_range(start..snapshot.max_point())
8265 .flatten()
8266 .copied();
8267
8268 // If this line currently begins with the line comment prefix, then record
8269 // the range containing the prefix.
8270 if line_bytes
8271 .by_ref()
8272 .take(comment_prefix.len())
8273 .eq(comment_prefix.bytes())
8274 {
8275 // Include any whitespace that matches the comment prefix.
8276 let matching_whitespace_len = line_bytes
8277 .zip(comment_prefix_whitespace.bytes())
8278 .take_while(|(a, b)| a == b)
8279 .count() as u32;
8280 let end = Point::new(
8281 start.row,
8282 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8283 );
8284 start..end
8285 } else {
8286 start..start
8287 }
8288 }
8289
8290 fn comment_suffix_range(
8291 snapshot: &MultiBufferSnapshot,
8292 row: MultiBufferRow,
8293 comment_suffix: &str,
8294 comment_suffix_has_leading_space: bool,
8295 ) -> Range<Point> {
8296 let end = Point::new(row.0, snapshot.line_len(row));
8297 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8298
8299 let mut line_end_bytes = snapshot
8300 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8301 .flatten()
8302 .copied();
8303
8304 let leading_space_len = if suffix_start_column > 0
8305 && line_end_bytes.next() == Some(b' ')
8306 && comment_suffix_has_leading_space
8307 {
8308 1
8309 } else {
8310 0
8311 };
8312
8313 // If this line currently begins with the line comment prefix, then record
8314 // the range containing the prefix.
8315 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8316 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8317 start..end
8318 } else {
8319 end..end
8320 }
8321 }
8322
8323 // TODO: Handle selections that cross excerpts
8324 for selection in &mut selections {
8325 let start_column = snapshot
8326 .indent_size_for_line(MultiBufferRow(selection.start.row))
8327 .len;
8328 let language = if let Some(language) =
8329 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8330 {
8331 language
8332 } else {
8333 continue;
8334 };
8335
8336 selection_edit_ranges.clear();
8337
8338 // If multiple selections contain a given row, avoid processing that
8339 // row more than once.
8340 let mut start_row = MultiBufferRow(selection.start.row);
8341 if last_toggled_row == Some(start_row) {
8342 start_row = start_row.next_row();
8343 }
8344 let end_row =
8345 if selection.end.row > selection.start.row && selection.end.column == 0 {
8346 MultiBufferRow(selection.end.row - 1)
8347 } else {
8348 MultiBufferRow(selection.end.row)
8349 };
8350 last_toggled_row = Some(end_row);
8351
8352 if start_row > end_row {
8353 continue;
8354 }
8355
8356 // If the language has line comments, toggle those.
8357 let full_comment_prefixes = language.line_comment_prefixes();
8358 if !full_comment_prefixes.is_empty() {
8359 let first_prefix = full_comment_prefixes
8360 .first()
8361 .expect("prefixes is non-empty");
8362 let prefix_trimmed_lengths = full_comment_prefixes
8363 .iter()
8364 .map(|p| p.trim_end_matches(' ').len())
8365 .collect::<SmallVec<[usize; 4]>>();
8366
8367 let mut all_selection_lines_are_comments = true;
8368
8369 for row in start_row.0..=end_row.0 {
8370 let row = MultiBufferRow(row);
8371 if start_row < end_row && snapshot.is_line_blank(row) {
8372 continue;
8373 }
8374
8375 let prefix_range = full_comment_prefixes
8376 .iter()
8377 .zip(prefix_trimmed_lengths.iter().copied())
8378 .map(|(prefix, trimmed_prefix_len)| {
8379 comment_prefix_range(
8380 snapshot.deref(),
8381 row,
8382 &prefix[..trimmed_prefix_len],
8383 &prefix[trimmed_prefix_len..],
8384 )
8385 })
8386 .max_by_key(|range| range.end.column - range.start.column)
8387 .expect("prefixes is non-empty");
8388
8389 if prefix_range.is_empty() {
8390 all_selection_lines_are_comments = false;
8391 }
8392
8393 selection_edit_ranges.push(prefix_range);
8394 }
8395
8396 if all_selection_lines_are_comments {
8397 edits.extend(
8398 selection_edit_ranges
8399 .iter()
8400 .cloned()
8401 .map(|range| (range, empty_str.clone())),
8402 );
8403 } else {
8404 let min_column = selection_edit_ranges
8405 .iter()
8406 .map(|range| range.start.column)
8407 .min()
8408 .unwrap_or(0);
8409 edits.extend(selection_edit_ranges.iter().map(|range| {
8410 let position = Point::new(range.start.row, min_column);
8411 (position..position, first_prefix.clone())
8412 }));
8413 }
8414 } else if let Some((full_comment_prefix, comment_suffix)) =
8415 language.block_comment_delimiters()
8416 {
8417 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8418 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8419 let prefix_range = comment_prefix_range(
8420 snapshot.deref(),
8421 start_row,
8422 comment_prefix,
8423 comment_prefix_whitespace,
8424 );
8425 let suffix_range = comment_suffix_range(
8426 snapshot.deref(),
8427 end_row,
8428 comment_suffix.trim_start_matches(' '),
8429 comment_suffix.starts_with(' '),
8430 );
8431
8432 if prefix_range.is_empty() || suffix_range.is_empty() {
8433 edits.push((
8434 prefix_range.start..prefix_range.start,
8435 full_comment_prefix.clone(),
8436 ));
8437 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8438 suffixes_inserted.push((end_row, comment_suffix.len()));
8439 } else {
8440 edits.push((prefix_range, empty_str.clone()));
8441 edits.push((suffix_range, empty_str.clone()));
8442 }
8443 } else {
8444 continue;
8445 }
8446 }
8447
8448 drop(snapshot);
8449 this.buffer.update(cx, |buffer, cx| {
8450 buffer.edit(edits, None, cx);
8451 });
8452
8453 // Adjust selections so that they end before any comment suffixes that
8454 // were inserted.
8455 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8456 let mut selections = this.selections.all::<Point>(cx);
8457 let snapshot = this.buffer.read(cx).read(cx);
8458 for selection in &mut selections {
8459 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8460 match row.cmp(&MultiBufferRow(selection.end.row)) {
8461 Ordering::Less => {
8462 suffixes_inserted.next();
8463 continue;
8464 }
8465 Ordering::Greater => break,
8466 Ordering::Equal => {
8467 if selection.end.column == snapshot.line_len(row) {
8468 if selection.is_empty() {
8469 selection.start.column -= suffix_len as u32;
8470 }
8471 selection.end.column -= suffix_len as u32;
8472 }
8473 break;
8474 }
8475 }
8476 }
8477 }
8478
8479 drop(snapshot);
8480 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8481
8482 let selections = this.selections.all::<Point>(cx);
8483 let selections_on_single_row = selections.windows(2).all(|selections| {
8484 selections[0].start.row == selections[1].start.row
8485 && selections[0].end.row == selections[1].end.row
8486 && selections[0].start.row == selections[0].end.row
8487 });
8488 let selections_selecting = selections
8489 .iter()
8490 .any(|selection| selection.start != selection.end);
8491 let advance_downwards = action.advance_downwards
8492 && selections_on_single_row
8493 && !selections_selecting
8494 && !matches!(this.mode, EditorMode::SingleLine { .. });
8495
8496 if advance_downwards {
8497 let snapshot = this.buffer.read(cx).snapshot(cx);
8498
8499 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8500 s.move_cursors_with(|display_snapshot, display_point, _| {
8501 let mut point = display_point.to_point(display_snapshot);
8502 point.row += 1;
8503 point = snapshot.clip_point(point, Bias::Left);
8504 let display_point = point.to_display_point(display_snapshot);
8505 let goal = SelectionGoal::HorizontalPosition(
8506 display_snapshot
8507 .x_for_display_point(display_point, &text_layout_details)
8508 .into(),
8509 );
8510 (display_point, goal)
8511 })
8512 });
8513 }
8514 });
8515 }
8516
8517 pub fn select_enclosing_symbol(
8518 &mut self,
8519 _: &SelectEnclosingSymbol,
8520 cx: &mut ViewContext<Self>,
8521 ) {
8522 let buffer = self.buffer.read(cx).snapshot(cx);
8523 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8524
8525 fn update_selection(
8526 selection: &Selection<usize>,
8527 buffer_snap: &MultiBufferSnapshot,
8528 ) -> Option<Selection<usize>> {
8529 let cursor = selection.head();
8530 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8531 for symbol in symbols.iter().rev() {
8532 let start = symbol.range.start.to_offset(&buffer_snap);
8533 let end = symbol.range.end.to_offset(&buffer_snap);
8534 let new_range = start..end;
8535 if start < selection.start || end > selection.end {
8536 return Some(Selection {
8537 id: selection.id,
8538 start: new_range.start,
8539 end: new_range.end,
8540 goal: SelectionGoal::None,
8541 reversed: selection.reversed,
8542 });
8543 }
8544 }
8545 None
8546 }
8547
8548 let mut selected_larger_symbol = false;
8549 let new_selections = old_selections
8550 .iter()
8551 .map(|selection| match update_selection(selection, &buffer) {
8552 Some(new_selection) => {
8553 if new_selection.range() != selection.range() {
8554 selected_larger_symbol = true;
8555 }
8556 new_selection
8557 }
8558 None => selection.clone(),
8559 })
8560 .collect::<Vec<_>>();
8561
8562 if selected_larger_symbol {
8563 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8564 s.select(new_selections);
8565 });
8566 }
8567 }
8568
8569 pub fn select_larger_syntax_node(
8570 &mut self,
8571 _: &SelectLargerSyntaxNode,
8572 cx: &mut ViewContext<Self>,
8573 ) {
8574 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8575 let buffer = self.buffer.read(cx).snapshot(cx);
8576 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8577
8578 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8579 let mut selected_larger_node = false;
8580 let new_selections = old_selections
8581 .iter()
8582 .map(|selection| {
8583 let old_range = selection.start..selection.end;
8584 let mut new_range = old_range.clone();
8585 while let Some(containing_range) =
8586 buffer.range_for_syntax_ancestor(new_range.clone())
8587 {
8588 new_range = containing_range;
8589 if !display_map.intersects_fold(new_range.start)
8590 && !display_map.intersects_fold(new_range.end)
8591 {
8592 break;
8593 }
8594 }
8595
8596 selected_larger_node |= new_range != old_range;
8597 Selection {
8598 id: selection.id,
8599 start: new_range.start,
8600 end: new_range.end,
8601 goal: SelectionGoal::None,
8602 reversed: selection.reversed,
8603 }
8604 })
8605 .collect::<Vec<_>>();
8606
8607 if selected_larger_node {
8608 stack.push(old_selections);
8609 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8610 s.select(new_selections);
8611 });
8612 }
8613 self.select_larger_syntax_node_stack = stack;
8614 }
8615
8616 pub fn select_smaller_syntax_node(
8617 &mut self,
8618 _: &SelectSmallerSyntaxNode,
8619 cx: &mut ViewContext<Self>,
8620 ) {
8621 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8622 if let Some(selections) = stack.pop() {
8623 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8624 s.select(selections.to_vec());
8625 });
8626 }
8627 self.select_larger_syntax_node_stack = stack;
8628 }
8629
8630 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8631 if !EditorSettings::get_global(cx).gutter.runnables {
8632 self.clear_tasks();
8633 return Task::ready(());
8634 }
8635 let project = self.project.clone();
8636 cx.spawn(|this, mut cx| async move {
8637 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8638 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8639 }) else {
8640 return;
8641 };
8642
8643 let Some(project) = project else {
8644 return;
8645 };
8646
8647 let hide_runnables = project
8648 .update(&mut cx, |project, cx| {
8649 // Do not display any test indicators in non-dev server remote projects.
8650 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8651 })
8652 .unwrap_or(true);
8653 if hide_runnables {
8654 return;
8655 }
8656 let new_rows =
8657 cx.background_executor()
8658 .spawn({
8659 let snapshot = display_snapshot.clone();
8660 async move {
8661 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8662 }
8663 })
8664 .await;
8665 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8666
8667 this.update(&mut cx, |this, _| {
8668 this.clear_tasks();
8669 for (key, value) in rows {
8670 this.insert_tasks(key, value);
8671 }
8672 })
8673 .ok();
8674 })
8675 }
8676 fn fetch_runnable_ranges(
8677 snapshot: &DisplaySnapshot,
8678 range: Range<Anchor>,
8679 ) -> Vec<language::RunnableRange> {
8680 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8681 }
8682
8683 fn runnable_rows(
8684 project: Model<Project>,
8685 snapshot: DisplaySnapshot,
8686 runnable_ranges: Vec<RunnableRange>,
8687 mut cx: AsyncWindowContext,
8688 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8689 runnable_ranges
8690 .into_iter()
8691 .filter_map(|mut runnable| {
8692 let tasks = cx
8693 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8694 .ok()?;
8695 if tasks.is_empty() {
8696 return None;
8697 }
8698
8699 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8700
8701 let row = snapshot
8702 .buffer_snapshot
8703 .buffer_line_for_row(MultiBufferRow(point.row))?
8704 .1
8705 .start
8706 .row;
8707
8708 let context_range =
8709 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8710 Some((
8711 (runnable.buffer_id, row),
8712 RunnableTasks {
8713 templates: tasks,
8714 offset: MultiBufferOffset(runnable.run_range.start),
8715 context_range,
8716 column: point.column,
8717 extra_variables: runnable.extra_captures,
8718 },
8719 ))
8720 })
8721 .collect()
8722 }
8723
8724 fn templates_with_tags(
8725 project: &Model<Project>,
8726 runnable: &mut Runnable,
8727 cx: &WindowContext<'_>,
8728 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8729 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8730 let (worktree_id, file) = project
8731 .buffer_for_id(runnable.buffer, cx)
8732 .and_then(|buffer| buffer.read(cx).file())
8733 .map(|file| (WorktreeId::from_usize(file.worktree_id()), file.clone()))
8734 .unzip();
8735
8736 (project.task_inventory().clone(), worktree_id, file)
8737 });
8738
8739 let inventory = inventory.read(cx);
8740 let tags = mem::take(&mut runnable.tags);
8741 let mut tags: Vec<_> = tags
8742 .into_iter()
8743 .flat_map(|tag| {
8744 let tag = tag.0.clone();
8745 inventory
8746 .list_tasks(
8747 file.clone(),
8748 Some(runnable.language.clone()),
8749 worktree_id,
8750 cx,
8751 )
8752 .into_iter()
8753 .filter(move |(_, template)| {
8754 template.tags.iter().any(|source_tag| source_tag == &tag)
8755 })
8756 })
8757 .sorted_by_key(|(kind, _)| kind.to_owned())
8758 .collect();
8759 if let Some((leading_tag_source, _)) = tags.first() {
8760 // Strongest source wins; if we have worktree tag binding, prefer that to
8761 // global and language bindings;
8762 // if we have a global binding, prefer that to language binding.
8763 let first_mismatch = tags
8764 .iter()
8765 .position(|(tag_source, _)| tag_source != leading_tag_source);
8766 if let Some(index) = first_mismatch {
8767 tags.truncate(index);
8768 }
8769 }
8770
8771 tags
8772 }
8773
8774 pub fn move_to_enclosing_bracket(
8775 &mut self,
8776 _: &MoveToEnclosingBracket,
8777 cx: &mut ViewContext<Self>,
8778 ) {
8779 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8780 s.move_offsets_with(|snapshot, selection| {
8781 let Some(enclosing_bracket_ranges) =
8782 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
8783 else {
8784 return;
8785 };
8786
8787 let mut best_length = usize::MAX;
8788 let mut best_inside = false;
8789 let mut best_in_bracket_range = false;
8790 let mut best_destination = None;
8791 for (open, close) in enclosing_bracket_ranges {
8792 let close = close.to_inclusive();
8793 let length = close.end() - open.start;
8794 let inside = selection.start >= open.end && selection.end <= *close.start();
8795 let in_bracket_range = open.to_inclusive().contains(&selection.head())
8796 || close.contains(&selection.head());
8797
8798 // If best is next to a bracket and current isn't, skip
8799 if !in_bracket_range && best_in_bracket_range {
8800 continue;
8801 }
8802
8803 // Prefer smaller lengths unless best is inside and current isn't
8804 if length > best_length && (best_inside || !inside) {
8805 continue;
8806 }
8807
8808 best_length = length;
8809 best_inside = inside;
8810 best_in_bracket_range = in_bracket_range;
8811 best_destination = Some(
8812 if close.contains(&selection.start) && close.contains(&selection.end) {
8813 if inside {
8814 open.end
8815 } else {
8816 open.start
8817 }
8818 } else {
8819 if inside {
8820 *close.start()
8821 } else {
8822 *close.end()
8823 }
8824 },
8825 );
8826 }
8827
8828 if let Some(destination) = best_destination {
8829 selection.collapse_to(destination, SelectionGoal::None);
8830 }
8831 })
8832 });
8833 }
8834
8835 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
8836 self.end_selection(cx);
8837 self.selection_history.mode = SelectionHistoryMode::Undoing;
8838 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
8839 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8840 self.select_next_state = entry.select_next_state;
8841 self.select_prev_state = entry.select_prev_state;
8842 self.add_selections_state = entry.add_selections_state;
8843 self.request_autoscroll(Autoscroll::newest(), cx);
8844 }
8845 self.selection_history.mode = SelectionHistoryMode::Normal;
8846 }
8847
8848 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
8849 self.end_selection(cx);
8850 self.selection_history.mode = SelectionHistoryMode::Redoing;
8851 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
8852 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8853 self.select_next_state = entry.select_next_state;
8854 self.select_prev_state = entry.select_prev_state;
8855 self.add_selections_state = entry.add_selections_state;
8856 self.request_autoscroll(Autoscroll::newest(), cx);
8857 }
8858 self.selection_history.mode = SelectionHistoryMode::Normal;
8859 }
8860
8861 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
8862 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
8863 }
8864
8865 pub fn expand_excerpts_down(
8866 &mut self,
8867 action: &ExpandExcerptsDown,
8868 cx: &mut ViewContext<Self>,
8869 ) {
8870 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
8871 }
8872
8873 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
8874 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
8875 }
8876
8877 pub fn expand_excerpts_for_direction(
8878 &mut self,
8879 lines: u32,
8880 direction: ExpandExcerptDirection,
8881 cx: &mut ViewContext<Self>,
8882 ) {
8883 let selections = self.selections.disjoint_anchors();
8884
8885 let lines = if lines == 0 {
8886 EditorSettings::get_global(cx).expand_excerpt_lines
8887 } else {
8888 lines
8889 };
8890
8891 self.buffer.update(cx, |buffer, cx| {
8892 buffer.expand_excerpts(
8893 selections
8894 .into_iter()
8895 .map(|selection| selection.head().excerpt_id)
8896 .dedup(),
8897 lines,
8898 direction,
8899 cx,
8900 )
8901 })
8902 }
8903
8904 pub fn expand_excerpt(
8905 &mut self,
8906 excerpt: ExcerptId,
8907 direction: ExpandExcerptDirection,
8908 cx: &mut ViewContext<Self>,
8909 ) {
8910 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
8911 self.buffer.update(cx, |buffer, cx| {
8912 buffer.expand_excerpts([excerpt], lines, direction, cx)
8913 })
8914 }
8915
8916 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
8917 self.go_to_diagnostic_impl(Direction::Next, cx)
8918 }
8919
8920 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
8921 self.go_to_diagnostic_impl(Direction::Prev, cx)
8922 }
8923
8924 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
8925 let buffer = self.buffer.read(cx).snapshot(cx);
8926 let selection = self.selections.newest::<usize>(cx);
8927
8928 // If there is an active Diagnostic Popover jump to its diagnostic instead.
8929 if direction == Direction::Next {
8930 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
8931 let (group_id, jump_to) = popover.activation_info();
8932 if self.activate_diagnostics(group_id, cx) {
8933 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8934 let mut new_selection = s.newest_anchor().clone();
8935 new_selection.collapse_to(jump_to, SelectionGoal::None);
8936 s.select_anchors(vec![new_selection.clone()]);
8937 });
8938 }
8939 return;
8940 }
8941 }
8942
8943 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
8944 active_diagnostics
8945 .primary_range
8946 .to_offset(&buffer)
8947 .to_inclusive()
8948 });
8949 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
8950 if active_primary_range.contains(&selection.head()) {
8951 *active_primary_range.start()
8952 } else {
8953 selection.head()
8954 }
8955 } else {
8956 selection.head()
8957 };
8958 let snapshot = self.snapshot(cx);
8959 loop {
8960 let diagnostics = if direction == Direction::Prev {
8961 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
8962 } else {
8963 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
8964 }
8965 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
8966 let group = diagnostics
8967 // relies on diagnostics_in_range to return diagnostics with the same starting range to
8968 // be sorted in a stable way
8969 // skip until we are at current active diagnostic, if it exists
8970 .skip_while(|entry| {
8971 (match direction {
8972 Direction::Prev => entry.range.start >= search_start,
8973 Direction::Next => entry.range.start <= search_start,
8974 }) && self
8975 .active_diagnostics
8976 .as_ref()
8977 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
8978 })
8979 .find_map(|entry| {
8980 if entry.diagnostic.is_primary
8981 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
8982 && !entry.range.is_empty()
8983 // if we match with the active diagnostic, skip it
8984 && Some(entry.diagnostic.group_id)
8985 != self.active_diagnostics.as_ref().map(|d| d.group_id)
8986 {
8987 Some((entry.range, entry.diagnostic.group_id))
8988 } else {
8989 None
8990 }
8991 });
8992
8993 if let Some((primary_range, group_id)) = group {
8994 if self.activate_diagnostics(group_id, cx) {
8995 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8996 s.select(vec![Selection {
8997 id: selection.id,
8998 start: primary_range.start,
8999 end: primary_range.start,
9000 reversed: false,
9001 goal: SelectionGoal::None,
9002 }]);
9003 });
9004 }
9005 break;
9006 } else {
9007 // Cycle around to the start of the buffer, potentially moving back to the start of
9008 // the currently active diagnostic.
9009 active_primary_range.take();
9010 if direction == Direction::Prev {
9011 if search_start == buffer.len() {
9012 break;
9013 } else {
9014 search_start = buffer.len();
9015 }
9016 } else if search_start == 0 {
9017 break;
9018 } else {
9019 search_start = 0;
9020 }
9021 }
9022 }
9023 }
9024
9025 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9026 let snapshot = self
9027 .display_map
9028 .update(cx, |display_map, cx| display_map.snapshot(cx));
9029 let selection = self.selections.newest::<Point>(cx);
9030
9031 if !self.seek_in_direction(
9032 &snapshot,
9033 selection.head(),
9034 false,
9035 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9036 MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
9037 ),
9038 cx,
9039 ) {
9040 let wrapped_point = Point::zero();
9041 self.seek_in_direction(
9042 &snapshot,
9043 wrapped_point,
9044 true,
9045 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9046 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9047 ),
9048 cx,
9049 );
9050 }
9051 }
9052
9053 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9054 let snapshot = self
9055 .display_map
9056 .update(cx, |display_map, cx| display_map.snapshot(cx));
9057 let selection = self.selections.newest::<Point>(cx);
9058
9059 if !self.seek_in_direction(
9060 &snapshot,
9061 selection.head(),
9062 false,
9063 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9064 MultiBufferRow(0)..MultiBufferRow(selection.head().row),
9065 ),
9066 cx,
9067 ) {
9068 let wrapped_point = snapshot.buffer_snapshot.max_point();
9069 self.seek_in_direction(
9070 &snapshot,
9071 wrapped_point,
9072 true,
9073 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9074 MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
9075 ),
9076 cx,
9077 );
9078 }
9079 }
9080
9081 fn seek_in_direction(
9082 &mut self,
9083 snapshot: &DisplaySnapshot,
9084 initial_point: Point,
9085 is_wrapped: bool,
9086 hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
9087 cx: &mut ViewContext<Editor>,
9088 ) -> bool {
9089 let display_point = initial_point.to_display_point(snapshot);
9090 let mut hunks = hunks
9091 .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
9092 .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
9093 .dedup();
9094
9095 if let Some(hunk) = hunks.next() {
9096 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9097 let row = hunk.start_display_row();
9098 let point = DisplayPoint::new(row, 0);
9099 s.select_display_ranges([point..point]);
9100 });
9101
9102 true
9103 } else {
9104 false
9105 }
9106 }
9107
9108 pub fn go_to_definition(
9109 &mut self,
9110 _: &GoToDefinition,
9111 cx: &mut ViewContext<Self>,
9112 ) -> Task<Result<Navigated>> {
9113 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9114 let references = self.find_all_references(&FindAllReferences, cx);
9115 cx.background_executor().spawn(async move {
9116 if definition.await? == Navigated::Yes {
9117 return Ok(Navigated::Yes);
9118 }
9119 if let Some(references) = references {
9120 if references.await? == Navigated::Yes {
9121 return Ok(Navigated::Yes);
9122 }
9123 }
9124
9125 Ok(Navigated::No)
9126 })
9127 }
9128
9129 pub fn go_to_declaration(
9130 &mut self,
9131 _: &GoToDeclaration,
9132 cx: &mut ViewContext<Self>,
9133 ) -> Task<Result<Navigated>> {
9134 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9135 }
9136
9137 pub fn go_to_declaration_split(
9138 &mut self,
9139 _: &GoToDeclaration,
9140 cx: &mut ViewContext<Self>,
9141 ) -> Task<Result<Navigated>> {
9142 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9143 }
9144
9145 pub fn go_to_implementation(
9146 &mut self,
9147 _: &GoToImplementation,
9148 cx: &mut ViewContext<Self>,
9149 ) -> Task<Result<Navigated>> {
9150 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9151 }
9152
9153 pub fn go_to_implementation_split(
9154 &mut self,
9155 _: &GoToImplementationSplit,
9156 cx: &mut ViewContext<Self>,
9157 ) -> Task<Result<Navigated>> {
9158 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9159 }
9160
9161 pub fn go_to_type_definition(
9162 &mut self,
9163 _: &GoToTypeDefinition,
9164 cx: &mut ViewContext<Self>,
9165 ) -> Task<Result<Navigated>> {
9166 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9167 }
9168
9169 pub fn go_to_definition_split(
9170 &mut self,
9171 _: &GoToDefinitionSplit,
9172 cx: &mut ViewContext<Self>,
9173 ) -> Task<Result<Navigated>> {
9174 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9175 }
9176
9177 pub fn go_to_type_definition_split(
9178 &mut self,
9179 _: &GoToTypeDefinitionSplit,
9180 cx: &mut ViewContext<Self>,
9181 ) -> Task<Result<Navigated>> {
9182 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9183 }
9184
9185 fn go_to_definition_of_kind(
9186 &mut self,
9187 kind: GotoDefinitionKind,
9188 split: bool,
9189 cx: &mut ViewContext<Self>,
9190 ) -> Task<Result<Navigated>> {
9191 let Some(workspace) = self.workspace() else {
9192 return Task::ready(Ok(Navigated::No));
9193 };
9194 let buffer = self.buffer.read(cx);
9195 let head = self.selections.newest::<usize>(cx).head();
9196 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9197 text_anchor
9198 } else {
9199 return Task::ready(Ok(Navigated::No));
9200 };
9201
9202 let project = workspace.read(cx).project().clone();
9203 let definitions = project.update(cx, |project, cx| match kind {
9204 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
9205 GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
9206 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
9207 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
9208 });
9209
9210 cx.spawn(|editor, mut cx| async move {
9211 let definitions = definitions.await?;
9212 let navigated = editor
9213 .update(&mut cx, |editor, cx| {
9214 editor.navigate_to_hover_links(
9215 Some(kind),
9216 definitions
9217 .into_iter()
9218 .filter(|location| {
9219 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9220 })
9221 .map(HoverLink::Text)
9222 .collect::<Vec<_>>(),
9223 split,
9224 cx,
9225 )
9226 })?
9227 .await?;
9228 anyhow::Ok(navigated)
9229 })
9230 }
9231
9232 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9233 let position = self.selections.newest_anchor().head();
9234 let Some((buffer, buffer_position)) =
9235 self.buffer.read(cx).text_anchor_for_position(position, cx)
9236 else {
9237 return;
9238 };
9239
9240 cx.spawn(|editor, mut cx| async move {
9241 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9242 editor.update(&mut cx, |_, cx| {
9243 cx.open_url(&url);
9244 })
9245 } else {
9246 Ok(())
9247 }
9248 })
9249 .detach();
9250 }
9251
9252 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9253 let Some(workspace) = self.workspace() else {
9254 return;
9255 };
9256
9257 let position = self.selections.newest_anchor().head();
9258
9259 let Some((buffer, buffer_position)) =
9260 self.buffer.read(cx).text_anchor_for_position(position, cx)
9261 else {
9262 return;
9263 };
9264
9265 let Some(project) = self.project.clone() else {
9266 return;
9267 };
9268
9269 cx.spawn(|_, mut cx| async move {
9270 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9271
9272 if let Some((_, path)) = result {
9273 workspace
9274 .update(&mut cx, |workspace, cx| {
9275 workspace.open_resolved_path(path, cx)
9276 })?
9277 .await?;
9278 }
9279 anyhow::Ok(())
9280 })
9281 .detach();
9282 }
9283
9284 pub(crate) fn navigate_to_hover_links(
9285 &mut self,
9286 kind: Option<GotoDefinitionKind>,
9287 mut definitions: Vec<HoverLink>,
9288 split: bool,
9289 cx: &mut ViewContext<Editor>,
9290 ) -> Task<Result<Navigated>> {
9291 // If there is one definition, just open it directly
9292 if definitions.len() == 1 {
9293 let definition = definitions.pop().unwrap();
9294
9295 enum TargetTaskResult {
9296 Location(Option<Location>),
9297 AlreadyNavigated,
9298 }
9299
9300 let target_task = match definition {
9301 HoverLink::Text(link) => {
9302 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9303 }
9304 HoverLink::InlayHint(lsp_location, server_id) => {
9305 let computation = self.compute_target_location(lsp_location, server_id, cx);
9306 cx.background_executor().spawn(async move {
9307 let location = computation.await?;
9308 Ok(TargetTaskResult::Location(location))
9309 })
9310 }
9311 HoverLink::Url(url) => {
9312 cx.open_url(&url);
9313 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9314 }
9315 HoverLink::File(path) => {
9316 if let Some(workspace) = self.workspace() {
9317 cx.spawn(|_, mut cx| async move {
9318 workspace
9319 .update(&mut cx, |workspace, cx| {
9320 workspace.open_resolved_path(path, cx)
9321 })?
9322 .await
9323 .map(|_| TargetTaskResult::AlreadyNavigated)
9324 })
9325 } else {
9326 Task::ready(Ok(TargetTaskResult::Location(None)))
9327 }
9328 }
9329 };
9330 cx.spawn(|editor, mut cx| async move {
9331 let target = match target_task.await.context("target resolution task")? {
9332 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9333 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9334 TargetTaskResult::Location(Some(target)) => target,
9335 };
9336
9337 editor.update(&mut cx, |editor, cx| {
9338 let Some(workspace) = editor.workspace() else {
9339 return Navigated::No;
9340 };
9341 let pane = workspace.read(cx).active_pane().clone();
9342
9343 let range = target.range.to_offset(target.buffer.read(cx));
9344 let range = editor.range_for_match(&range);
9345
9346 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9347 let buffer = target.buffer.read(cx);
9348 let range = check_multiline_range(buffer, range);
9349 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
9350 s.select_ranges([range]);
9351 });
9352 } else {
9353 cx.window_context().defer(move |cx| {
9354 let target_editor: View<Self> =
9355 workspace.update(cx, |workspace, cx| {
9356 let pane = if split {
9357 workspace.adjacent_pane(cx)
9358 } else {
9359 workspace.active_pane().clone()
9360 };
9361
9362 workspace.open_project_item(
9363 pane,
9364 target.buffer.clone(),
9365 true,
9366 true,
9367 cx,
9368 )
9369 });
9370 target_editor.update(cx, |target_editor, cx| {
9371 // When selecting a definition in a different buffer, disable the nav history
9372 // to avoid creating a history entry at the previous cursor location.
9373 pane.update(cx, |pane, _| pane.disable_history());
9374 let buffer = target.buffer.read(cx);
9375 let range = check_multiline_range(buffer, range);
9376 target_editor.change_selections(
9377 Some(Autoscroll::focused()),
9378 cx,
9379 |s| {
9380 s.select_ranges([range]);
9381 },
9382 );
9383 pane.update(cx, |pane, _| pane.enable_history());
9384 });
9385 });
9386 }
9387 Navigated::Yes
9388 })
9389 })
9390 } else if !definitions.is_empty() {
9391 let replica_id = self.replica_id(cx);
9392 cx.spawn(|editor, mut cx| async move {
9393 let (title, location_tasks, workspace) = editor
9394 .update(&mut cx, |editor, cx| {
9395 let tab_kind = match kind {
9396 Some(GotoDefinitionKind::Implementation) => "Implementations",
9397 _ => "Definitions",
9398 };
9399 let title = definitions
9400 .iter()
9401 .find_map(|definition| match definition {
9402 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9403 let buffer = origin.buffer.read(cx);
9404 format!(
9405 "{} for {}",
9406 tab_kind,
9407 buffer
9408 .text_for_range(origin.range.clone())
9409 .collect::<String>()
9410 )
9411 }),
9412 HoverLink::InlayHint(_, _) => None,
9413 HoverLink::Url(_) => None,
9414 HoverLink::File(_) => None,
9415 })
9416 .unwrap_or(tab_kind.to_string());
9417 let location_tasks = definitions
9418 .into_iter()
9419 .map(|definition| match definition {
9420 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9421 HoverLink::InlayHint(lsp_location, server_id) => {
9422 editor.compute_target_location(lsp_location, server_id, cx)
9423 }
9424 HoverLink::Url(_) => Task::ready(Ok(None)),
9425 HoverLink::File(_) => Task::ready(Ok(None)),
9426 })
9427 .collect::<Vec<_>>();
9428 (title, location_tasks, editor.workspace().clone())
9429 })
9430 .context("location tasks preparation")?;
9431
9432 let locations = futures::future::join_all(location_tasks)
9433 .await
9434 .into_iter()
9435 .filter_map(|location| location.transpose())
9436 .collect::<Result<_>>()
9437 .context("location tasks")?;
9438
9439 let Some(workspace) = workspace else {
9440 return Ok(Navigated::No);
9441 };
9442 let opened = workspace
9443 .update(&mut cx, |workspace, cx| {
9444 Self::open_locations_in_multibuffer(
9445 workspace, locations, replica_id, title, split, cx,
9446 )
9447 })
9448 .ok();
9449
9450 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9451 })
9452 } else {
9453 Task::ready(Ok(Navigated::No))
9454 }
9455 }
9456
9457 fn compute_target_location(
9458 &self,
9459 lsp_location: lsp::Location,
9460 server_id: LanguageServerId,
9461 cx: &mut ViewContext<Editor>,
9462 ) -> Task<anyhow::Result<Option<Location>>> {
9463 let Some(project) = self.project.clone() else {
9464 return Task::Ready(Some(Ok(None)));
9465 };
9466
9467 cx.spawn(move |editor, mut cx| async move {
9468 let location_task = editor.update(&mut cx, |editor, cx| {
9469 project.update(cx, |project, cx| {
9470 let language_server_name =
9471 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9472 project
9473 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9474 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9475 });
9476 language_server_name.map(|language_server_name| {
9477 project.open_local_buffer_via_lsp(
9478 lsp_location.uri.clone(),
9479 server_id,
9480 language_server_name,
9481 cx,
9482 )
9483 })
9484 })
9485 })?;
9486 let location = match location_task {
9487 Some(task) => Some({
9488 let target_buffer_handle = task.await.context("open local buffer")?;
9489 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9490 let target_start = target_buffer
9491 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9492 let target_end = target_buffer
9493 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9494 target_buffer.anchor_after(target_start)
9495 ..target_buffer.anchor_before(target_end)
9496 })?;
9497 Location {
9498 buffer: target_buffer_handle,
9499 range,
9500 }
9501 }),
9502 None => None,
9503 };
9504 Ok(location)
9505 })
9506 }
9507
9508 pub fn find_all_references(
9509 &mut self,
9510 _: &FindAllReferences,
9511 cx: &mut ViewContext<Self>,
9512 ) -> Option<Task<Result<Navigated>>> {
9513 let multi_buffer = self.buffer.read(cx);
9514 let selection = self.selections.newest::<usize>(cx);
9515 let head = selection.head();
9516
9517 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9518 let head_anchor = multi_buffer_snapshot.anchor_at(
9519 head,
9520 if head < selection.tail() {
9521 Bias::Right
9522 } else {
9523 Bias::Left
9524 },
9525 );
9526
9527 match self
9528 .find_all_references_task_sources
9529 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9530 {
9531 Ok(_) => {
9532 log::info!(
9533 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9534 );
9535 return None;
9536 }
9537 Err(i) => {
9538 self.find_all_references_task_sources.insert(i, head_anchor);
9539 }
9540 }
9541
9542 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9543 let replica_id = self.replica_id(cx);
9544 let workspace = self.workspace()?;
9545 let project = workspace.read(cx).project().clone();
9546 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9547 Some(cx.spawn(|editor, mut cx| async move {
9548 let _cleanup = defer({
9549 let mut cx = cx.clone();
9550 move || {
9551 let _ = editor.update(&mut cx, |editor, _| {
9552 if let Ok(i) =
9553 editor
9554 .find_all_references_task_sources
9555 .binary_search_by(|anchor| {
9556 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9557 })
9558 {
9559 editor.find_all_references_task_sources.remove(i);
9560 }
9561 });
9562 }
9563 });
9564
9565 let locations = references.await?;
9566 if locations.is_empty() {
9567 return anyhow::Ok(Navigated::No);
9568 }
9569
9570 workspace.update(&mut cx, |workspace, cx| {
9571 let title = locations
9572 .first()
9573 .as_ref()
9574 .map(|location| {
9575 let buffer = location.buffer.read(cx);
9576 format!(
9577 "References to `{}`",
9578 buffer
9579 .text_for_range(location.range.clone())
9580 .collect::<String>()
9581 )
9582 })
9583 .unwrap();
9584 Self::open_locations_in_multibuffer(
9585 workspace, locations, replica_id, title, false, cx,
9586 );
9587 Navigated::Yes
9588 })
9589 }))
9590 }
9591
9592 /// Opens a multibuffer with the given project locations in it
9593 pub fn open_locations_in_multibuffer(
9594 workspace: &mut Workspace,
9595 mut locations: Vec<Location>,
9596 replica_id: ReplicaId,
9597 title: String,
9598 split: bool,
9599 cx: &mut ViewContext<Workspace>,
9600 ) {
9601 // If there are multiple definitions, open them in a multibuffer
9602 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9603 let mut locations = locations.into_iter().peekable();
9604 let mut ranges_to_highlight = Vec::new();
9605 let capability = workspace.project().read(cx).capability();
9606
9607 let excerpt_buffer = cx.new_model(|cx| {
9608 let mut multibuffer = MultiBuffer::new(replica_id, capability);
9609 while let Some(location) = locations.next() {
9610 let buffer = location.buffer.read(cx);
9611 let mut ranges_for_buffer = Vec::new();
9612 let range = location.range.to_offset(buffer);
9613 ranges_for_buffer.push(range.clone());
9614
9615 while let Some(next_location) = locations.peek() {
9616 if next_location.buffer == location.buffer {
9617 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9618 locations.next();
9619 } else {
9620 break;
9621 }
9622 }
9623
9624 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9625 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9626 location.buffer.clone(),
9627 ranges_for_buffer,
9628 DEFAULT_MULTIBUFFER_CONTEXT,
9629 cx,
9630 ))
9631 }
9632
9633 multibuffer.with_title(title)
9634 });
9635
9636 let editor = cx.new_view(|cx| {
9637 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9638 });
9639 editor.update(cx, |editor, cx| {
9640 if let Some(first_range) = ranges_to_highlight.first() {
9641 editor.change_selections(None, cx, |selections| {
9642 selections.clear_disjoint();
9643 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9644 });
9645 }
9646 editor.highlight_background::<Self>(
9647 &ranges_to_highlight,
9648 |theme| theme.editor_highlighted_line_background,
9649 cx,
9650 );
9651 });
9652
9653 let item = Box::new(editor);
9654 let item_id = item.item_id();
9655
9656 if split {
9657 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9658 } else {
9659 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9660 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9661 pane.close_current_preview_item(cx)
9662 } else {
9663 None
9664 }
9665 });
9666 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9667 }
9668 workspace.active_pane().update(cx, |pane, cx| {
9669 pane.set_preview_item_id(Some(item_id), cx);
9670 });
9671 }
9672
9673 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9674 use language::ToOffset as _;
9675
9676 let project = self.project.clone()?;
9677 let selection = self.selections.newest_anchor().clone();
9678 let (cursor_buffer, cursor_buffer_position) = self
9679 .buffer
9680 .read(cx)
9681 .text_anchor_for_position(selection.head(), cx)?;
9682 let (tail_buffer, cursor_buffer_position_end) = self
9683 .buffer
9684 .read(cx)
9685 .text_anchor_for_position(selection.tail(), cx)?;
9686 if tail_buffer != cursor_buffer {
9687 return None;
9688 }
9689
9690 let snapshot = cursor_buffer.read(cx).snapshot();
9691 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9692 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9693 let prepare_rename = project.update(cx, |project, cx| {
9694 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
9695 });
9696 drop(snapshot);
9697
9698 Some(cx.spawn(|this, mut cx| async move {
9699 let rename_range = if let Some(range) = prepare_rename.await? {
9700 Some(range)
9701 } else {
9702 this.update(&mut cx, |this, cx| {
9703 let buffer = this.buffer.read(cx).snapshot(cx);
9704 let mut buffer_highlights = this
9705 .document_highlights_for_position(selection.head(), &buffer)
9706 .filter(|highlight| {
9707 highlight.start.excerpt_id == selection.head().excerpt_id
9708 && highlight.end.excerpt_id == selection.head().excerpt_id
9709 });
9710 buffer_highlights
9711 .next()
9712 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9713 })?
9714 };
9715 if let Some(rename_range) = rename_range {
9716 this.update(&mut cx, |this, cx| {
9717 let snapshot = cursor_buffer.read(cx).snapshot();
9718 let rename_buffer_range = rename_range.to_offset(&snapshot);
9719 let cursor_offset_in_rename_range =
9720 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9721 let cursor_offset_in_rename_range_end =
9722 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9723
9724 this.take_rename(false, cx);
9725 let buffer = this.buffer.read(cx).read(cx);
9726 let cursor_offset = selection.head().to_offset(&buffer);
9727 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9728 let rename_end = rename_start + rename_buffer_range.len();
9729 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9730 let mut old_highlight_id = None;
9731 let old_name: Arc<str> = buffer
9732 .chunks(rename_start..rename_end, true)
9733 .map(|chunk| {
9734 if old_highlight_id.is_none() {
9735 old_highlight_id = chunk.syntax_highlight_id;
9736 }
9737 chunk.text
9738 })
9739 .collect::<String>()
9740 .into();
9741
9742 drop(buffer);
9743
9744 // Position the selection in the rename editor so that it matches the current selection.
9745 this.show_local_selections = false;
9746 let rename_editor = cx.new_view(|cx| {
9747 let mut editor = Editor::single_line(cx);
9748 editor.buffer.update(cx, |buffer, cx| {
9749 buffer.edit([(0..0, old_name.clone())], None, cx)
9750 });
9751 let rename_selection_range = match cursor_offset_in_rename_range
9752 .cmp(&cursor_offset_in_rename_range_end)
9753 {
9754 Ordering::Equal => {
9755 editor.select_all(&SelectAll, cx);
9756 return editor;
9757 }
9758 Ordering::Less => {
9759 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9760 }
9761 Ordering::Greater => {
9762 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9763 }
9764 };
9765 if rename_selection_range.end > old_name.len() {
9766 editor.select_all(&SelectAll, cx);
9767 } else {
9768 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9769 s.select_ranges([rename_selection_range]);
9770 });
9771 }
9772 editor
9773 });
9774 cx.subscribe(&rename_editor, |_, _, e, cx| match e {
9775 EditorEvent::Focused => cx.emit(EditorEvent::FocusedIn),
9776 _ => {}
9777 })
9778 .detach();
9779
9780 let write_highlights =
9781 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
9782 let read_highlights =
9783 this.clear_background_highlights::<DocumentHighlightRead>(cx);
9784 let ranges = write_highlights
9785 .iter()
9786 .flat_map(|(_, ranges)| ranges.iter())
9787 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
9788 .cloned()
9789 .collect();
9790
9791 this.highlight_text::<Rename>(
9792 ranges,
9793 HighlightStyle {
9794 fade_out: Some(0.6),
9795 ..Default::default()
9796 },
9797 cx,
9798 );
9799 let rename_focus_handle = rename_editor.focus_handle(cx);
9800 cx.focus(&rename_focus_handle);
9801 let block_id = this.insert_blocks(
9802 [BlockProperties {
9803 style: BlockStyle::Flex,
9804 position: range.start,
9805 height: 1,
9806 render: Box::new({
9807 let rename_editor = rename_editor.clone();
9808 move |cx: &mut BlockContext| {
9809 let mut text_style = cx.editor_style.text.clone();
9810 if let Some(highlight_style) = old_highlight_id
9811 .and_then(|h| h.style(&cx.editor_style.syntax))
9812 {
9813 text_style = text_style.highlight(highlight_style);
9814 }
9815 div()
9816 .pl(cx.anchor_x)
9817 .child(EditorElement::new(
9818 &rename_editor,
9819 EditorStyle {
9820 background: cx.theme().system().transparent,
9821 local_player: cx.editor_style.local_player,
9822 text: text_style,
9823 scrollbar_width: cx.editor_style.scrollbar_width,
9824 syntax: cx.editor_style.syntax.clone(),
9825 status: cx.editor_style.status.clone(),
9826 inlay_hints_style: HighlightStyle {
9827 color: Some(cx.theme().status().hint),
9828 font_weight: Some(FontWeight::BOLD),
9829 ..HighlightStyle::default()
9830 },
9831 suggestions_style: HighlightStyle {
9832 color: Some(cx.theme().status().predictive),
9833 ..HighlightStyle::default()
9834 },
9835 ..EditorStyle::default()
9836 },
9837 ))
9838 .into_any_element()
9839 }
9840 }),
9841 disposition: BlockDisposition::Below,
9842 priority: 0,
9843 }],
9844 Some(Autoscroll::fit()),
9845 cx,
9846 )[0];
9847 this.pending_rename = Some(RenameState {
9848 range,
9849 old_name,
9850 editor: rename_editor,
9851 block_id,
9852 });
9853 })?;
9854 }
9855
9856 Ok(())
9857 }))
9858 }
9859
9860 pub fn confirm_rename(
9861 &mut self,
9862 _: &ConfirmRename,
9863 cx: &mut ViewContext<Self>,
9864 ) -> Option<Task<Result<()>>> {
9865 let rename = self.take_rename(false, cx)?;
9866 let workspace = self.workspace()?;
9867 let (start_buffer, start) = self
9868 .buffer
9869 .read(cx)
9870 .text_anchor_for_position(rename.range.start, cx)?;
9871 let (end_buffer, end) = self
9872 .buffer
9873 .read(cx)
9874 .text_anchor_for_position(rename.range.end, cx)?;
9875 if start_buffer != end_buffer {
9876 return None;
9877 }
9878
9879 let buffer = start_buffer;
9880 let range = start..end;
9881 let old_name = rename.old_name;
9882 let new_name = rename.editor.read(cx).text(cx);
9883
9884 let rename = workspace
9885 .read(cx)
9886 .project()
9887 .clone()
9888 .update(cx, |project, cx| {
9889 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
9890 });
9891 let workspace = workspace.downgrade();
9892
9893 Some(cx.spawn(|editor, mut cx| async move {
9894 let project_transaction = rename.await?;
9895 Self::open_project_transaction(
9896 &editor,
9897 workspace,
9898 project_transaction,
9899 format!("Rename: {} → {}", old_name, new_name),
9900 cx.clone(),
9901 )
9902 .await?;
9903
9904 editor.update(&mut cx, |editor, cx| {
9905 editor.refresh_document_highlights(cx);
9906 })?;
9907 Ok(())
9908 }))
9909 }
9910
9911 fn take_rename(
9912 &mut self,
9913 moving_cursor: bool,
9914 cx: &mut ViewContext<Self>,
9915 ) -> Option<RenameState> {
9916 let rename = self.pending_rename.take()?;
9917 if rename.editor.focus_handle(cx).is_focused(cx) {
9918 cx.focus(&self.focus_handle);
9919 }
9920
9921 self.remove_blocks(
9922 [rename.block_id].into_iter().collect(),
9923 Some(Autoscroll::fit()),
9924 cx,
9925 );
9926 self.clear_highlights::<Rename>(cx);
9927 self.show_local_selections = true;
9928
9929 if moving_cursor {
9930 let rename_editor = rename.editor.read(cx);
9931 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
9932
9933 // Update the selection to match the position of the selection inside
9934 // the rename editor.
9935 let snapshot = self.buffer.read(cx).read(cx);
9936 let rename_range = rename.range.to_offset(&snapshot);
9937 let cursor_in_editor = snapshot
9938 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
9939 .min(rename_range.end);
9940 drop(snapshot);
9941
9942 self.change_selections(None, cx, |s| {
9943 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
9944 });
9945 } else {
9946 self.refresh_document_highlights(cx);
9947 }
9948
9949 Some(rename)
9950 }
9951
9952 pub fn pending_rename(&self) -> Option<&RenameState> {
9953 self.pending_rename.as_ref()
9954 }
9955
9956 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9957 let project = match &self.project {
9958 Some(project) => project.clone(),
9959 None => return None,
9960 };
9961
9962 Some(self.perform_format(project, FormatTrigger::Manual, cx))
9963 }
9964
9965 fn perform_format(
9966 &mut self,
9967 project: Model<Project>,
9968 trigger: FormatTrigger,
9969 cx: &mut ViewContext<Self>,
9970 ) -> Task<Result<()>> {
9971 let buffer = self.buffer().clone();
9972 let mut buffers = buffer.read(cx).all_buffers();
9973 if trigger == FormatTrigger::Save {
9974 buffers.retain(|buffer| buffer.read(cx).is_dirty());
9975 }
9976
9977 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
9978 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
9979
9980 cx.spawn(|_, mut cx| async move {
9981 let transaction = futures::select_biased! {
9982 () = timeout => {
9983 log::warn!("timed out waiting for formatting");
9984 None
9985 }
9986 transaction = format.log_err().fuse() => transaction,
9987 };
9988
9989 buffer
9990 .update(&mut cx, |buffer, cx| {
9991 if let Some(transaction) = transaction {
9992 if !buffer.is_singleton() {
9993 buffer.push_transaction(&transaction.0, cx);
9994 }
9995 }
9996
9997 cx.notify();
9998 })
9999 .ok();
10000
10001 Ok(())
10002 })
10003 }
10004
10005 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10006 if let Some(project) = self.project.clone() {
10007 self.buffer.update(cx, |multi_buffer, cx| {
10008 project.update(cx, |project, cx| {
10009 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10010 });
10011 })
10012 }
10013 }
10014
10015 fn cancel_language_server_work(
10016 &mut self,
10017 _: &CancelLanguageServerWork,
10018 cx: &mut ViewContext<Self>,
10019 ) {
10020 if let Some(project) = self.project.clone() {
10021 self.buffer.update(cx, |multi_buffer, cx| {
10022 project.update(cx, |project, cx| {
10023 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10024 });
10025 })
10026 }
10027 }
10028
10029 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10030 cx.show_character_palette();
10031 }
10032
10033 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10034 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10035 let buffer = self.buffer.read(cx).snapshot(cx);
10036 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10037 let is_valid = buffer
10038 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10039 .any(|entry| {
10040 entry.diagnostic.is_primary
10041 && !entry.range.is_empty()
10042 && entry.range.start == primary_range_start
10043 && entry.diagnostic.message == active_diagnostics.primary_message
10044 });
10045
10046 if is_valid != active_diagnostics.is_valid {
10047 active_diagnostics.is_valid = is_valid;
10048 let mut new_styles = HashMap::default();
10049 for (block_id, diagnostic) in &active_diagnostics.blocks {
10050 new_styles.insert(
10051 *block_id,
10052 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10053 );
10054 }
10055 self.display_map.update(cx, |display_map, _cx| {
10056 display_map.replace_blocks(new_styles)
10057 });
10058 }
10059 }
10060 }
10061
10062 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10063 self.dismiss_diagnostics(cx);
10064 let snapshot = self.snapshot(cx);
10065 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10066 let buffer = self.buffer.read(cx).snapshot(cx);
10067
10068 let mut primary_range = None;
10069 let mut primary_message = None;
10070 let mut group_end = Point::zero();
10071 let diagnostic_group = buffer
10072 .diagnostic_group::<MultiBufferPoint>(group_id)
10073 .filter_map(|entry| {
10074 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10075 && (entry.range.start.row == entry.range.end.row
10076 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10077 {
10078 return None;
10079 }
10080 if entry.range.end > group_end {
10081 group_end = entry.range.end;
10082 }
10083 if entry.diagnostic.is_primary {
10084 primary_range = Some(entry.range.clone());
10085 primary_message = Some(entry.diagnostic.message.clone());
10086 }
10087 Some(entry)
10088 })
10089 .collect::<Vec<_>>();
10090 let primary_range = primary_range?;
10091 let primary_message = primary_message?;
10092 let primary_range =
10093 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10094
10095 let blocks = display_map
10096 .insert_blocks(
10097 diagnostic_group.iter().map(|entry| {
10098 let diagnostic = entry.diagnostic.clone();
10099 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10100 BlockProperties {
10101 style: BlockStyle::Fixed,
10102 position: buffer.anchor_after(entry.range.start),
10103 height: message_height,
10104 render: diagnostic_block_renderer(diagnostic, None, true, true),
10105 disposition: BlockDisposition::Below,
10106 priority: 0,
10107 }
10108 }),
10109 cx,
10110 )
10111 .into_iter()
10112 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10113 .collect();
10114
10115 Some(ActiveDiagnosticGroup {
10116 primary_range,
10117 primary_message,
10118 group_id,
10119 blocks,
10120 is_valid: true,
10121 })
10122 });
10123 self.active_diagnostics.is_some()
10124 }
10125
10126 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10127 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10128 self.display_map.update(cx, |display_map, cx| {
10129 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10130 });
10131 cx.notify();
10132 }
10133 }
10134
10135 pub fn set_selections_from_remote(
10136 &mut self,
10137 selections: Vec<Selection<Anchor>>,
10138 pending_selection: Option<Selection<Anchor>>,
10139 cx: &mut ViewContext<Self>,
10140 ) {
10141 let old_cursor_position = self.selections.newest_anchor().head();
10142 self.selections.change_with(cx, |s| {
10143 s.select_anchors(selections);
10144 if let Some(pending_selection) = pending_selection {
10145 s.set_pending(pending_selection, SelectMode::Character);
10146 } else {
10147 s.clear_pending();
10148 }
10149 });
10150 self.selections_did_change(false, &old_cursor_position, true, cx);
10151 }
10152
10153 fn push_to_selection_history(&mut self) {
10154 self.selection_history.push(SelectionHistoryEntry {
10155 selections: self.selections.disjoint_anchors(),
10156 select_next_state: self.select_next_state.clone(),
10157 select_prev_state: self.select_prev_state.clone(),
10158 add_selections_state: self.add_selections_state.clone(),
10159 });
10160 }
10161
10162 pub fn transact(
10163 &mut self,
10164 cx: &mut ViewContext<Self>,
10165 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10166 ) -> Option<TransactionId> {
10167 self.start_transaction_at(Instant::now(), cx);
10168 update(self, cx);
10169 self.end_transaction_at(Instant::now(), cx)
10170 }
10171
10172 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10173 self.end_selection(cx);
10174 if let Some(tx_id) = self
10175 .buffer
10176 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10177 {
10178 self.selection_history
10179 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10180 cx.emit(EditorEvent::TransactionBegun {
10181 transaction_id: tx_id,
10182 })
10183 }
10184 }
10185
10186 fn end_transaction_at(
10187 &mut self,
10188 now: Instant,
10189 cx: &mut ViewContext<Self>,
10190 ) -> Option<TransactionId> {
10191 if let Some(transaction_id) = self
10192 .buffer
10193 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10194 {
10195 if let Some((_, end_selections)) =
10196 self.selection_history.transaction_mut(transaction_id)
10197 {
10198 *end_selections = Some(self.selections.disjoint_anchors());
10199 } else {
10200 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10201 }
10202
10203 cx.emit(EditorEvent::Edited { transaction_id });
10204 Some(transaction_id)
10205 } else {
10206 None
10207 }
10208 }
10209
10210 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10211 let mut fold_ranges = Vec::new();
10212
10213 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10214
10215 let selections = self.selections.all_adjusted(cx);
10216 for selection in selections {
10217 let range = selection.range().sorted();
10218 let buffer_start_row = range.start.row;
10219
10220 for row in (0..=range.end.row).rev() {
10221 if let Some((foldable_range, fold_text)) =
10222 display_map.foldable_range(MultiBufferRow(row))
10223 {
10224 if foldable_range.end.row >= buffer_start_row {
10225 fold_ranges.push((foldable_range, fold_text));
10226 if row <= range.start.row {
10227 break;
10228 }
10229 }
10230 }
10231 }
10232 }
10233
10234 self.fold_ranges(fold_ranges, true, cx);
10235 }
10236
10237 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10238 let buffer_row = fold_at.buffer_row;
10239 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10240
10241 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10242 let autoscroll = self
10243 .selections
10244 .all::<Point>(cx)
10245 .iter()
10246 .any(|selection| fold_range.overlaps(&selection.range()));
10247
10248 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10249 }
10250 }
10251
10252 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10253 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10254 let buffer = &display_map.buffer_snapshot;
10255 let selections = self.selections.all::<Point>(cx);
10256 let ranges = selections
10257 .iter()
10258 .map(|s| {
10259 let range = s.display_range(&display_map).sorted();
10260 let mut start = range.start.to_point(&display_map);
10261 let mut end = range.end.to_point(&display_map);
10262 start.column = 0;
10263 end.column = buffer.line_len(MultiBufferRow(end.row));
10264 start..end
10265 })
10266 .collect::<Vec<_>>();
10267
10268 self.unfold_ranges(ranges, true, true, cx);
10269 }
10270
10271 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10272 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10273
10274 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10275 ..Point::new(
10276 unfold_at.buffer_row.0,
10277 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10278 );
10279
10280 let autoscroll = self
10281 .selections
10282 .all::<Point>(cx)
10283 .iter()
10284 .any(|selection| selection.range().overlaps(&intersection_range));
10285
10286 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10287 }
10288
10289 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10290 let selections = self.selections.all::<Point>(cx);
10291 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10292 let line_mode = self.selections.line_mode;
10293 let ranges = selections.into_iter().map(|s| {
10294 if line_mode {
10295 let start = Point::new(s.start.row, 0);
10296 let end = Point::new(
10297 s.end.row,
10298 display_map
10299 .buffer_snapshot
10300 .line_len(MultiBufferRow(s.end.row)),
10301 );
10302 (start..end, display_map.fold_placeholder.clone())
10303 } else {
10304 (s.start..s.end, display_map.fold_placeholder.clone())
10305 }
10306 });
10307 self.fold_ranges(ranges, true, cx);
10308 }
10309
10310 pub fn fold_ranges<T: ToOffset + Clone>(
10311 &mut self,
10312 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10313 auto_scroll: bool,
10314 cx: &mut ViewContext<Self>,
10315 ) {
10316 let mut fold_ranges = Vec::new();
10317 let mut buffers_affected = HashMap::default();
10318 let multi_buffer = self.buffer().read(cx);
10319 for (fold_range, fold_text) in ranges {
10320 if let Some((_, buffer, _)) =
10321 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10322 {
10323 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10324 };
10325 fold_ranges.push((fold_range, fold_text));
10326 }
10327
10328 let mut ranges = fold_ranges.into_iter().peekable();
10329 if ranges.peek().is_some() {
10330 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10331
10332 if auto_scroll {
10333 self.request_autoscroll(Autoscroll::fit(), cx);
10334 }
10335
10336 for buffer in buffers_affected.into_values() {
10337 self.sync_expanded_diff_hunks(buffer, cx);
10338 }
10339
10340 cx.notify();
10341
10342 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10343 // Clear diagnostics block when folding a range that contains it.
10344 let snapshot = self.snapshot(cx);
10345 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10346 drop(snapshot);
10347 self.active_diagnostics = Some(active_diagnostics);
10348 self.dismiss_diagnostics(cx);
10349 } else {
10350 self.active_diagnostics = Some(active_diagnostics);
10351 }
10352 }
10353
10354 self.scrollbar_marker_state.dirty = true;
10355 }
10356 }
10357
10358 pub fn unfold_ranges<T: ToOffset + Clone>(
10359 &mut self,
10360 ranges: impl IntoIterator<Item = Range<T>>,
10361 inclusive: bool,
10362 auto_scroll: bool,
10363 cx: &mut ViewContext<Self>,
10364 ) {
10365 let mut unfold_ranges = Vec::new();
10366 let mut buffers_affected = HashMap::default();
10367 let multi_buffer = self.buffer().read(cx);
10368 for range in ranges {
10369 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10370 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10371 };
10372 unfold_ranges.push(range);
10373 }
10374
10375 let mut ranges = unfold_ranges.into_iter().peekable();
10376 if ranges.peek().is_some() {
10377 self.display_map
10378 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10379 if auto_scroll {
10380 self.request_autoscroll(Autoscroll::fit(), cx);
10381 }
10382
10383 for buffer in buffers_affected.into_values() {
10384 self.sync_expanded_diff_hunks(buffer, cx);
10385 }
10386
10387 cx.notify();
10388 self.scrollbar_marker_state.dirty = true;
10389 self.active_indent_guides_state.dirty = true;
10390 }
10391 }
10392
10393 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10394 if hovered != self.gutter_hovered {
10395 self.gutter_hovered = hovered;
10396 cx.notify();
10397 }
10398 }
10399
10400 pub fn insert_blocks(
10401 &mut self,
10402 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10403 autoscroll: Option<Autoscroll>,
10404 cx: &mut ViewContext<Self>,
10405 ) -> Vec<CustomBlockId> {
10406 let blocks = self
10407 .display_map
10408 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10409 if let Some(autoscroll) = autoscroll {
10410 self.request_autoscroll(autoscroll, cx);
10411 }
10412 cx.notify();
10413 blocks
10414 }
10415
10416 pub fn resize_blocks(
10417 &mut self,
10418 heights: HashMap<CustomBlockId, u32>,
10419 autoscroll: Option<Autoscroll>,
10420 cx: &mut ViewContext<Self>,
10421 ) {
10422 self.display_map
10423 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10424 if let Some(autoscroll) = autoscroll {
10425 self.request_autoscroll(autoscroll, cx);
10426 }
10427 cx.notify();
10428 }
10429
10430 pub fn replace_blocks(
10431 &mut self,
10432 renderers: HashMap<CustomBlockId, RenderBlock>,
10433 autoscroll: Option<Autoscroll>,
10434 cx: &mut ViewContext<Self>,
10435 ) {
10436 self.display_map
10437 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10438 if let Some(autoscroll) = autoscroll {
10439 self.request_autoscroll(autoscroll, cx);
10440 }
10441 cx.notify();
10442 }
10443
10444 pub fn remove_blocks(
10445 &mut self,
10446 block_ids: HashSet<CustomBlockId>,
10447 autoscroll: Option<Autoscroll>,
10448 cx: &mut ViewContext<Self>,
10449 ) {
10450 self.display_map.update(cx, |display_map, cx| {
10451 display_map.remove_blocks(block_ids, cx)
10452 });
10453 if let Some(autoscroll) = autoscroll {
10454 self.request_autoscroll(autoscroll, cx);
10455 }
10456 cx.notify();
10457 }
10458
10459 pub fn row_for_block(
10460 &self,
10461 block_id: CustomBlockId,
10462 cx: &mut ViewContext<Self>,
10463 ) -> Option<DisplayRow> {
10464 self.display_map
10465 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10466 }
10467
10468 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10469 self.focused_block = Some(focused_block);
10470 }
10471
10472 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10473 self.focused_block.take()
10474 }
10475
10476 pub fn insert_creases(
10477 &mut self,
10478 creases: impl IntoIterator<Item = Crease>,
10479 cx: &mut ViewContext<Self>,
10480 ) -> Vec<CreaseId> {
10481 self.display_map
10482 .update(cx, |map, cx| map.insert_creases(creases, cx))
10483 }
10484
10485 pub fn remove_creases(
10486 &mut self,
10487 ids: impl IntoIterator<Item = CreaseId>,
10488 cx: &mut ViewContext<Self>,
10489 ) {
10490 self.display_map
10491 .update(cx, |map, cx| map.remove_creases(ids, cx));
10492 }
10493
10494 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10495 self.display_map
10496 .update(cx, |map, cx| map.snapshot(cx))
10497 .longest_row()
10498 }
10499
10500 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10501 self.display_map
10502 .update(cx, |map, cx| map.snapshot(cx))
10503 .max_point()
10504 }
10505
10506 pub fn text(&self, cx: &AppContext) -> String {
10507 self.buffer.read(cx).read(cx).text()
10508 }
10509
10510 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10511 let text = self.text(cx);
10512 let text = text.trim();
10513
10514 if text.is_empty() {
10515 return None;
10516 }
10517
10518 Some(text.to_string())
10519 }
10520
10521 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10522 self.transact(cx, |this, cx| {
10523 this.buffer
10524 .read(cx)
10525 .as_singleton()
10526 .expect("you can only call set_text on editors for singleton buffers")
10527 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10528 });
10529 }
10530
10531 pub fn display_text(&self, cx: &mut AppContext) -> String {
10532 self.display_map
10533 .update(cx, |map, cx| map.snapshot(cx))
10534 .text()
10535 }
10536
10537 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10538 let mut wrap_guides = smallvec::smallvec![];
10539
10540 if self.show_wrap_guides == Some(false) {
10541 return wrap_guides;
10542 }
10543
10544 let settings = self.buffer.read(cx).settings_at(0, cx);
10545 if settings.show_wrap_guides {
10546 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10547 wrap_guides.push((soft_wrap as usize, true));
10548 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
10549 wrap_guides.push((soft_wrap as usize, true));
10550 }
10551 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10552 }
10553
10554 wrap_guides
10555 }
10556
10557 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10558 let settings = self.buffer.read(cx).settings_at(0, cx);
10559 let mode = self
10560 .soft_wrap_mode_override
10561 .unwrap_or_else(|| settings.soft_wrap);
10562 match mode {
10563 language_settings::SoftWrap::None => SoftWrap::None,
10564 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10565 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10566 language_settings::SoftWrap::PreferredLineLength => {
10567 SoftWrap::Column(settings.preferred_line_length)
10568 }
10569 language_settings::SoftWrap::Bounded => {
10570 SoftWrap::Bounded(settings.preferred_line_length)
10571 }
10572 }
10573 }
10574
10575 pub fn set_soft_wrap_mode(
10576 &mut self,
10577 mode: language_settings::SoftWrap,
10578 cx: &mut ViewContext<Self>,
10579 ) {
10580 self.soft_wrap_mode_override = Some(mode);
10581 cx.notify();
10582 }
10583
10584 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10585 let rem_size = cx.rem_size();
10586 self.display_map.update(cx, |map, cx| {
10587 map.set_font(
10588 style.text.font(),
10589 style.text.font_size.to_pixels(rem_size),
10590 cx,
10591 )
10592 });
10593 self.style = Some(style);
10594 }
10595
10596 pub fn style(&self) -> Option<&EditorStyle> {
10597 self.style.as_ref()
10598 }
10599
10600 // Called by the element. This method is not designed to be called outside of the editor
10601 // element's layout code because it does not notify when rewrapping is computed synchronously.
10602 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10603 self.display_map
10604 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10605 }
10606
10607 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10608 if self.soft_wrap_mode_override.is_some() {
10609 self.soft_wrap_mode_override.take();
10610 } else {
10611 let soft_wrap = match self.soft_wrap_mode(cx) {
10612 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10613 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
10614 language_settings::SoftWrap::PreferLine
10615 }
10616 };
10617 self.soft_wrap_mode_override = Some(soft_wrap);
10618 }
10619 cx.notify();
10620 }
10621
10622 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10623 let Some(workspace) = self.workspace() else {
10624 return;
10625 };
10626 let fs = workspace.read(cx).app_state().fs.clone();
10627 let current_show = TabBarSettings::get_global(cx).show;
10628 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10629 setting.show = Some(!current_show);
10630 });
10631 }
10632
10633 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10634 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10635 self.buffer
10636 .read(cx)
10637 .settings_at(0, cx)
10638 .indent_guides
10639 .enabled
10640 });
10641 self.show_indent_guides = Some(!currently_enabled);
10642 cx.notify();
10643 }
10644
10645 fn should_show_indent_guides(&self) -> Option<bool> {
10646 self.show_indent_guides
10647 }
10648
10649 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10650 let mut editor_settings = EditorSettings::get_global(cx).clone();
10651 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10652 EditorSettings::override_global(editor_settings, cx);
10653 }
10654
10655 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
10656 self.use_relative_line_numbers
10657 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
10658 }
10659
10660 pub fn toggle_relative_line_numbers(
10661 &mut self,
10662 _: &ToggleRelativeLineNumbers,
10663 cx: &mut ViewContext<Self>,
10664 ) {
10665 let is_relative = self.should_use_relative_line_numbers(cx);
10666 self.set_relative_line_number(Some(!is_relative), cx)
10667 }
10668
10669 pub fn set_relative_line_number(
10670 &mut self,
10671 is_relative: Option<bool>,
10672 cx: &mut ViewContext<Self>,
10673 ) {
10674 self.use_relative_line_numbers = is_relative;
10675 cx.notify();
10676 }
10677
10678 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10679 self.show_gutter = show_gutter;
10680 cx.notify();
10681 }
10682
10683 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10684 self.show_line_numbers = Some(show_line_numbers);
10685 cx.notify();
10686 }
10687
10688 pub fn set_show_git_diff_gutter(
10689 &mut self,
10690 show_git_diff_gutter: bool,
10691 cx: &mut ViewContext<Self>,
10692 ) {
10693 self.show_git_diff_gutter = Some(show_git_diff_gutter);
10694 cx.notify();
10695 }
10696
10697 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10698 self.show_code_actions = Some(show_code_actions);
10699 cx.notify();
10700 }
10701
10702 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10703 self.show_runnables = Some(show_runnables);
10704 cx.notify();
10705 }
10706
10707 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
10708 if self.display_map.read(cx).masked != masked {
10709 self.display_map.update(cx, |map, _| map.masked = masked);
10710 }
10711 cx.notify()
10712 }
10713
10714 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10715 self.show_wrap_guides = Some(show_wrap_guides);
10716 cx.notify();
10717 }
10718
10719 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10720 self.show_indent_guides = Some(show_indent_guides);
10721 cx.notify();
10722 }
10723
10724 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10725 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10726 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10727 if let Some(dir) = file.abs_path(cx).parent() {
10728 return Some(dir.to_owned());
10729 }
10730 }
10731
10732 if let Some(project_path) = buffer.read(cx).project_path(cx) {
10733 return Some(project_path.path.to_path_buf());
10734 }
10735 }
10736
10737 None
10738 }
10739
10740 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10741 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10742 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10743 cx.reveal_path(&file.abs_path(cx));
10744 }
10745 }
10746 }
10747
10748 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10749 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10750 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10751 if let Some(path) = file.abs_path(cx).to_str() {
10752 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10753 }
10754 }
10755 }
10756 }
10757
10758 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10759 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10760 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10761 if let Some(path) = file.path().to_str() {
10762 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10763 }
10764 }
10765 }
10766 }
10767
10768 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10769 self.show_git_blame_gutter = !self.show_git_blame_gutter;
10770
10771 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10772 self.start_git_blame(true, cx);
10773 }
10774
10775 cx.notify();
10776 }
10777
10778 pub fn toggle_git_blame_inline(
10779 &mut self,
10780 _: &ToggleGitBlameInline,
10781 cx: &mut ViewContext<Self>,
10782 ) {
10783 self.toggle_git_blame_inline_internal(true, cx);
10784 cx.notify();
10785 }
10786
10787 pub fn git_blame_inline_enabled(&self) -> bool {
10788 self.git_blame_inline_enabled
10789 }
10790
10791 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10792 self.show_selection_menu = self
10793 .show_selection_menu
10794 .map(|show_selections_menu| !show_selections_menu)
10795 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10796
10797 cx.notify();
10798 }
10799
10800 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10801 self.show_selection_menu
10802 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10803 }
10804
10805 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10806 if let Some(project) = self.project.as_ref() {
10807 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10808 return;
10809 };
10810
10811 if buffer.read(cx).file().is_none() {
10812 return;
10813 }
10814
10815 let focused = self.focus_handle(cx).contains_focused(cx);
10816
10817 let project = project.clone();
10818 let blame =
10819 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10820 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10821 self.blame = Some(blame);
10822 }
10823 }
10824
10825 fn toggle_git_blame_inline_internal(
10826 &mut self,
10827 user_triggered: bool,
10828 cx: &mut ViewContext<Self>,
10829 ) {
10830 if self.git_blame_inline_enabled {
10831 self.git_blame_inline_enabled = false;
10832 self.show_git_blame_inline = false;
10833 self.show_git_blame_inline_delay_task.take();
10834 } else {
10835 self.git_blame_inline_enabled = true;
10836 self.start_git_blame_inline(user_triggered, cx);
10837 }
10838
10839 cx.notify();
10840 }
10841
10842 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10843 self.start_git_blame(user_triggered, cx);
10844
10845 if ProjectSettings::get_global(cx)
10846 .git
10847 .inline_blame_delay()
10848 .is_some()
10849 {
10850 self.start_inline_blame_timer(cx);
10851 } else {
10852 self.show_git_blame_inline = true
10853 }
10854 }
10855
10856 pub fn blame(&self) -> Option<&Model<GitBlame>> {
10857 self.blame.as_ref()
10858 }
10859
10860 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10861 self.show_git_blame_gutter && self.has_blame_entries(cx)
10862 }
10863
10864 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10865 self.show_git_blame_inline
10866 && self.focus_handle.is_focused(cx)
10867 && !self.newest_selection_head_on_empty_line(cx)
10868 && self.has_blame_entries(cx)
10869 }
10870
10871 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10872 self.blame()
10873 .map_or(false, |blame| blame.read(cx).has_generated_entries())
10874 }
10875
10876 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10877 let cursor_anchor = self.selections.newest_anchor().head();
10878
10879 let snapshot = self.buffer.read(cx).snapshot(cx);
10880 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10881
10882 snapshot.line_len(buffer_row) == 0
10883 }
10884
10885 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10886 let (path, selection, repo) = maybe!({
10887 let project_handle = self.project.as_ref()?.clone();
10888 let project = project_handle.read(cx);
10889
10890 let selection = self.selections.newest::<Point>(cx);
10891 let selection_range = selection.range();
10892
10893 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10894 (buffer, selection_range.start.row..selection_range.end.row)
10895 } else {
10896 let buffer_ranges = self
10897 .buffer()
10898 .read(cx)
10899 .range_to_buffer_ranges(selection_range, cx);
10900
10901 let (buffer, range, _) = if selection.reversed {
10902 buffer_ranges.first()
10903 } else {
10904 buffer_ranges.last()
10905 }?;
10906
10907 let snapshot = buffer.read(cx).snapshot();
10908 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10909 ..text::ToPoint::to_point(&range.end, &snapshot).row;
10910 (buffer.clone(), selection)
10911 };
10912
10913 let path = buffer
10914 .read(cx)
10915 .file()?
10916 .as_local()?
10917 .path()
10918 .to_str()?
10919 .to_string();
10920 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10921 Some((path, selection, repo))
10922 })
10923 .ok_or_else(|| anyhow!("unable to open git repository"))?;
10924
10925 const REMOTE_NAME: &str = "origin";
10926 let origin_url = repo
10927 .remote_url(REMOTE_NAME)
10928 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10929 let sha = repo
10930 .head_sha()
10931 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10932
10933 let (provider, remote) =
10934 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10935 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10936
10937 Ok(provider.build_permalink(
10938 remote,
10939 BuildPermalinkParams {
10940 sha: &sha,
10941 path: &path,
10942 selection: Some(selection),
10943 },
10944 ))
10945 }
10946
10947 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10948 let permalink = self.get_permalink_to_line(cx);
10949
10950 match permalink {
10951 Ok(permalink) => {
10952 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
10953 }
10954 Err(err) => {
10955 let message = format!("Failed to copy permalink: {err}");
10956
10957 Err::<(), anyhow::Error>(err).log_err();
10958
10959 if let Some(workspace) = self.workspace() {
10960 workspace.update(cx, |workspace, cx| {
10961 struct CopyPermalinkToLine;
10962
10963 workspace.show_toast(
10964 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10965 cx,
10966 )
10967 })
10968 }
10969 }
10970 }
10971 }
10972
10973 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
10974 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10975 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10976 if let Some(path) = file.path().to_str() {
10977 let selection = self.selections.newest::<Point>(cx).start.row + 1;
10978 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
10979 }
10980 }
10981 }
10982 }
10983
10984 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10985 let permalink = self.get_permalink_to_line(cx);
10986
10987 match permalink {
10988 Ok(permalink) => {
10989 cx.open_url(permalink.as_ref());
10990 }
10991 Err(err) => {
10992 let message = format!("Failed to open permalink: {err}");
10993
10994 Err::<(), anyhow::Error>(err).log_err();
10995
10996 if let Some(workspace) = self.workspace() {
10997 workspace.update(cx, |workspace, cx| {
10998 struct OpenPermalinkToLine;
10999
11000 workspace.show_toast(
11001 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11002 cx,
11003 )
11004 })
11005 }
11006 }
11007 }
11008 }
11009
11010 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
11011 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
11012 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
11013 pub fn highlight_rows<T: 'static>(
11014 &mut self,
11015 rows: RangeInclusive<Anchor>,
11016 color: Option<Hsla>,
11017 should_autoscroll: bool,
11018 cx: &mut ViewContext<Self>,
11019 ) {
11020 let snapshot = self.buffer().read(cx).snapshot(cx);
11021 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11022 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
11023 highlight
11024 .range
11025 .start()
11026 .cmp(&rows.start(), &snapshot)
11027 .then(highlight.range.end().cmp(&rows.end(), &snapshot))
11028 });
11029 match (color, existing_highlight_index) {
11030 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
11031 ix,
11032 RowHighlight {
11033 index: post_inc(&mut self.highlight_order),
11034 range: rows,
11035 should_autoscroll,
11036 color,
11037 },
11038 ),
11039 (None, Ok(i)) => {
11040 row_highlights.remove(i);
11041 }
11042 }
11043 }
11044
11045 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11046 pub fn clear_row_highlights<T: 'static>(&mut self) {
11047 self.highlighted_rows.remove(&TypeId::of::<T>());
11048 }
11049
11050 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11051 pub fn highlighted_rows<T: 'static>(
11052 &self,
11053 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
11054 Some(
11055 self.highlighted_rows
11056 .get(&TypeId::of::<T>())?
11057 .iter()
11058 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
11059 )
11060 }
11061
11062 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11063 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11064 /// Allows to ignore certain kinds of highlights.
11065 pub fn highlighted_display_rows(
11066 &mut self,
11067 cx: &mut WindowContext,
11068 ) -> BTreeMap<DisplayRow, Hsla> {
11069 let snapshot = self.snapshot(cx);
11070 let mut used_highlight_orders = HashMap::default();
11071 self.highlighted_rows
11072 .iter()
11073 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11074 .fold(
11075 BTreeMap::<DisplayRow, Hsla>::new(),
11076 |mut unique_rows, highlight| {
11077 let start_row = highlight.range.start().to_display_point(&snapshot).row();
11078 let end_row = highlight.range.end().to_display_point(&snapshot).row();
11079 for row in start_row.0..=end_row.0 {
11080 let used_index =
11081 used_highlight_orders.entry(row).or_insert(highlight.index);
11082 if highlight.index >= *used_index {
11083 *used_index = highlight.index;
11084 match highlight.color {
11085 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
11086 None => unique_rows.remove(&DisplayRow(row)),
11087 };
11088 }
11089 }
11090 unique_rows
11091 },
11092 )
11093 }
11094
11095 pub fn highlighted_display_row_for_autoscroll(
11096 &self,
11097 snapshot: &DisplaySnapshot,
11098 ) -> Option<DisplayRow> {
11099 self.highlighted_rows
11100 .values()
11101 .flat_map(|highlighted_rows| highlighted_rows.iter())
11102 .filter_map(|highlight| {
11103 if highlight.color.is_none() || !highlight.should_autoscroll {
11104 return None;
11105 }
11106 Some(highlight.range.start().to_display_point(&snapshot).row())
11107 })
11108 .min()
11109 }
11110
11111 pub fn set_search_within_ranges(
11112 &mut self,
11113 ranges: &[Range<Anchor>],
11114 cx: &mut ViewContext<Self>,
11115 ) {
11116 self.highlight_background::<SearchWithinRange>(
11117 ranges,
11118 |colors| colors.editor_document_highlight_read_background,
11119 cx,
11120 )
11121 }
11122
11123 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11124 self.breadcrumb_header = Some(new_header);
11125 }
11126
11127 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11128 self.clear_background_highlights::<SearchWithinRange>(cx);
11129 }
11130
11131 pub fn highlight_background<T: 'static>(
11132 &mut self,
11133 ranges: &[Range<Anchor>],
11134 color_fetcher: fn(&ThemeColors) -> Hsla,
11135 cx: &mut ViewContext<Self>,
11136 ) {
11137 self.background_highlights
11138 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11139 self.scrollbar_marker_state.dirty = true;
11140 cx.notify();
11141 }
11142
11143 pub fn clear_background_highlights<T: 'static>(
11144 &mut self,
11145 cx: &mut ViewContext<Self>,
11146 ) -> Option<BackgroundHighlight> {
11147 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11148 if !text_highlights.1.is_empty() {
11149 self.scrollbar_marker_state.dirty = true;
11150 cx.notify();
11151 }
11152 Some(text_highlights)
11153 }
11154
11155 pub fn highlight_gutter<T: 'static>(
11156 &mut self,
11157 ranges: &[Range<Anchor>],
11158 color_fetcher: fn(&AppContext) -> Hsla,
11159 cx: &mut ViewContext<Self>,
11160 ) {
11161 self.gutter_highlights
11162 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11163 cx.notify();
11164 }
11165
11166 pub fn clear_gutter_highlights<T: 'static>(
11167 &mut self,
11168 cx: &mut ViewContext<Self>,
11169 ) -> Option<GutterHighlight> {
11170 cx.notify();
11171 self.gutter_highlights.remove(&TypeId::of::<T>())
11172 }
11173
11174 #[cfg(feature = "test-support")]
11175 pub fn all_text_background_highlights(
11176 &mut self,
11177 cx: &mut ViewContext<Self>,
11178 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11179 let snapshot = self.snapshot(cx);
11180 let buffer = &snapshot.buffer_snapshot;
11181 let start = buffer.anchor_before(0);
11182 let end = buffer.anchor_after(buffer.len());
11183 let theme = cx.theme().colors();
11184 self.background_highlights_in_range(start..end, &snapshot, theme)
11185 }
11186
11187 #[cfg(feature = "test-support")]
11188 pub fn search_background_highlights(
11189 &mut self,
11190 cx: &mut ViewContext<Self>,
11191 ) -> Vec<Range<Point>> {
11192 let snapshot = self.buffer().read(cx).snapshot(cx);
11193
11194 let highlights = self
11195 .background_highlights
11196 .get(&TypeId::of::<items::BufferSearchHighlights>());
11197
11198 if let Some((_color, ranges)) = highlights {
11199 ranges
11200 .iter()
11201 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11202 .collect_vec()
11203 } else {
11204 vec![]
11205 }
11206 }
11207
11208 fn document_highlights_for_position<'a>(
11209 &'a self,
11210 position: Anchor,
11211 buffer: &'a MultiBufferSnapshot,
11212 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
11213 let read_highlights = self
11214 .background_highlights
11215 .get(&TypeId::of::<DocumentHighlightRead>())
11216 .map(|h| &h.1);
11217 let write_highlights = self
11218 .background_highlights
11219 .get(&TypeId::of::<DocumentHighlightWrite>())
11220 .map(|h| &h.1);
11221 let left_position = position.bias_left(buffer);
11222 let right_position = position.bias_right(buffer);
11223 read_highlights
11224 .into_iter()
11225 .chain(write_highlights)
11226 .flat_map(move |ranges| {
11227 let start_ix = match ranges.binary_search_by(|probe| {
11228 let cmp = probe.end.cmp(&left_position, buffer);
11229 if cmp.is_ge() {
11230 Ordering::Greater
11231 } else {
11232 Ordering::Less
11233 }
11234 }) {
11235 Ok(i) | Err(i) => i,
11236 };
11237
11238 ranges[start_ix..]
11239 .iter()
11240 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11241 })
11242 }
11243
11244 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11245 self.background_highlights
11246 .get(&TypeId::of::<T>())
11247 .map_or(false, |(_, highlights)| !highlights.is_empty())
11248 }
11249
11250 pub fn background_highlights_in_range(
11251 &self,
11252 search_range: Range<Anchor>,
11253 display_snapshot: &DisplaySnapshot,
11254 theme: &ThemeColors,
11255 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11256 let mut results = Vec::new();
11257 for (color_fetcher, ranges) in self.background_highlights.values() {
11258 let color = color_fetcher(theme);
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 for range in &ranges[start_ix..] {
11272 if range
11273 .start
11274 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11275 .is_ge()
11276 {
11277 break;
11278 }
11279
11280 let start = range.start.to_display_point(&display_snapshot);
11281 let end = range.end.to_display_point(&display_snapshot);
11282 results.push((start..end, color))
11283 }
11284 }
11285 results
11286 }
11287
11288 pub fn background_highlight_row_ranges<T: 'static>(
11289 &self,
11290 search_range: Range<Anchor>,
11291 display_snapshot: &DisplaySnapshot,
11292 count: usize,
11293 ) -> Vec<RangeInclusive<DisplayPoint>> {
11294 let mut results = Vec::new();
11295 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11296 return vec![];
11297 };
11298
11299 let start_ix = match ranges.binary_search_by(|probe| {
11300 let cmp = probe
11301 .end
11302 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11303 if cmp.is_gt() {
11304 Ordering::Greater
11305 } else {
11306 Ordering::Less
11307 }
11308 }) {
11309 Ok(i) | Err(i) => i,
11310 };
11311 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11312 if let (Some(start_display), Some(end_display)) = (start, end) {
11313 results.push(
11314 start_display.to_display_point(display_snapshot)
11315 ..=end_display.to_display_point(display_snapshot),
11316 );
11317 }
11318 };
11319 let mut start_row: Option<Point> = None;
11320 let mut end_row: Option<Point> = None;
11321 if ranges.len() > count {
11322 return Vec::new();
11323 }
11324 for range in &ranges[start_ix..] {
11325 if range
11326 .start
11327 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11328 .is_ge()
11329 {
11330 break;
11331 }
11332 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11333 if let Some(current_row) = &end_row {
11334 if end.row == current_row.row {
11335 continue;
11336 }
11337 }
11338 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11339 if start_row.is_none() {
11340 assert_eq!(end_row, None);
11341 start_row = Some(start);
11342 end_row = Some(end);
11343 continue;
11344 }
11345 if let Some(current_end) = end_row.as_mut() {
11346 if start.row > current_end.row + 1 {
11347 push_region(start_row, end_row);
11348 start_row = Some(start);
11349 end_row = Some(end);
11350 } else {
11351 // Merge two hunks.
11352 *current_end = end;
11353 }
11354 } else {
11355 unreachable!();
11356 }
11357 }
11358 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11359 push_region(start_row, end_row);
11360 results
11361 }
11362
11363 pub fn gutter_highlights_in_range(
11364 &self,
11365 search_range: Range<Anchor>,
11366 display_snapshot: &DisplaySnapshot,
11367 cx: &AppContext,
11368 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11369 let mut results = Vec::new();
11370 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11371 let color = color_fetcher(cx);
11372 let start_ix = match ranges.binary_search_by(|probe| {
11373 let cmp = probe
11374 .end
11375 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11376 if cmp.is_gt() {
11377 Ordering::Greater
11378 } else {
11379 Ordering::Less
11380 }
11381 }) {
11382 Ok(i) | Err(i) => i,
11383 };
11384 for range in &ranges[start_ix..] {
11385 if range
11386 .start
11387 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11388 .is_ge()
11389 {
11390 break;
11391 }
11392
11393 let start = range.start.to_display_point(&display_snapshot);
11394 let end = range.end.to_display_point(&display_snapshot);
11395 results.push((start..end, color))
11396 }
11397 }
11398 results
11399 }
11400
11401 /// Get the text ranges corresponding to the redaction query
11402 pub fn redacted_ranges(
11403 &self,
11404 search_range: Range<Anchor>,
11405 display_snapshot: &DisplaySnapshot,
11406 cx: &WindowContext,
11407 ) -> Vec<Range<DisplayPoint>> {
11408 display_snapshot
11409 .buffer_snapshot
11410 .redacted_ranges(search_range, |file| {
11411 if let Some(file) = file {
11412 file.is_private()
11413 && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
11414 } else {
11415 false
11416 }
11417 })
11418 .map(|range| {
11419 range.start.to_display_point(display_snapshot)
11420 ..range.end.to_display_point(display_snapshot)
11421 })
11422 .collect()
11423 }
11424
11425 pub fn highlight_text<T: 'static>(
11426 &mut self,
11427 ranges: Vec<Range<Anchor>>,
11428 style: HighlightStyle,
11429 cx: &mut ViewContext<Self>,
11430 ) {
11431 self.display_map.update(cx, |map, _| {
11432 map.highlight_text(TypeId::of::<T>(), ranges, style)
11433 });
11434 cx.notify();
11435 }
11436
11437 pub(crate) fn highlight_inlays<T: 'static>(
11438 &mut self,
11439 highlights: Vec<InlayHighlight>,
11440 style: HighlightStyle,
11441 cx: &mut ViewContext<Self>,
11442 ) {
11443 self.display_map.update(cx, |map, _| {
11444 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11445 });
11446 cx.notify();
11447 }
11448
11449 pub fn text_highlights<'a, T: 'static>(
11450 &'a self,
11451 cx: &'a AppContext,
11452 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11453 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11454 }
11455
11456 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11457 let cleared = self
11458 .display_map
11459 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11460 if cleared {
11461 cx.notify();
11462 }
11463 }
11464
11465 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11466 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11467 && self.focus_handle.is_focused(cx)
11468 }
11469
11470 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11471 self.show_cursor_when_unfocused = is_enabled;
11472 cx.notify();
11473 }
11474
11475 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11476 cx.notify();
11477 }
11478
11479 fn on_buffer_event(
11480 &mut self,
11481 multibuffer: Model<MultiBuffer>,
11482 event: &multi_buffer::Event,
11483 cx: &mut ViewContext<Self>,
11484 ) {
11485 match event {
11486 multi_buffer::Event::Edited {
11487 singleton_buffer_edited,
11488 } => {
11489 self.scrollbar_marker_state.dirty = true;
11490 self.active_indent_guides_state.dirty = true;
11491 self.refresh_active_diagnostics(cx);
11492 self.refresh_code_actions(cx);
11493 if self.has_active_inline_completion(cx) {
11494 self.update_visible_inline_completion(cx);
11495 }
11496 cx.emit(EditorEvent::BufferEdited);
11497 cx.emit(SearchEvent::MatchesInvalidated);
11498 if *singleton_buffer_edited {
11499 if let Some(project) = &self.project {
11500 let project = project.read(cx);
11501 #[allow(clippy::mutable_key_type)]
11502 let languages_affected = multibuffer
11503 .read(cx)
11504 .all_buffers()
11505 .into_iter()
11506 .filter_map(|buffer| {
11507 let buffer = buffer.read(cx);
11508 let language = buffer.language()?;
11509 if project.is_local_or_ssh()
11510 && project.language_servers_for_buffer(buffer, cx).count() == 0
11511 {
11512 None
11513 } else {
11514 Some(language)
11515 }
11516 })
11517 .cloned()
11518 .collect::<HashSet<_>>();
11519 if !languages_affected.is_empty() {
11520 self.refresh_inlay_hints(
11521 InlayHintRefreshReason::BufferEdited(languages_affected),
11522 cx,
11523 );
11524 }
11525 }
11526 }
11527
11528 let Some(project) = &self.project else { return };
11529 let telemetry = project.read(cx).client().telemetry().clone();
11530 refresh_linked_ranges(self, cx);
11531 telemetry.log_edit_event("editor");
11532 }
11533 multi_buffer::Event::ExcerptsAdded {
11534 buffer,
11535 predecessor,
11536 excerpts,
11537 } => {
11538 self.tasks_update_task = Some(self.refresh_runnables(cx));
11539 cx.emit(EditorEvent::ExcerptsAdded {
11540 buffer: buffer.clone(),
11541 predecessor: *predecessor,
11542 excerpts: excerpts.clone(),
11543 });
11544 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11545 }
11546 multi_buffer::Event::ExcerptsRemoved { ids } => {
11547 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11548 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11549 }
11550 multi_buffer::Event::ExcerptsEdited { ids } => {
11551 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11552 }
11553 multi_buffer::Event::ExcerptsExpanded { ids } => {
11554 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11555 }
11556 multi_buffer::Event::Reparsed(buffer_id) => {
11557 self.tasks_update_task = Some(self.refresh_runnables(cx));
11558
11559 cx.emit(EditorEvent::Reparsed(*buffer_id));
11560 }
11561 multi_buffer::Event::LanguageChanged(buffer_id) => {
11562 linked_editing_ranges::refresh_linked_ranges(self, cx);
11563 cx.emit(EditorEvent::Reparsed(*buffer_id));
11564 cx.notify();
11565 }
11566 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11567 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11568 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11569 cx.emit(EditorEvent::TitleChanged)
11570 }
11571 multi_buffer::Event::DiffBaseChanged => {
11572 self.scrollbar_marker_state.dirty = true;
11573 cx.emit(EditorEvent::DiffBaseChanged);
11574 cx.notify();
11575 }
11576 multi_buffer::Event::DiffUpdated { buffer } => {
11577 self.sync_expanded_diff_hunks(buffer.clone(), cx);
11578 cx.notify();
11579 }
11580 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11581 multi_buffer::Event::DiagnosticsUpdated => {
11582 self.refresh_active_diagnostics(cx);
11583 self.scrollbar_marker_state.dirty = true;
11584 cx.notify();
11585 }
11586 _ => {}
11587 };
11588 }
11589
11590 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11591 cx.notify();
11592 }
11593
11594 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11595 self.tasks_update_task = Some(self.refresh_runnables(cx));
11596 self.refresh_inline_completion(true, false, cx);
11597 self.refresh_inlay_hints(
11598 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11599 self.selections.newest_anchor().head(),
11600 &self.buffer.read(cx).snapshot(cx),
11601 cx,
11602 )),
11603 cx,
11604 );
11605 let editor_settings = EditorSettings::get_global(cx);
11606 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11607 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11608
11609 let project_settings = ProjectSettings::get_global(cx);
11610 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11611
11612 if self.mode == EditorMode::Full {
11613 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11614 if self.git_blame_inline_enabled != inline_blame_enabled {
11615 self.toggle_git_blame_inline_internal(false, cx);
11616 }
11617 }
11618
11619 cx.notify();
11620 }
11621
11622 pub fn set_searchable(&mut self, searchable: bool) {
11623 self.searchable = searchable;
11624 }
11625
11626 pub fn searchable(&self) -> bool {
11627 self.searchable
11628 }
11629
11630 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11631 self.open_excerpts_common(true, cx)
11632 }
11633
11634 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11635 self.open_excerpts_common(false, cx)
11636 }
11637
11638 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11639 let buffer = self.buffer.read(cx);
11640 if buffer.is_singleton() {
11641 cx.propagate();
11642 return;
11643 }
11644
11645 let Some(workspace) = self.workspace() else {
11646 cx.propagate();
11647 return;
11648 };
11649
11650 let mut new_selections_by_buffer = HashMap::default();
11651 for selection in self.selections.all::<usize>(cx) {
11652 for (buffer, mut range, _) in
11653 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11654 {
11655 if selection.reversed {
11656 mem::swap(&mut range.start, &mut range.end);
11657 }
11658 new_selections_by_buffer
11659 .entry(buffer)
11660 .or_insert(Vec::new())
11661 .push(range)
11662 }
11663 }
11664
11665 // We defer the pane interaction because we ourselves are a workspace item
11666 // and activating a new item causes the pane to call a method on us reentrantly,
11667 // which panics if we're on the stack.
11668 cx.window_context().defer(move |cx| {
11669 workspace.update(cx, |workspace, cx| {
11670 let pane = if split {
11671 workspace.adjacent_pane(cx)
11672 } else {
11673 workspace.active_pane().clone()
11674 };
11675
11676 for (buffer, ranges) in new_selections_by_buffer {
11677 let editor =
11678 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
11679 editor.update(cx, |editor, cx| {
11680 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11681 s.select_ranges(ranges);
11682 });
11683 });
11684 }
11685 })
11686 });
11687 }
11688
11689 fn jump(
11690 &mut self,
11691 path: ProjectPath,
11692 position: Point,
11693 anchor: language::Anchor,
11694 offset_from_top: u32,
11695 cx: &mut ViewContext<Self>,
11696 ) {
11697 let workspace = self.workspace();
11698 cx.spawn(|_, mut cx| async move {
11699 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11700 let editor = workspace.update(&mut cx, |workspace, cx| {
11701 // Reset the preview item id before opening the new item
11702 workspace.active_pane().update(cx, |pane, cx| {
11703 pane.set_preview_item_id(None, cx);
11704 });
11705 workspace.open_path_preview(path, None, true, true, cx)
11706 })?;
11707 let editor = editor
11708 .await?
11709 .downcast::<Editor>()
11710 .ok_or_else(|| anyhow!("opened item was not an editor"))?
11711 .downgrade();
11712 editor.update(&mut cx, |editor, cx| {
11713 let buffer = editor
11714 .buffer()
11715 .read(cx)
11716 .as_singleton()
11717 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11718 let buffer = buffer.read(cx);
11719 let cursor = if buffer.can_resolve(&anchor) {
11720 language::ToPoint::to_point(&anchor, buffer)
11721 } else {
11722 buffer.clip_point(position, Bias::Left)
11723 };
11724
11725 let nav_history = editor.nav_history.take();
11726 editor.change_selections(
11727 Some(Autoscroll::top_relative(offset_from_top as usize)),
11728 cx,
11729 |s| {
11730 s.select_ranges([cursor..cursor]);
11731 },
11732 );
11733 editor.nav_history = nav_history;
11734
11735 anyhow::Ok(())
11736 })??;
11737
11738 anyhow::Ok(())
11739 })
11740 .detach_and_log_err(cx);
11741 }
11742
11743 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11744 let snapshot = self.buffer.read(cx).read(cx);
11745 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11746 Some(
11747 ranges
11748 .iter()
11749 .map(move |range| {
11750 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11751 })
11752 .collect(),
11753 )
11754 }
11755
11756 fn selection_replacement_ranges(
11757 &self,
11758 range: Range<OffsetUtf16>,
11759 cx: &AppContext,
11760 ) -> Vec<Range<OffsetUtf16>> {
11761 let selections = self.selections.all::<OffsetUtf16>(cx);
11762 let newest_selection = selections
11763 .iter()
11764 .max_by_key(|selection| selection.id)
11765 .unwrap();
11766 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11767 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11768 let snapshot = self.buffer.read(cx).read(cx);
11769 selections
11770 .into_iter()
11771 .map(|mut selection| {
11772 selection.start.0 =
11773 (selection.start.0 as isize).saturating_add(start_delta) as usize;
11774 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11775 snapshot.clip_offset_utf16(selection.start, Bias::Left)
11776 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11777 })
11778 .collect()
11779 }
11780
11781 fn report_editor_event(
11782 &self,
11783 operation: &'static str,
11784 file_extension: Option<String>,
11785 cx: &AppContext,
11786 ) {
11787 if cfg!(any(test, feature = "test-support")) {
11788 return;
11789 }
11790
11791 let Some(project) = &self.project else { return };
11792
11793 // If None, we are in a file without an extension
11794 let file = self
11795 .buffer
11796 .read(cx)
11797 .as_singleton()
11798 .and_then(|b| b.read(cx).file());
11799 let file_extension = file_extension.or(file
11800 .as_ref()
11801 .and_then(|file| Path::new(file.file_name(cx)).extension())
11802 .and_then(|e| e.to_str())
11803 .map(|a| a.to_string()));
11804
11805 let vim_mode = cx
11806 .global::<SettingsStore>()
11807 .raw_user_settings()
11808 .get("vim_mode")
11809 == Some(&serde_json::Value::Bool(true));
11810
11811 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11812 == language::language_settings::InlineCompletionProvider::Copilot;
11813 let copilot_enabled_for_language = self
11814 .buffer
11815 .read(cx)
11816 .settings_at(0, cx)
11817 .show_inline_completions;
11818
11819 let telemetry = project.read(cx).client().telemetry().clone();
11820 telemetry.report_editor_event(
11821 file_extension,
11822 vim_mode,
11823 operation,
11824 copilot_enabled,
11825 copilot_enabled_for_language,
11826 )
11827 }
11828
11829 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11830 /// with each line being an array of {text, highlight} objects.
11831 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11832 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11833 return;
11834 };
11835
11836 #[derive(Serialize)]
11837 struct Chunk<'a> {
11838 text: String,
11839 highlight: Option<&'a str>,
11840 }
11841
11842 let snapshot = buffer.read(cx).snapshot();
11843 let range = self
11844 .selected_text_range(false, cx)
11845 .and_then(|selection| {
11846 if selection.range.is_empty() {
11847 None
11848 } else {
11849 Some(selection.range)
11850 }
11851 })
11852 .unwrap_or_else(|| 0..snapshot.len());
11853
11854 let chunks = snapshot.chunks(range, true);
11855 let mut lines = Vec::new();
11856 let mut line: VecDeque<Chunk> = VecDeque::new();
11857
11858 let Some(style) = self.style.as_ref() else {
11859 return;
11860 };
11861
11862 for chunk in chunks {
11863 let highlight = chunk
11864 .syntax_highlight_id
11865 .and_then(|id| id.name(&style.syntax));
11866 let mut chunk_lines = chunk.text.split('\n').peekable();
11867 while let Some(text) = chunk_lines.next() {
11868 let mut merged_with_last_token = false;
11869 if let Some(last_token) = line.back_mut() {
11870 if last_token.highlight == highlight {
11871 last_token.text.push_str(text);
11872 merged_with_last_token = true;
11873 }
11874 }
11875
11876 if !merged_with_last_token {
11877 line.push_back(Chunk {
11878 text: text.into(),
11879 highlight,
11880 });
11881 }
11882
11883 if chunk_lines.peek().is_some() {
11884 if line.len() > 1 && line.front().unwrap().text.is_empty() {
11885 line.pop_front();
11886 }
11887 if line.len() > 1 && line.back().unwrap().text.is_empty() {
11888 line.pop_back();
11889 }
11890
11891 lines.push(mem::take(&mut line));
11892 }
11893 }
11894 }
11895
11896 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11897 return;
11898 };
11899 cx.write_to_clipboard(ClipboardItem::new_string(lines));
11900 }
11901
11902 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11903 &self.inlay_hint_cache
11904 }
11905
11906 pub fn replay_insert_event(
11907 &mut self,
11908 text: &str,
11909 relative_utf16_range: Option<Range<isize>>,
11910 cx: &mut ViewContext<Self>,
11911 ) {
11912 if !self.input_enabled {
11913 cx.emit(EditorEvent::InputIgnored { text: text.into() });
11914 return;
11915 }
11916 if let Some(relative_utf16_range) = relative_utf16_range {
11917 let selections = self.selections.all::<OffsetUtf16>(cx);
11918 self.change_selections(None, cx, |s| {
11919 let new_ranges = selections.into_iter().map(|range| {
11920 let start = OffsetUtf16(
11921 range
11922 .head()
11923 .0
11924 .saturating_add_signed(relative_utf16_range.start),
11925 );
11926 let end = OffsetUtf16(
11927 range
11928 .head()
11929 .0
11930 .saturating_add_signed(relative_utf16_range.end),
11931 );
11932 start..end
11933 });
11934 s.select_ranges(new_ranges);
11935 });
11936 }
11937
11938 self.handle_input(text, cx);
11939 }
11940
11941 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11942 let Some(project) = self.project.as_ref() else {
11943 return false;
11944 };
11945 let project = project.read(cx);
11946
11947 let mut supports = false;
11948 self.buffer().read(cx).for_each_buffer(|buffer| {
11949 if !supports {
11950 supports = project
11951 .language_servers_for_buffer(buffer.read(cx), cx)
11952 .any(
11953 |(_, server)| match server.capabilities().inlay_hint_provider {
11954 Some(lsp::OneOf::Left(enabled)) => enabled,
11955 Some(lsp::OneOf::Right(_)) => true,
11956 None => false,
11957 },
11958 )
11959 }
11960 });
11961 supports
11962 }
11963
11964 pub fn focus(&self, cx: &mut WindowContext) {
11965 cx.focus(&self.focus_handle)
11966 }
11967
11968 pub fn is_focused(&self, cx: &WindowContext) -> bool {
11969 self.focus_handle.is_focused(cx)
11970 }
11971
11972 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11973 cx.emit(EditorEvent::Focused);
11974
11975 if let Some(descendant) = self
11976 .last_focused_descendant
11977 .take()
11978 .and_then(|descendant| descendant.upgrade())
11979 {
11980 cx.focus(&descendant);
11981 } else {
11982 if let Some(blame) = self.blame.as_ref() {
11983 blame.update(cx, GitBlame::focus)
11984 }
11985
11986 self.blink_manager.update(cx, BlinkManager::enable);
11987 self.show_cursor_names(cx);
11988 self.buffer.update(cx, |buffer, cx| {
11989 buffer.finalize_last_transaction(cx);
11990 if self.leader_peer_id.is_none() {
11991 buffer.set_active_selections(
11992 &self.selections.disjoint_anchors(),
11993 self.selections.line_mode,
11994 self.cursor_shape,
11995 cx,
11996 );
11997 }
11998 });
11999 }
12000 }
12001
12002 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12003 cx.emit(EditorEvent::FocusedIn)
12004 }
12005
12006 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12007 if event.blurred != self.focus_handle {
12008 self.last_focused_descendant = Some(event.blurred);
12009 }
12010 }
12011
12012 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12013 self.blink_manager.update(cx, BlinkManager::disable);
12014 self.buffer
12015 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12016
12017 if let Some(blame) = self.blame.as_ref() {
12018 blame.update(cx, GitBlame::blur)
12019 }
12020 if !self.hover_state.focused(cx) {
12021 hide_hover(self, cx);
12022 }
12023
12024 self.hide_context_menu(cx);
12025 cx.emit(EditorEvent::Blurred);
12026 cx.notify();
12027 }
12028
12029 pub fn register_action<A: Action>(
12030 &mut self,
12031 listener: impl Fn(&A, &mut WindowContext) + 'static,
12032 ) -> Subscription {
12033 let id = self.next_editor_action_id.post_inc();
12034 let listener = Arc::new(listener);
12035 self.editor_actions.borrow_mut().insert(
12036 id,
12037 Box::new(move |cx| {
12038 let cx = cx.window_context();
12039 let listener = listener.clone();
12040 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12041 let action = action.downcast_ref().unwrap();
12042 if phase == DispatchPhase::Bubble {
12043 listener(action, cx)
12044 }
12045 })
12046 }),
12047 );
12048
12049 let editor_actions = self.editor_actions.clone();
12050 Subscription::new(move || {
12051 editor_actions.borrow_mut().remove(&id);
12052 })
12053 }
12054
12055 pub fn file_header_size(&self) -> u32 {
12056 self.file_header_size
12057 }
12058
12059 pub fn revert(
12060 &mut self,
12061 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12062 cx: &mut ViewContext<Self>,
12063 ) {
12064 self.buffer().update(cx, |multi_buffer, cx| {
12065 for (buffer_id, changes) in revert_changes {
12066 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12067 buffer.update(cx, |buffer, cx| {
12068 buffer.edit(
12069 changes.into_iter().map(|(range, text)| {
12070 (range, text.to_string().map(Arc::<str>::from))
12071 }),
12072 None,
12073 cx,
12074 );
12075 });
12076 }
12077 }
12078 });
12079 self.change_selections(None, cx, |selections| selections.refresh());
12080 }
12081
12082 pub fn to_pixel_point(
12083 &mut self,
12084 source: multi_buffer::Anchor,
12085 editor_snapshot: &EditorSnapshot,
12086 cx: &mut ViewContext<Self>,
12087 ) -> Option<gpui::Point<Pixels>> {
12088 let source_point = source.to_display_point(editor_snapshot);
12089 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12090 }
12091
12092 pub fn display_to_pixel_point(
12093 &mut self,
12094 source: DisplayPoint,
12095 editor_snapshot: &EditorSnapshot,
12096 cx: &mut ViewContext<Self>,
12097 ) -> Option<gpui::Point<Pixels>> {
12098 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12099 let text_layout_details = self.text_layout_details(cx);
12100 let scroll_top = text_layout_details
12101 .scroll_anchor
12102 .scroll_position(editor_snapshot)
12103 .y;
12104
12105 if source.row().as_f32() < scroll_top.floor() {
12106 return None;
12107 }
12108 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12109 let source_y = line_height * (source.row().as_f32() - scroll_top);
12110 Some(gpui::Point::new(source_x, source_y))
12111 }
12112
12113 fn gutter_bounds(&self) -> Option<Bounds<Pixels>> {
12114 let bounds = self.last_bounds?;
12115 Some(element::gutter_bounds(bounds, self.gutter_dimensions))
12116 }
12117
12118 pub fn has_active_completions_menu(&self) -> bool {
12119 self.context_menu.read().as_ref().map_or(false, |menu| {
12120 menu.visible() && matches!(menu, ContextMenu::Completions(_))
12121 })
12122 }
12123
12124 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12125 self.addons
12126 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12127 }
12128
12129 pub fn unregister_addon<T: Addon>(&mut self) {
12130 self.addons.remove(&std::any::TypeId::of::<T>());
12131 }
12132
12133 pub fn addon<T: Addon>(&self) -> Option<&T> {
12134 let type_id = std::any::TypeId::of::<T>();
12135 self.addons
12136 .get(&type_id)
12137 .and_then(|item| item.to_any().downcast_ref::<T>())
12138 }
12139}
12140
12141fn hunks_for_selections(
12142 multi_buffer_snapshot: &MultiBufferSnapshot,
12143 selections: &[Selection<Anchor>],
12144) -> Vec<DiffHunk<MultiBufferRow>> {
12145 let buffer_rows_for_selections = selections.iter().map(|selection| {
12146 let head = selection.head();
12147 let tail = selection.tail();
12148 let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
12149 let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
12150 if start > end {
12151 end..start
12152 } else {
12153 start..end
12154 }
12155 });
12156
12157 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12158}
12159
12160pub fn hunks_for_rows(
12161 rows: impl Iterator<Item = Range<MultiBufferRow>>,
12162 multi_buffer_snapshot: &MultiBufferSnapshot,
12163) -> Vec<DiffHunk<MultiBufferRow>> {
12164 let mut hunks = Vec::new();
12165 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12166 HashMap::default();
12167 for selected_multi_buffer_rows in rows {
12168 let query_rows =
12169 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12170 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12171 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12172 // when the caret is just above or just below the deleted hunk.
12173 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12174 let related_to_selection = if allow_adjacent {
12175 hunk.associated_range.overlaps(&query_rows)
12176 || hunk.associated_range.start == query_rows.end
12177 || hunk.associated_range.end == query_rows.start
12178 } else {
12179 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12180 // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12181 hunk.associated_range.overlaps(&selected_multi_buffer_rows)
12182 || selected_multi_buffer_rows.end == hunk.associated_range.start
12183 };
12184 if related_to_selection {
12185 if !processed_buffer_rows
12186 .entry(hunk.buffer_id)
12187 .or_default()
12188 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12189 {
12190 continue;
12191 }
12192 hunks.push(hunk);
12193 }
12194 }
12195 }
12196
12197 hunks
12198}
12199
12200pub trait CollaborationHub {
12201 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12202 fn user_participant_indices<'a>(
12203 &self,
12204 cx: &'a AppContext,
12205 ) -> &'a HashMap<u64, ParticipantIndex>;
12206 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12207}
12208
12209impl CollaborationHub for Model<Project> {
12210 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12211 self.read(cx).collaborators()
12212 }
12213
12214 fn user_participant_indices<'a>(
12215 &self,
12216 cx: &'a AppContext,
12217 ) -> &'a HashMap<u64, ParticipantIndex> {
12218 self.read(cx).user_store().read(cx).participant_indices()
12219 }
12220
12221 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12222 let this = self.read(cx);
12223 let user_ids = this.collaborators().values().map(|c| c.user_id);
12224 this.user_store().read_with(cx, |user_store, cx| {
12225 user_store.participant_names(user_ids, cx)
12226 })
12227 }
12228}
12229
12230pub trait CompletionProvider {
12231 fn completions(
12232 &self,
12233 buffer: &Model<Buffer>,
12234 buffer_position: text::Anchor,
12235 trigger: CompletionContext,
12236 cx: &mut ViewContext<Editor>,
12237 ) -> Task<Result<Vec<Completion>>>;
12238
12239 fn resolve_completions(
12240 &self,
12241 buffer: Model<Buffer>,
12242 completion_indices: Vec<usize>,
12243 completions: Arc<RwLock<Box<[Completion]>>>,
12244 cx: &mut ViewContext<Editor>,
12245 ) -> Task<Result<bool>>;
12246
12247 fn apply_additional_edits_for_completion(
12248 &self,
12249 buffer: Model<Buffer>,
12250 completion: Completion,
12251 push_to_history: bool,
12252 cx: &mut ViewContext<Editor>,
12253 ) -> Task<Result<Option<language::Transaction>>>;
12254
12255 fn is_completion_trigger(
12256 &self,
12257 buffer: &Model<Buffer>,
12258 position: language::Anchor,
12259 text: &str,
12260 trigger_in_words: bool,
12261 cx: &mut ViewContext<Editor>,
12262 ) -> bool;
12263
12264 fn sort_completions(&self) -> bool {
12265 true
12266 }
12267}
12268
12269fn snippet_completions(
12270 project: &Project,
12271 buffer: &Model<Buffer>,
12272 buffer_position: text::Anchor,
12273 cx: &mut AppContext,
12274) -> Vec<Completion> {
12275 let language = buffer.read(cx).language_at(buffer_position);
12276 let language_name = language.as_ref().map(|language| language.lsp_id());
12277 let snippet_store = project.snippets().read(cx);
12278 let snippets = snippet_store.snippets_for(language_name, cx);
12279
12280 if snippets.is_empty() {
12281 return vec![];
12282 }
12283 let snapshot = buffer.read(cx).text_snapshot();
12284 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12285
12286 let mut lines = chunks.lines();
12287 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12288 return vec![];
12289 };
12290
12291 let scope = language.map(|language| language.default_scope());
12292 let mut last_word = line_at
12293 .chars()
12294 .rev()
12295 .take_while(|c| char_kind(&scope, *c) == CharKind::Word)
12296 .collect::<String>();
12297 last_word = last_word.chars().rev().collect();
12298 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12299 let to_lsp = |point: &text::Anchor| {
12300 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12301 point_to_lsp(end)
12302 };
12303 let lsp_end = to_lsp(&buffer_position);
12304 snippets
12305 .into_iter()
12306 .filter_map(|snippet| {
12307 let matching_prefix = snippet
12308 .prefix
12309 .iter()
12310 .find(|prefix| prefix.starts_with(&last_word))?;
12311 let start = as_offset - last_word.len();
12312 let start = snapshot.anchor_before(start);
12313 let range = start..buffer_position;
12314 let lsp_start = to_lsp(&start);
12315 let lsp_range = lsp::Range {
12316 start: lsp_start,
12317 end: lsp_end,
12318 };
12319 Some(Completion {
12320 old_range: range,
12321 new_text: snippet.body.clone(),
12322 label: CodeLabel {
12323 text: matching_prefix.clone(),
12324 runs: vec![],
12325 filter_range: 0..matching_prefix.len(),
12326 },
12327 server_id: LanguageServerId(usize::MAX),
12328 documentation: snippet
12329 .description
12330 .clone()
12331 .map(|description| Documentation::SingleLine(description)),
12332 lsp_completion: lsp::CompletionItem {
12333 label: snippet.prefix.first().unwrap().clone(),
12334 kind: Some(CompletionItemKind::SNIPPET),
12335 label_details: snippet.description.as_ref().map(|description| {
12336 lsp::CompletionItemLabelDetails {
12337 detail: Some(description.clone()),
12338 description: None,
12339 }
12340 }),
12341 insert_text_format: Some(InsertTextFormat::SNIPPET),
12342 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12343 lsp::InsertReplaceEdit {
12344 new_text: snippet.body.clone(),
12345 insert: lsp_range,
12346 replace: lsp_range,
12347 },
12348 )),
12349 filter_text: Some(snippet.body.clone()),
12350 sort_text: Some(char::MAX.to_string()),
12351 ..Default::default()
12352 },
12353 confirm: None,
12354 })
12355 })
12356 .collect()
12357}
12358
12359impl CompletionProvider for Model<Project> {
12360 fn completions(
12361 &self,
12362 buffer: &Model<Buffer>,
12363 buffer_position: text::Anchor,
12364 options: CompletionContext,
12365 cx: &mut ViewContext<Editor>,
12366 ) -> Task<Result<Vec<Completion>>> {
12367 self.update(cx, |project, cx| {
12368 let snippets = snippet_completions(project, buffer, buffer_position, cx);
12369 let project_completions = project.completions(&buffer, buffer_position, options, cx);
12370 cx.background_executor().spawn(async move {
12371 let mut completions = project_completions.await?;
12372 //let snippets = snippets.into_iter().;
12373 completions.extend(snippets);
12374 Ok(completions)
12375 })
12376 })
12377 }
12378
12379 fn resolve_completions(
12380 &self,
12381 buffer: Model<Buffer>,
12382 completion_indices: Vec<usize>,
12383 completions: Arc<RwLock<Box<[Completion]>>>,
12384 cx: &mut ViewContext<Editor>,
12385 ) -> Task<Result<bool>> {
12386 self.update(cx, |project, cx| {
12387 project.resolve_completions(buffer, completion_indices, completions, cx)
12388 })
12389 }
12390
12391 fn apply_additional_edits_for_completion(
12392 &self,
12393 buffer: Model<Buffer>,
12394 completion: Completion,
12395 push_to_history: bool,
12396 cx: &mut ViewContext<Editor>,
12397 ) -> Task<Result<Option<language::Transaction>>> {
12398 self.update(cx, |project, cx| {
12399 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12400 })
12401 }
12402
12403 fn is_completion_trigger(
12404 &self,
12405 buffer: &Model<Buffer>,
12406 position: language::Anchor,
12407 text: &str,
12408 trigger_in_words: bool,
12409 cx: &mut ViewContext<Editor>,
12410 ) -> bool {
12411 if !EditorSettings::get_global(cx).show_completions_on_input {
12412 return false;
12413 }
12414
12415 let mut chars = text.chars();
12416 let char = if let Some(char) = chars.next() {
12417 char
12418 } else {
12419 return false;
12420 };
12421 if chars.next().is_some() {
12422 return false;
12423 }
12424
12425 let buffer = buffer.read(cx);
12426 let scope = buffer.snapshot().language_scope_at(position);
12427 if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
12428 return true;
12429 }
12430
12431 buffer
12432 .completion_triggers()
12433 .iter()
12434 .any(|string| string == text)
12435 }
12436}
12437
12438fn inlay_hint_settings(
12439 location: Anchor,
12440 snapshot: &MultiBufferSnapshot,
12441 cx: &mut ViewContext<'_, Editor>,
12442) -> InlayHintSettings {
12443 let file = snapshot.file_at(location);
12444 let language = snapshot.language_at(location);
12445 let settings = all_language_settings(file, cx);
12446 settings
12447 .language(language.map(|l| l.name()).as_deref())
12448 .inlay_hints
12449}
12450
12451fn consume_contiguous_rows(
12452 contiguous_row_selections: &mut Vec<Selection<Point>>,
12453 selection: &Selection<Point>,
12454 display_map: &DisplaySnapshot,
12455 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12456) -> (MultiBufferRow, MultiBufferRow) {
12457 contiguous_row_selections.push(selection.clone());
12458 let start_row = MultiBufferRow(selection.start.row);
12459 let mut end_row = ending_row(selection, display_map);
12460
12461 while let Some(next_selection) = selections.peek() {
12462 if next_selection.start.row <= end_row.0 {
12463 end_row = ending_row(next_selection, display_map);
12464 contiguous_row_selections.push(selections.next().unwrap().clone());
12465 } else {
12466 break;
12467 }
12468 }
12469 (start_row, end_row)
12470}
12471
12472fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12473 if next_selection.end.column > 0 || next_selection.is_empty() {
12474 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12475 } else {
12476 MultiBufferRow(next_selection.end.row)
12477 }
12478}
12479
12480impl EditorSnapshot {
12481 pub fn remote_selections_in_range<'a>(
12482 &'a self,
12483 range: &'a Range<Anchor>,
12484 collaboration_hub: &dyn CollaborationHub,
12485 cx: &'a AppContext,
12486 ) -> impl 'a + Iterator<Item = RemoteSelection> {
12487 let participant_names = collaboration_hub.user_names(cx);
12488 let participant_indices = collaboration_hub.user_participant_indices(cx);
12489 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12490 let collaborators_by_replica_id = collaborators_by_peer_id
12491 .iter()
12492 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12493 .collect::<HashMap<_, _>>();
12494 self.buffer_snapshot
12495 .selections_in_range(range, false)
12496 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12497 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12498 let participant_index = participant_indices.get(&collaborator.user_id).copied();
12499 let user_name = participant_names.get(&collaborator.user_id).cloned();
12500 Some(RemoteSelection {
12501 replica_id,
12502 selection,
12503 cursor_shape,
12504 line_mode,
12505 participant_index,
12506 peer_id: collaborator.peer_id,
12507 user_name,
12508 })
12509 })
12510 }
12511
12512 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12513 self.display_snapshot.buffer_snapshot.language_at(position)
12514 }
12515
12516 pub fn is_focused(&self) -> bool {
12517 self.is_focused
12518 }
12519
12520 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12521 self.placeholder_text.as_ref()
12522 }
12523
12524 pub fn scroll_position(&self) -> gpui::Point<f32> {
12525 self.scroll_anchor.scroll_position(&self.display_snapshot)
12526 }
12527
12528 fn gutter_dimensions(
12529 &self,
12530 font_id: FontId,
12531 font_size: Pixels,
12532 em_width: Pixels,
12533 max_line_number_width: Pixels,
12534 cx: &AppContext,
12535 ) -> GutterDimensions {
12536 if !self.show_gutter {
12537 return GutterDimensions::default();
12538 }
12539 let descent = cx.text_system().descent(font_id, font_size);
12540
12541 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12542 matches!(
12543 ProjectSettings::get_global(cx).git.git_gutter,
12544 Some(GitGutterSetting::TrackedFiles)
12545 )
12546 });
12547 let gutter_settings = EditorSettings::get_global(cx).gutter;
12548 let show_line_numbers = self
12549 .show_line_numbers
12550 .unwrap_or(gutter_settings.line_numbers);
12551 let line_gutter_width = if show_line_numbers {
12552 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12553 let min_width_for_number_on_gutter = em_width * 4.0;
12554 max_line_number_width.max(min_width_for_number_on_gutter)
12555 } else {
12556 0.0.into()
12557 };
12558
12559 let show_code_actions = self
12560 .show_code_actions
12561 .unwrap_or(gutter_settings.code_actions);
12562
12563 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12564
12565 let git_blame_entries_width = self
12566 .render_git_blame_gutter
12567 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12568
12569 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12570 left_padding += if show_code_actions || show_runnables {
12571 em_width * 3.0
12572 } else if show_git_gutter && show_line_numbers {
12573 em_width * 2.0
12574 } else if show_git_gutter || show_line_numbers {
12575 em_width
12576 } else {
12577 px(0.)
12578 };
12579
12580 let right_padding = if gutter_settings.folds && show_line_numbers {
12581 em_width * 4.0
12582 } else if gutter_settings.folds {
12583 em_width * 3.0
12584 } else if show_line_numbers {
12585 em_width
12586 } else {
12587 px(0.)
12588 };
12589
12590 GutterDimensions {
12591 left_padding,
12592 right_padding,
12593 width: line_gutter_width + left_padding + right_padding,
12594 margin: -descent,
12595 git_blame_entries_width,
12596 }
12597 }
12598
12599 pub fn render_fold_toggle(
12600 &self,
12601 buffer_row: MultiBufferRow,
12602 row_contains_cursor: bool,
12603 editor: View<Editor>,
12604 cx: &mut WindowContext,
12605 ) -> Option<AnyElement> {
12606 let folded = self.is_line_folded(buffer_row);
12607
12608 if let Some(crease) = self
12609 .crease_snapshot
12610 .query_row(buffer_row, &self.buffer_snapshot)
12611 {
12612 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12613 if folded {
12614 editor.update(cx, |editor, cx| {
12615 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12616 });
12617 } else {
12618 editor.update(cx, |editor, cx| {
12619 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12620 });
12621 }
12622 });
12623
12624 Some((crease.render_toggle)(
12625 buffer_row,
12626 folded,
12627 toggle_callback,
12628 cx,
12629 ))
12630 } else if folded
12631 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12632 {
12633 Some(
12634 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12635 .selected(folded)
12636 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12637 if folded {
12638 this.unfold_at(&UnfoldAt { buffer_row }, cx);
12639 } else {
12640 this.fold_at(&FoldAt { buffer_row }, cx);
12641 }
12642 }))
12643 .into_any_element(),
12644 )
12645 } else {
12646 None
12647 }
12648 }
12649
12650 pub fn render_crease_trailer(
12651 &self,
12652 buffer_row: MultiBufferRow,
12653 cx: &mut WindowContext,
12654 ) -> Option<AnyElement> {
12655 let folded = self.is_line_folded(buffer_row);
12656 let crease = self
12657 .crease_snapshot
12658 .query_row(buffer_row, &self.buffer_snapshot)?;
12659 Some((crease.render_trailer)(buffer_row, folded, cx))
12660 }
12661}
12662
12663impl Deref for EditorSnapshot {
12664 type Target = DisplaySnapshot;
12665
12666 fn deref(&self) -> &Self::Target {
12667 &self.display_snapshot
12668 }
12669}
12670
12671#[derive(Clone, Debug, PartialEq, Eq)]
12672pub enum EditorEvent {
12673 InputIgnored {
12674 text: Arc<str>,
12675 },
12676 InputHandled {
12677 utf16_range_to_replace: Option<Range<isize>>,
12678 text: Arc<str>,
12679 },
12680 ExcerptsAdded {
12681 buffer: Model<Buffer>,
12682 predecessor: ExcerptId,
12683 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12684 },
12685 ExcerptsRemoved {
12686 ids: Vec<ExcerptId>,
12687 },
12688 ExcerptsEdited {
12689 ids: Vec<ExcerptId>,
12690 },
12691 ExcerptsExpanded {
12692 ids: Vec<ExcerptId>,
12693 },
12694 BufferEdited,
12695 Edited {
12696 transaction_id: clock::Lamport,
12697 },
12698 Reparsed(BufferId),
12699 Focused,
12700 FocusedIn,
12701 Blurred,
12702 DirtyChanged,
12703 Saved,
12704 TitleChanged,
12705 DiffBaseChanged,
12706 SelectionsChanged {
12707 local: bool,
12708 },
12709 ScrollPositionChanged {
12710 local: bool,
12711 autoscroll: bool,
12712 },
12713 Closed,
12714 TransactionUndone {
12715 transaction_id: clock::Lamport,
12716 },
12717 TransactionBegun {
12718 transaction_id: clock::Lamport,
12719 },
12720}
12721
12722impl EventEmitter<EditorEvent> for Editor {}
12723
12724impl FocusableView for Editor {
12725 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12726 self.focus_handle.clone()
12727 }
12728}
12729
12730impl Render for Editor {
12731 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12732 let settings = ThemeSettings::get_global(cx);
12733
12734 let text_style = match self.mode {
12735 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12736 color: cx.theme().colors().editor_foreground,
12737 font_family: settings.ui_font.family.clone(),
12738 font_features: settings.ui_font.features.clone(),
12739 font_fallbacks: settings.ui_font.fallbacks.clone(),
12740 font_size: rems(0.875).into(),
12741 font_weight: settings.ui_font.weight,
12742 line_height: relative(settings.buffer_line_height.value()),
12743 ..Default::default()
12744 },
12745 EditorMode::Full => TextStyle {
12746 color: cx.theme().colors().editor_foreground,
12747 font_family: settings.buffer_font.family.clone(),
12748 font_features: settings.buffer_font.features.clone(),
12749 font_fallbacks: settings.buffer_font.fallbacks.clone(),
12750 font_size: settings.buffer_font_size(cx).into(),
12751 font_weight: settings.buffer_font.weight,
12752 line_height: relative(settings.buffer_line_height.value()),
12753 ..Default::default()
12754 },
12755 };
12756
12757 let background = match self.mode {
12758 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12759 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12760 EditorMode::Full => cx.theme().colors().editor_background,
12761 };
12762
12763 EditorElement::new(
12764 cx.view(),
12765 EditorStyle {
12766 background,
12767 local_player: cx.theme().players().local(),
12768 text: text_style,
12769 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12770 syntax: cx.theme().syntax().clone(),
12771 status: cx.theme().status().clone(),
12772 inlay_hints_style: HighlightStyle {
12773 color: Some(cx.theme().status().hint),
12774 ..HighlightStyle::default()
12775 },
12776 suggestions_style: HighlightStyle {
12777 color: Some(cx.theme().status().predictive),
12778 ..HighlightStyle::default()
12779 },
12780 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
12781 },
12782 )
12783 }
12784}
12785
12786impl ViewInputHandler for Editor {
12787 fn text_for_range(
12788 &mut self,
12789 range_utf16: Range<usize>,
12790 cx: &mut ViewContext<Self>,
12791 ) -> Option<String> {
12792 Some(
12793 self.buffer
12794 .read(cx)
12795 .read(cx)
12796 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12797 .collect(),
12798 )
12799 }
12800
12801 fn selected_text_range(
12802 &mut self,
12803 ignore_disabled_input: bool,
12804 cx: &mut ViewContext<Self>,
12805 ) -> Option<UTF16Selection> {
12806 // Prevent the IME menu from appearing when holding down an alphabetic key
12807 // while input is disabled.
12808 if !ignore_disabled_input && !self.input_enabled {
12809 return None;
12810 }
12811
12812 let selection = self.selections.newest::<OffsetUtf16>(cx);
12813 let range = selection.range();
12814
12815 Some(UTF16Selection {
12816 range: range.start.0..range.end.0,
12817 reversed: selection.reversed,
12818 })
12819 }
12820
12821 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12822 let snapshot = self.buffer.read(cx).read(cx);
12823 let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
12824 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12825 }
12826
12827 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12828 self.clear_highlights::<InputComposition>(cx);
12829 self.ime_transaction.take();
12830 }
12831
12832 fn replace_text_in_range(
12833 &mut self,
12834 range_utf16: Option<Range<usize>>,
12835 text: &str,
12836 cx: &mut ViewContext<Self>,
12837 ) {
12838 if !self.input_enabled {
12839 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12840 return;
12841 }
12842
12843 self.transact(cx, |this, cx| {
12844 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12845 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12846 Some(this.selection_replacement_ranges(range_utf16, cx))
12847 } else {
12848 this.marked_text_ranges(cx)
12849 };
12850
12851 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12852 let newest_selection_id = this.selections.newest_anchor().id;
12853 this.selections
12854 .all::<OffsetUtf16>(cx)
12855 .iter()
12856 .zip(ranges_to_replace.iter())
12857 .find_map(|(selection, range)| {
12858 if selection.id == newest_selection_id {
12859 Some(
12860 (range.start.0 as isize - selection.head().0 as isize)
12861 ..(range.end.0 as isize - selection.head().0 as isize),
12862 )
12863 } else {
12864 None
12865 }
12866 })
12867 });
12868
12869 cx.emit(EditorEvent::InputHandled {
12870 utf16_range_to_replace: range_to_replace,
12871 text: text.into(),
12872 });
12873
12874 if let Some(new_selected_ranges) = new_selected_ranges {
12875 this.change_selections(None, cx, |selections| {
12876 selections.select_ranges(new_selected_ranges)
12877 });
12878 this.backspace(&Default::default(), cx);
12879 }
12880
12881 this.handle_input(text, cx);
12882 });
12883
12884 if let Some(transaction) = self.ime_transaction {
12885 self.buffer.update(cx, |buffer, cx| {
12886 buffer.group_until_transaction(transaction, cx);
12887 });
12888 }
12889
12890 self.unmark_text(cx);
12891 }
12892
12893 fn replace_and_mark_text_in_range(
12894 &mut self,
12895 range_utf16: Option<Range<usize>>,
12896 text: &str,
12897 new_selected_range_utf16: Option<Range<usize>>,
12898 cx: &mut ViewContext<Self>,
12899 ) {
12900 if !self.input_enabled {
12901 return;
12902 }
12903
12904 let transaction = self.transact(cx, |this, cx| {
12905 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12906 let snapshot = this.buffer.read(cx).read(cx);
12907 if let Some(relative_range_utf16) = range_utf16.as_ref() {
12908 for marked_range in &mut marked_ranges {
12909 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12910 marked_range.start.0 += relative_range_utf16.start;
12911 marked_range.start =
12912 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12913 marked_range.end =
12914 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12915 }
12916 }
12917 Some(marked_ranges)
12918 } else if let Some(range_utf16) = range_utf16 {
12919 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12920 Some(this.selection_replacement_ranges(range_utf16, cx))
12921 } else {
12922 None
12923 };
12924
12925 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12926 let newest_selection_id = this.selections.newest_anchor().id;
12927 this.selections
12928 .all::<OffsetUtf16>(cx)
12929 .iter()
12930 .zip(ranges_to_replace.iter())
12931 .find_map(|(selection, range)| {
12932 if selection.id == newest_selection_id {
12933 Some(
12934 (range.start.0 as isize - selection.head().0 as isize)
12935 ..(range.end.0 as isize - selection.head().0 as isize),
12936 )
12937 } else {
12938 None
12939 }
12940 })
12941 });
12942
12943 cx.emit(EditorEvent::InputHandled {
12944 utf16_range_to_replace: range_to_replace,
12945 text: text.into(),
12946 });
12947
12948 if let Some(ranges) = ranges_to_replace {
12949 this.change_selections(None, cx, |s| s.select_ranges(ranges));
12950 }
12951
12952 let marked_ranges = {
12953 let snapshot = this.buffer.read(cx).read(cx);
12954 this.selections
12955 .disjoint_anchors()
12956 .iter()
12957 .map(|selection| {
12958 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12959 })
12960 .collect::<Vec<_>>()
12961 };
12962
12963 if text.is_empty() {
12964 this.unmark_text(cx);
12965 } else {
12966 this.highlight_text::<InputComposition>(
12967 marked_ranges.clone(),
12968 HighlightStyle {
12969 underline: Some(UnderlineStyle {
12970 thickness: px(1.),
12971 color: None,
12972 wavy: false,
12973 }),
12974 ..Default::default()
12975 },
12976 cx,
12977 );
12978 }
12979
12980 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12981 let use_autoclose = this.use_autoclose;
12982 let use_auto_surround = this.use_auto_surround;
12983 this.set_use_autoclose(false);
12984 this.set_use_auto_surround(false);
12985 this.handle_input(text, cx);
12986 this.set_use_autoclose(use_autoclose);
12987 this.set_use_auto_surround(use_auto_surround);
12988
12989 if let Some(new_selected_range) = new_selected_range_utf16 {
12990 let snapshot = this.buffer.read(cx).read(cx);
12991 let new_selected_ranges = marked_ranges
12992 .into_iter()
12993 .map(|marked_range| {
12994 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
12995 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
12996 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
12997 snapshot.clip_offset_utf16(new_start, Bias::Left)
12998 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
12999 })
13000 .collect::<Vec<_>>();
13001
13002 drop(snapshot);
13003 this.change_selections(None, cx, |selections| {
13004 selections.select_ranges(new_selected_ranges)
13005 });
13006 }
13007 });
13008
13009 self.ime_transaction = self.ime_transaction.or(transaction);
13010 if let Some(transaction) = self.ime_transaction {
13011 self.buffer.update(cx, |buffer, cx| {
13012 buffer.group_until_transaction(transaction, cx);
13013 });
13014 }
13015
13016 if self.text_highlights::<InputComposition>(cx).is_none() {
13017 self.ime_transaction.take();
13018 }
13019 }
13020
13021 fn bounds_for_range(
13022 &mut self,
13023 range_utf16: Range<usize>,
13024 element_bounds: gpui::Bounds<Pixels>,
13025 cx: &mut ViewContext<Self>,
13026 ) -> Option<gpui::Bounds<Pixels>> {
13027 let text_layout_details = self.text_layout_details(cx);
13028 let style = &text_layout_details.editor_style;
13029 let font_id = cx.text_system().resolve_font(&style.text.font());
13030 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13031 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13032
13033 let em_width = cx
13034 .text_system()
13035 .typographic_bounds(font_id, font_size, 'm')
13036 .unwrap()
13037 .size
13038 .width;
13039
13040 let snapshot = self.snapshot(cx);
13041 let scroll_position = snapshot.scroll_position();
13042 let scroll_left = scroll_position.x * em_width;
13043
13044 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13045 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13046 + self.gutter_dimensions.width;
13047 let y = line_height * (start.row().as_f32() - scroll_position.y);
13048
13049 Some(Bounds {
13050 origin: element_bounds.origin + point(x, y),
13051 size: size(em_width, line_height),
13052 })
13053 }
13054}
13055
13056trait SelectionExt {
13057 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13058 fn spanned_rows(
13059 &self,
13060 include_end_if_at_line_start: bool,
13061 map: &DisplaySnapshot,
13062 ) -> Range<MultiBufferRow>;
13063}
13064
13065impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
13066 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
13067 let start = self
13068 .start
13069 .to_point(&map.buffer_snapshot)
13070 .to_display_point(map);
13071 let end = self
13072 .end
13073 .to_point(&map.buffer_snapshot)
13074 .to_display_point(map);
13075 if self.reversed {
13076 end..start
13077 } else {
13078 start..end
13079 }
13080 }
13081
13082 fn spanned_rows(
13083 &self,
13084 include_end_if_at_line_start: bool,
13085 map: &DisplaySnapshot,
13086 ) -> Range<MultiBufferRow> {
13087 let start = self.start.to_point(&map.buffer_snapshot);
13088 let mut end = self.end.to_point(&map.buffer_snapshot);
13089 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
13090 end.row -= 1;
13091 }
13092
13093 let buffer_start = map.prev_line_boundary(start).0;
13094 let buffer_end = map.next_line_boundary(end).0;
13095 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
13096 }
13097}
13098
13099impl<T: InvalidationRegion> InvalidationStack<T> {
13100 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
13101 where
13102 S: Clone + ToOffset,
13103 {
13104 while let Some(region) = self.last() {
13105 let all_selections_inside_invalidation_ranges =
13106 if selections.len() == region.ranges().len() {
13107 selections
13108 .iter()
13109 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
13110 .all(|(selection, invalidation_range)| {
13111 let head = selection.head().to_offset(buffer);
13112 invalidation_range.start <= head && invalidation_range.end >= head
13113 })
13114 } else {
13115 false
13116 };
13117
13118 if all_selections_inside_invalidation_ranges {
13119 break;
13120 } else {
13121 self.pop();
13122 }
13123 }
13124 }
13125}
13126
13127impl<T> Default for InvalidationStack<T> {
13128 fn default() -> Self {
13129 Self(Default::default())
13130 }
13131}
13132
13133impl<T> Deref for InvalidationStack<T> {
13134 type Target = Vec<T>;
13135
13136 fn deref(&self) -> &Self::Target {
13137 &self.0
13138 }
13139}
13140
13141impl<T> DerefMut for InvalidationStack<T> {
13142 fn deref_mut(&mut self) -> &mut Self::Target {
13143 &mut self.0
13144 }
13145}
13146
13147impl InvalidationRegion for SnippetState {
13148 fn ranges(&self) -> &[Range<Anchor>] {
13149 &self.ranges[self.active_index]
13150 }
13151}
13152
13153pub fn diagnostic_block_renderer(
13154 diagnostic: Diagnostic,
13155 max_message_rows: Option<u8>,
13156 allow_closing: bool,
13157 _is_valid: bool,
13158) -> RenderBlock {
13159 let (text_without_backticks, code_ranges) =
13160 highlight_diagnostic_message(&diagnostic, max_message_rows);
13161
13162 Box::new(move |cx: &mut BlockContext| {
13163 let group_id: SharedString = cx.block_id.to_string().into();
13164
13165 let mut text_style = cx.text_style().clone();
13166 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13167 let theme_settings = ThemeSettings::get_global(cx);
13168 text_style.font_family = theme_settings.buffer_font.family.clone();
13169 text_style.font_style = theme_settings.buffer_font.style;
13170 text_style.font_features = theme_settings.buffer_font.features.clone();
13171 text_style.font_weight = theme_settings.buffer_font.weight;
13172
13173 let multi_line_diagnostic = diagnostic.message.contains('\n');
13174
13175 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13176 if multi_line_diagnostic {
13177 v_flex()
13178 } else {
13179 h_flex()
13180 }
13181 .when(allow_closing, |div| {
13182 div.children(diagnostic.is_primary.then(|| {
13183 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13184 .icon_color(Color::Muted)
13185 .size(ButtonSize::Compact)
13186 .style(ButtonStyle::Transparent)
13187 .visible_on_hover(group_id.clone())
13188 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13189 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13190 }))
13191 })
13192 .child(
13193 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13194 .icon_color(Color::Muted)
13195 .size(ButtonSize::Compact)
13196 .style(ButtonStyle::Transparent)
13197 .visible_on_hover(group_id.clone())
13198 .on_click({
13199 let message = diagnostic.message.clone();
13200 move |_click, cx| {
13201 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13202 }
13203 })
13204 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13205 )
13206 };
13207
13208 let icon_size = buttons(&diagnostic, cx.block_id)
13209 .into_any_element()
13210 .layout_as_root(AvailableSpace::min_size(), cx);
13211
13212 h_flex()
13213 .id(cx.block_id)
13214 .group(group_id.clone())
13215 .relative()
13216 .size_full()
13217 .pl(cx.gutter_dimensions.width)
13218 .w(cx.max_width + cx.gutter_dimensions.width)
13219 .child(
13220 div()
13221 .flex()
13222 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13223 .flex_shrink(),
13224 )
13225 .child(buttons(&diagnostic, cx.block_id))
13226 .child(div().flex().flex_shrink_0().child(
13227 StyledText::new(text_without_backticks.clone()).with_highlights(
13228 &text_style,
13229 code_ranges.iter().map(|range| {
13230 (
13231 range.clone(),
13232 HighlightStyle {
13233 font_weight: Some(FontWeight::BOLD),
13234 ..Default::default()
13235 },
13236 )
13237 }),
13238 ),
13239 ))
13240 .into_any_element()
13241 })
13242}
13243
13244pub fn highlight_diagnostic_message(
13245 diagnostic: &Diagnostic,
13246 mut max_message_rows: Option<u8>,
13247) -> (SharedString, Vec<Range<usize>>) {
13248 let mut text_without_backticks = String::new();
13249 let mut code_ranges = Vec::new();
13250
13251 if let Some(source) = &diagnostic.source {
13252 text_without_backticks.push_str(&source);
13253 code_ranges.push(0..source.len());
13254 text_without_backticks.push_str(": ");
13255 }
13256
13257 let mut prev_offset = 0;
13258 let mut in_code_block = false;
13259 let has_row_limit = max_message_rows.is_some();
13260 let mut newline_indices = diagnostic
13261 .message
13262 .match_indices('\n')
13263 .filter(|_| has_row_limit)
13264 .map(|(ix, _)| ix)
13265 .fuse()
13266 .peekable();
13267
13268 for (quote_ix, _) in diagnostic
13269 .message
13270 .match_indices('`')
13271 .chain([(diagnostic.message.len(), "")])
13272 {
13273 let mut first_newline_ix = None;
13274 let mut last_newline_ix = None;
13275 while let Some(newline_ix) = newline_indices.peek() {
13276 if *newline_ix < quote_ix {
13277 if first_newline_ix.is_none() {
13278 first_newline_ix = Some(*newline_ix);
13279 }
13280 last_newline_ix = Some(*newline_ix);
13281
13282 if let Some(rows_left) = &mut max_message_rows {
13283 if *rows_left == 0 {
13284 break;
13285 } else {
13286 *rows_left -= 1;
13287 }
13288 }
13289 let _ = newline_indices.next();
13290 } else {
13291 break;
13292 }
13293 }
13294 let prev_len = text_without_backticks.len();
13295 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
13296 text_without_backticks.push_str(new_text);
13297 if in_code_block {
13298 code_ranges.push(prev_len..text_without_backticks.len());
13299 }
13300 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13301 in_code_block = !in_code_block;
13302 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13303 text_without_backticks.push_str("...");
13304 break;
13305 }
13306 }
13307
13308 (text_without_backticks.into(), code_ranges)
13309}
13310
13311fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13312 match severity {
13313 DiagnosticSeverity::ERROR => colors.error,
13314 DiagnosticSeverity::WARNING => colors.warning,
13315 DiagnosticSeverity::INFORMATION => colors.info,
13316 DiagnosticSeverity::HINT => colors.info,
13317 _ => colors.ignored,
13318 }
13319}
13320
13321pub fn styled_runs_for_code_label<'a>(
13322 label: &'a CodeLabel,
13323 syntax_theme: &'a theme::SyntaxTheme,
13324) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13325 let fade_out = HighlightStyle {
13326 fade_out: Some(0.35),
13327 ..Default::default()
13328 };
13329
13330 let mut prev_end = label.filter_range.end;
13331 label
13332 .runs
13333 .iter()
13334 .enumerate()
13335 .flat_map(move |(ix, (range, highlight_id))| {
13336 let style = if let Some(style) = highlight_id.style(syntax_theme) {
13337 style
13338 } else {
13339 return Default::default();
13340 };
13341 let mut muted_style = style;
13342 muted_style.highlight(fade_out);
13343
13344 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13345 if range.start >= label.filter_range.end {
13346 if range.start > prev_end {
13347 runs.push((prev_end..range.start, fade_out));
13348 }
13349 runs.push((range.clone(), muted_style));
13350 } else if range.end <= label.filter_range.end {
13351 runs.push((range.clone(), style));
13352 } else {
13353 runs.push((range.start..label.filter_range.end, style));
13354 runs.push((label.filter_range.end..range.end, muted_style));
13355 }
13356 prev_end = cmp::max(prev_end, range.end);
13357
13358 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13359 runs.push((prev_end..label.text.len(), fade_out));
13360 }
13361
13362 runs
13363 })
13364}
13365
13366pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13367 let mut prev_index = 0;
13368 let mut prev_codepoint: Option<char> = None;
13369 text.char_indices()
13370 .chain([(text.len(), '\0')])
13371 .filter_map(move |(index, codepoint)| {
13372 let prev_codepoint = prev_codepoint.replace(codepoint)?;
13373 let is_boundary = index == text.len()
13374 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13375 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13376 if is_boundary {
13377 let chunk = &text[prev_index..index];
13378 prev_index = index;
13379 Some(chunk)
13380 } else {
13381 None
13382 }
13383 })
13384}
13385
13386pub trait RangeToAnchorExt: Sized {
13387 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13388
13389 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13390 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13391 anchor_range.start.to_display_point(&snapshot)..anchor_range.end.to_display_point(&snapshot)
13392 }
13393}
13394
13395impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13396 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13397 let start_offset = self.start.to_offset(snapshot);
13398 let end_offset = self.end.to_offset(snapshot);
13399 if start_offset == end_offset {
13400 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13401 } else {
13402 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13403 }
13404 }
13405}
13406
13407pub trait RowExt {
13408 fn as_f32(&self) -> f32;
13409
13410 fn next_row(&self) -> Self;
13411
13412 fn previous_row(&self) -> Self;
13413
13414 fn minus(&self, other: Self) -> u32;
13415}
13416
13417impl RowExt for DisplayRow {
13418 fn as_f32(&self) -> f32 {
13419 self.0 as f32
13420 }
13421
13422 fn next_row(&self) -> Self {
13423 Self(self.0 + 1)
13424 }
13425
13426 fn previous_row(&self) -> Self {
13427 Self(self.0.saturating_sub(1))
13428 }
13429
13430 fn minus(&self, other: Self) -> u32 {
13431 self.0 - other.0
13432 }
13433}
13434
13435impl RowExt for MultiBufferRow {
13436 fn as_f32(&self) -> f32 {
13437 self.0 as f32
13438 }
13439
13440 fn next_row(&self) -> Self {
13441 Self(self.0 + 1)
13442 }
13443
13444 fn previous_row(&self) -> Self {
13445 Self(self.0.saturating_sub(1))
13446 }
13447
13448 fn minus(&self, other: Self) -> u32 {
13449 self.0 - other.0
13450 }
13451}
13452
13453trait RowRangeExt {
13454 type Row;
13455
13456 fn len(&self) -> usize;
13457
13458 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13459}
13460
13461impl RowRangeExt for Range<MultiBufferRow> {
13462 type Row = MultiBufferRow;
13463
13464 fn len(&self) -> usize {
13465 (self.end.0 - self.start.0) as usize
13466 }
13467
13468 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13469 (self.start.0..self.end.0).map(MultiBufferRow)
13470 }
13471}
13472
13473impl RowRangeExt for Range<DisplayRow> {
13474 type Row = DisplayRow;
13475
13476 fn len(&self) -> usize {
13477 (self.end.0 - self.start.0) as usize
13478 }
13479
13480 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13481 (self.start.0..self.end.0).map(DisplayRow)
13482 }
13483}
13484
13485fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13486 if hunk.diff_base_byte_range.is_empty() {
13487 DiffHunkStatus::Added
13488 } else if hunk.associated_range.is_empty() {
13489 DiffHunkStatus::Removed
13490 } else {
13491 DiffHunkStatus::Modified
13492 }
13493}
13494
13495/// If select range has more than one line, we
13496/// just point the cursor to range.start.
13497fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
13498 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
13499 range
13500 } else {
13501 range.start..range.start
13502 }
13503}