1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blame_entry_tooltip;
17mod blink_manager;
18mod clangd_ext;
19mod debounced_delay;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod hunk_diff;
29mod indent_guides;
30mod inlay_hint_cache;
31mod inline_completion_provider;
32pub mod items;
33mod linked_editing_ranges;
34mod lsp_ext;
35mod mouse_context_menu;
36pub mod movement;
37mod persistence;
38mod rust_analyzer_ext;
39pub mod scroll;
40mod selections_collection;
41pub mod tasks;
42
43#[cfg(test)]
44mod editor_tests;
45mod signature_help;
46#[cfg(any(test, feature = "test-support"))]
47pub mod test;
48
49use ::git::diff::{DiffHunk, DiffHunkStatus};
50use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
51pub(crate) use actions::*;
52use aho_corasick::AhoCorasick;
53use anyhow::{anyhow, Context as _, Result};
54use blink_manager::BlinkManager;
55use client::{Collaborator, ParticipantIndex};
56use clock::ReplicaId;
57use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
58use convert_case::{Case, Casing};
59use debounced_delay::DebouncedDelay;
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine};
63pub use editor_settings_controls::*;
64use element::LineWithInvisibles;
65pub use element::{
66 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
67};
68use futures::FutureExt;
69use fuzzy::{StringMatch, StringMatchCandidate};
70use git::blame::GitBlame;
71use git::diff_hunk_to_display;
72use gpui::{
73 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
74 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
75 ClipboardItem, Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle,
76 FocusOutEvent, FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText,
77 KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
78 SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
79 UTF16Selection, UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler,
80 VisualContext, WeakFocusHandle, WeakView, WindowContext,
81};
82use highlight_matching_bracket::refresh_matching_bracket_highlights;
83use hover_popover::{hide_hover, HoverState};
84use hunk_diff::ExpandedHunks;
85pub(crate) use hunk_diff::HoveredHunk;
86use indent_guides::ActiveIndentGuidesState;
87use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
88pub use inline_completion_provider::*;
89pub use items::MAX_TAB_TITLE_LEN;
90use itertools::Itertools;
91use language::{
92 char_kind,
93 language_settings::{self, all_language_settings, InlayHintSettings},
94 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
95 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
96 Point, Selection, SelectionGoal, TransactionId,
97};
98use language::{point_to_lsp, BufferRow, Runnable, RunnableRange};
99use linked_editing_ranges::refresh_linked_ranges;
100use task::{ResolvedTask, TaskTemplate, TaskVariables};
101
102use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
103pub use lsp::CompletionContext;
104use lsp::{
105 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
106 LanguageServerId,
107};
108use mouse_context_menu::MouseContextMenu;
109use movement::TextLayoutDetails;
110pub use multi_buffer::{
111 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
112 ToPoint,
113};
114use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
115use ordered_float::OrderedFloat;
116use parking_lot::{Mutex, RwLock};
117use project::project_settings::{GitGutterSetting, ProjectSettings};
118use project::{
119 CodeAction, Completion, CompletionIntent, FormatTrigger, Item, Location, Project, ProjectPath,
120 ProjectTransaction, TaskSourceKind, WorktreeId,
121};
122use rand::prelude::*;
123use rpc::{proto::*, ErrorExt};
124use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
125use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
126use serde::{Deserialize, Serialize};
127use settings::{update_settings_file, Settings, SettingsStore};
128use smallvec::SmallVec;
129use snippet::Snippet;
130use std::{
131 any::TypeId,
132 borrow::Cow,
133 cell::RefCell,
134 cmp::{self, Ordering, Reverse},
135 mem,
136 num::NonZeroU32,
137 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
138 path::{Path, PathBuf},
139 rc::Rc,
140 sync::Arc,
141 time::{Duration, Instant},
142};
143pub use sum_tree::Bias;
144use sum_tree::TreeMap;
145use text::{BufferId, OffsetUtf16, Rope};
146use theme::{
147 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
148 ThemeColors, ThemeSettings,
149};
150use ui::{
151 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
152 ListItem, Popover, Tooltip,
153};
154use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
155use workspace::item::{ItemHandle, PreviewTabsSettings};
156use workspace::notifications::{DetachAndPromptErr, NotificationId};
157use workspace::{
158 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
159};
160use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
161
162use crate::hover_links::find_url;
163use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
164
165pub const FILE_HEADER_HEIGHT: u32 = 1;
166pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
167pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
168pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
169const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
170const MAX_LINE_LEN: usize = 1024;
171const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
172const MAX_SELECTION_HISTORY_LEN: usize = 1024;
173pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
174#[doc(hidden)]
175pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
176#[doc(hidden)]
177pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
178
179pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
180pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
181
182pub fn render_parsed_markdown(
183 element_id: impl Into<ElementId>,
184 parsed: &language::ParsedMarkdown,
185 editor_style: &EditorStyle,
186 workspace: Option<WeakView<Workspace>>,
187 cx: &mut WindowContext,
188) -> InteractiveText {
189 let code_span_background_color = cx
190 .theme()
191 .colors()
192 .editor_document_highlight_read_background;
193
194 let highlights = gpui::combine_highlights(
195 parsed.highlights.iter().filter_map(|(range, highlight)| {
196 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
197 Some((range.clone(), highlight))
198 }),
199 parsed
200 .regions
201 .iter()
202 .zip(&parsed.region_ranges)
203 .filter_map(|(region, range)| {
204 if region.code {
205 Some((
206 range.clone(),
207 HighlightStyle {
208 background_color: Some(code_span_background_color),
209 ..Default::default()
210 },
211 ))
212 } else {
213 None
214 }
215 }),
216 );
217
218 let mut links = Vec::new();
219 let mut link_ranges = Vec::new();
220 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
221 if let Some(link) = region.link.clone() {
222 links.push(link);
223 link_ranges.push(range.clone());
224 }
225 }
226
227 InteractiveText::new(
228 element_id,
229 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
230 )
231 .on_click(link_ranges, move |clicked_range_ix, cx| {
232 match &links[clicked_range_ix] {
233 markdown::Link::Web { url } => cx.open_url(url),
234 markdown::Link::Path { path } => {
235 if let Some(workspace) = &workspace {
236 _ = workspace.update(cx, |workspace, cx| {
237 workspace.open_abs_path(path.clone(), false, cx).detach();
238 });
239 }
240 }
241 }
242 })
243}
244
245#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
246pub(crate) enum InlayId {
247 Suggestion(usize),
248 Hint(usize),
249}
250
251impl InlayId {
252 fn id(&self) -> usize {
253 match self {
254 Self::Suggestion(id) => *id,
255 Self::Hint(id) => *id,
256 }
257 }
258}
259
260enum DiffRowHighlight {}
261enum DocumentHighlightRead {}
262enum DocumentHighlightWrite {}
263enum InputComposition {}
264
265#[derive(Copy, Clone, PartialEq, Eq)]
266pub enum Direction {
267 Prev,
268 Next,
269}
270
271#[derive(Debug, Copy, Clone, PartialEq, Eq)]
272pub enum Navigated {
273 Yes,
274 No,
275}
276
277impl Navigated {
278 pub fn from_bool(yes: bool) -> Navigated {
279 if yes {
280 Navigated::Yes
281 } else {
282 Navigated::No
283 }
284 }
285}
286
287pub fn init_settings(cx: &mut AppContext) {
288 EditorSettings::register(cx);
289}
290
291pub fn init(cx: &mut AppContext) {
292 init_settings(cx);
293
294 workspace::register_project_item::<Editor>(cx);
295 workspace::FollowableViewRegistry::register::<Editor>(cx);
296 workspace::register_serializable_item::<Editor>(cx);
297
298 cx.observe_new_views(
299 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
300 workspace.register_action(Editor::new_file);
301 workspace.register_action(Editor::new_file_vertical);
302 workspace.register_action(Editor::new_file_horizontal);
303 },
304 )
305 .detach();
306
307 cx.on_action(move |_: &workspace::NewFile, cx| {
308 let app_state = workspace::AppState::global(cx);
309 if let Some(app_state) = app_state.upgrade() {
310 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
311 Editor::new_file(workspace, &Default::default(), cx)
312 })
313 .detach();
314 }
315 });
316 cx.on_action(move |_: &workspace::NewWindow, cx| {
317 let app_state = workspace::AppState::global(cx);
318 if let Some(app_state) = app_state.upgrade() {
319 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
320 Editor::new_file(workspace, &Default::default(), cx)
321 })
322 .detach();
323 }
324 });
325}
326
327pub struct SearchWithinRange;
328
329trait InvalidationRegion {
330 fn ranges(&self) -> &[Range<Anchor>];
331}
332
333#[derive(Clone, Debug, PartialEq)]
334pub enum SelectPhase {
335 Begin {
336 position: DisplayPoint,
337 add: bool,
338 click_count: usize,
339 },
340 BeginColumnar {
341 position: DisplayPoint,
342 reset: bool,
343 goal_column: u32,
344 },
345 Extend {
346 position: DisplayPoint,
347 click_count: usize,
348 },
349 Update {
350 position: DisplayPoint,
351 goal_column: u32,
352 scroll_delta: gpui::Point<f32>,
353 },
354 End,
355}
356
357#[derive(Clone, Debug)]
358pub enum SelectMode {
359 Character,
360 Word(Range<Anchor>),
361 Line(Range<Anchor>),
362 All,
363}
364
365#[derive(Copy, Clone, PartialEq, Eq, Debug)]
366pub enum EditorMode {
367 SingleLine { auto_width: bool },
368 AutoHeight { max_lines: usize },
369 Full,
370}
371
372#[derive(Clone, Debug)]
373pub enum SoftWrap {
374 None,
375 PreferLine,
376 EditorWidth,
377 Column(u32),
378 Bounded(u32),
379}
380
381#[derive(Clone)]
382pub struct EditorStyle {
383 pub background: Hsla,
384 pub local_player: PlayerColor,
385 pub text: TextStyle,
386 pub scrollbar_width: Pixels,
387 pub syntax: Arc<SyntaxTheme>,
388 pub status: StatusColors,
389 pub inlay_hints_style: HighlightStyle,
390 pub suggestions_style: HighlightStyle,
391 pub unnecessary_code_fade: f32,
392}
393
394impl Default for EditorStyle {
395 fn default() -> Self {
396 Self {
397 background: Hsla::default(),
398 local_player: PlayerColor::default(),
399 text: TextStyle::default(),
400 scrollbar_width: Pixels::default(),
401 syntax: Default::default(),
402 // HACK: Status colors don't have a real default.
403 // We should look into removing the status colors from the editor
404 // style and retrieve them directly from the theme.
405 status: StatusColors::dark(),
406 inlay_hints_style: HighlightStyle::default(),
407 suggestions_style: HighlightStyle::default(),
408 unnecessary_code_fade: Default::default(),
409 }
410 }
411}
412
413type CompletionId = usize;
414
415#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
416struct EditorActionId(usize);
417
418impl EditorActionId {
419 pub fn post_inc(&mut self) -> Self {
420 let answer = self.0;
421
422 *self = Self(answer + 1);
423
424 Self(answer)
425 }
426}
427
428// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
429// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
430
431type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
432type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
433
434#[derive(Default)]
435struct ScrollbarMarkerState {
436 scrollbar_size: Size<Pixels>,
437 dirty: bool,
438 markers: Arc<[PaintQuad]>,
439 pending_refresh: Option<Task<Result<()>>>,
440}
441
442impl ScrollbarMarkerState {
443 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
444 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
445 }
446}
447
448#[derive(Clone, Debug)]
449struct RunnableTasks {
450 templates: Vec<(TaskSourceKind, TaskTemplate)>,
451 offset: MultiBufferOffset,
452 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
453 column: u32,
454 // Values of all named captures, including those starting with '_'
455 extra_variables: HashMap<String, String>,
456 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
457 context_range: Range<BufferOffset>,
458}
459
460#[derive(Clone)]
461struct ResolvedTasks {
462 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
463 position: Anchor,
464}
465#[derive(Copy, Clone, Debug)]
466struct MultiBufferOffset(usize);
467#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
468struct BufferOffset(usize);
469
470// Addons allow storing per-editor state in other crates (e.g. Vim)
471pub trait Addon: 'static {
472 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
473
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 cx.spawn(|editor, mut cx| async move {
9115 if definition.await? == Navigated::Yes {
9116 return Ok(Navigated::Yes);
9117 }
9118 match editor.update(&mut cx, |editor, cx| {
9119 editor.find_all_references(&FindAllReferences, cx)
9120 })? {
9121 Some(references) => references.await,
9122 None => Ok(Navigated::No),
9123 }
9124 })
9125 }
9126
9127 pub fn go_to_declaration(
9128 &mut self,
9129 _: &GoToDeclaration,
9130 cx: &mut ViewContext<Self>,
9131 ) -> Task<Result<Navigated>> {
9132 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9133 }
9134
9135 pub fn go_to_declaration_split(
9136 &mut self,
9137 _: &GoToDeclaration,
9138 cx: &mut ViewContext<Self>,
9139 ) -> Task<Result<Navigated>> {
9140 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9141 }
9142
9143 pub fn go_to_implementation(
9144 &mut self,
9145 _: &GoToImplementation,
9146 cx: &mut ViewContext<Self>,
9147 ) -> Task<Result<Navigated>> {
9148 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9149 }
9150
9151 pub fn go_to_implementation_split(
9152 &mut self,
9153 _: &GoToImplementationSplit,
9154 cx: &mut ViewContext<Self>,
9155 ) -> Task<Result<Navigated>> {
9156 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9157 }
9158
9159 pub fn go_to_type_definition(
9160 &mut self,
9161 _: &GoToTypeDefinition,
9162 cx: &mut ViewContext<Self>,
9163 ) -> Task<Result<Navigated>> {
9164 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9165 }
9166
9167 pub fn go_to_definition_split(
9168 &mut self,
9169 _: &GoToDefinitionSplit,
9170 cx: &mut ViewContext<Self>,
9171 ) -> Task<Result<Navigated>> {
9172 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9173 }
9174
9175 pub fn go_to_type_definition_split(
9176 &mut self,
9177 _: &GoToTypeDefinitionSplit,
9178 cx: &mut ViewContext<Self>,
9179 ) -> Task<Result<Navigated>> {
9180 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9181 }
9182
9183 fn go_to_definition_of_kind(
9184 &mut self,
9185 kind: GotoDefinitionKind,
9186 split: bool,
9187 cx: &mut ViewContext<Self>,
9188 ) -> Task<Result<Navigated>> {
9189 let Some(workspace) = self.workspace() else {
9190 return Task::ready(Ok(Navigated::No));
9191 };
9192 let buffer = self.buffer.read(cx);
9193 let head = self.selections.newest::<usize>(cx).head();
9194 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9195 text_anchor
9196 } else {
9197 return Task::ready(Ok(Navigated::No));
9198 };
9199
9200 let project = workspace.read(cx).project().clone();
9201 let definitions = project.update(cx, |project, cx| match kind {
9202 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
9203 GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
9204 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
9205 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
9206 });
9207
9208 cx.spawn(|editor, mut cx| async move {
9209 let definitions = definitions.await?;
9210 let navigated = editor
9211 .update(&mut cx, |editor, cx| {
9212 editor.navigate_to_hover_links(
9213 Some(kind),
9214 definitions
9215 .into_iter()
9216 .filter(|location| {
9217 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9218 })
9219 .map(HoverLink::Text)
9220 .collect::<Vec<_>>(),
9221 split,
9222 cx,
9223 )
9224 })?
9225 .await?;
9226 anyhow::Ok(navigated)
9227 })
9228 }
9229
9230 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9231 let position = self.selections.newest_anchor().head();
9232 let Some((buffer, buffer_position)) =
9233 self.buffer.read(cx).text_anchor_for_position(position, cx)
9234 else {
9235 return;
9236 };
9237
9238 cx.spawn(|editor, mut cx| async move {
9239 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9240 editor.update(&mut cx, |_, cx| {
9241 cx.open_url(&url);
9242 })
9243 } else {
9244 Ok(())
9245 }
9246 })
9247 .detach();
9248 }
9249
9250 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9251 let Some(workspace) = self.workspace() else {
9252 return;
9253 };
9254
9255 let position = self.selections.newest_anchor().head();
9256
9257 let Some((buffer, buffer_position)) =
9258 self.buffer.read(cx).text_anchor_for_position(position, cx)
9259 else {
9260 return;
9261 };
9262
9263 let Some(project) = self.project.clone() else {
9264 return;
9265 };
9266
9267 cx.spawn(|_, mut cx| async move {
9268 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9269
9270 if let Some((_, path)) = result {
9271 workspace
9272 .update(&mut cx, |workspace, cx| {
9273 workspace.open_resolved_path(path, cx)
9274 })?
9275 .await?;
9276 }
9277 anyhow::Ok(())
9278 })
9279 .detach();
9280 }
9281
9282 pub(crate) fn navigate_to_hover_links(
9283 &mut self,
9284 kind: Option<GotoDefinitionKind>,
9285 mut definitions: Vec<HoverLink>,
9286 split: bool,
9287 cx: &mut ViewContext<Editor>,
9288 ) -> Task<Result<Navigated>> {
9289 // If there is one definition, just open it directly
9290 if definitions.len() == 1 {
9291 let definition = definitions.pop().unwrap();
9292
9293 enum TargetTaskResult {
9294 Location(Option<Location>),
9295 AlreadyNavigated,
9296 }
9297
9298 let target_task = match definition {
9299 HoverLink::Text(link) => {
9300 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9301 }
9302 HoverLink::InlayHint(lsp_location, server_id) => {
9303 let computation = self.compute_target_location(lsp_location, server_id, cx);
9304 cx.background_executor().spawn(async move {
9305 let location = computation.await?;
9306 Ok(TargetTaskResult::Location(location))
9307 })
9308 }
9309 HoverLink::Url(url) => {
9310 cx.open_url(&url);
9311 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9312 }
9313 HoverLink::File(path) => {
9314 if let Some(workspace) = self.workspace() {
9315 cx.spawn(|_, mut cx| async move {
9316 workspace
9317 .update(&mut cx, |workspace, cx| {
9318 workspace.open_resolved_path(path, cx)
9319 })?
9320 .await
9321 .map(|_| TargetTaskResult::AlreadyNavigated)
9322 })
9323 } else {
9324 Task::ready(Ok(TargetTaskResult::Location(None)))
9325 }
9326 }
9327 };
9328 cx.spawn(|editor, mut cx| async move {
9329 let target = match target_task.await.context("target resolution task")? {
9330 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9331 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9332 TargetTaskResult::Location(Some(target)) => target,
9333 };
9334
9335 editor.update(&mut cx, |editor, cx| {
9336 let Some(workspace) = editor.workspace() else {
9337 return Navigated::No;
9338 };
9339 let pane = workspace.read(cx).active_pane().clone();
9340
9341 let range = target.range.to_offset(target.buffer.read(cx));
9342 let range = editor.range_for_match(&range);
9343
9344 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9345 let buffer = target.buffer.read(cx);
9346 let range = check_multiline_range(buffer, range);
9347 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
9348 s.select_ranges([range]);
9349 });
9350 } else {
9351 cx.window_context().defer(move |cx| {
9352 let target_editor: View<Self> =
9353 workspace.update(cx, |workspace, cx| {
9354 let pane = if split {
9355 workspace.adjacent_pane(cx)
9356 } else {
9357 workspace.active_pane().clone()
9358 };
9359
9360 workspace.open_project_item(
9361 pane,
9362 target.buffer.clone(),
9363 true,
9364 true,
9365 cx,
9366 )
9367 });
9368 target_editor.update(cx, |target_editor, cx| {
9369 // When selecting a definition in a different buffer, disable the nav history
9370 // to avoid creating a history entry at the previous cursor location.
9371 pane.update(cx, |pane, _| pane.disable_history());
9372 let buffer = target.buffer.read(cx);
9373 let range = check_multiline_range(buffer, range);
9374 target_editor.change_selections(
9375 Some(Autoscroll::focused()),
9376 cx,
9377 |s| {
9378 s.select_ranges([range]);
9379 },
9380 );
9381 pane.update(cx, |pane, _| pane.enable_history());
9382 });
9383 });
9384 }
9385 Navigated::Yes
9386 })
9387 })
9388 } else if !definitions.is_empty() {
9389 let replica_id = self.replica_id(cx);
9390 cx.spawn(|editor, mut cx| async move {
9391 let (title, location_tasks, workspace) = editor
9392 .update(&mut cx, |editor, cx| {
9393 let tab_kind = match kind {
9394 Some(GotoDefinitionKind::Implementation) => "Implementations",
9395 _ => "Definitions",
9396 };
9397 let title = definitions
9398 .iter()
9399 .find_map(|definition| match definition {
9400 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9401 let buffer = origin.buffer.read(cx);
9402 format!(
9403 "{} for {}",
9404 tab_kind,
9405 buffer
9406 .text_for_range(origin.range.clone())
9407 .collect::<String>()
9408 )
9409 }),
9410 HoverLink::InlayHint(_, _) => None,
9411 HoverLink::Url(_) => None,
9412 HoverLink::File(_) => None,
9413 })
9414 .unwrap_or(tab_kind.to_string());
9415 let location_tasks = definitions
9416 .into_iter()
9417 .map(|definition| match definition {
9418 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9419 HoverLink::InlayHint(lsp_location, server_id) => {
9420 editor.compute_target_location(lsp_location, server_id, cx)
9421 }
9422 HoverLink::Url(_) => Task::ready(Ok(None)),
9423 HoverLink::File(_) => Task::ready(Ok(None)),
9424 })
9425 .collect::<Vec<_>>();
9426 (title, location_tasks, editor.workspace().clone())
9427 })
9428 .context("location tasks preparation")?;
9429
9430 let locations = futures::future::join_all(location_tasks)
9431 .await
9432 .into_iter()
9433 .filter_map(|location| location.transpose())
9434 .collect::<Result<_>>()
9435 .context("location tasks")?;
9436
9437 let Some(workspace) = workspace else {
9438 return Ok(Navigated::No);
9439 };
9440 let opened = workspace
9441 .update(&mut cx, |workspace, cx| {
9442 Self::open_locations_in_multibuffer(
9443 workspace, locations, replica_id, title, split, cx,
9444 )
9445 })
9446 .ok();
9447
9448 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9449 })
9450 } else {
9451 Task::ready(Ok(Navigated::No))
9452 }
9453 }
9454
9455 fn compute_target_location(
9456 &self,
9457 lsp_location: lsp::Location,
9458 server_id: LanguageServerId,
9459 cx: &mut ViewContext<Editor>,
9460 ) -> Task<anyhow::Result<Option<Location>>> {
9461 let Some(project) = self.project.clone() else {
9462 return Task::Ready(Some(Ok(None)));
9463 };
9464
9465 cx.spawn(move |editor, mut cx| async move {
9466 let location_task = editor.update(&mut cx, |editor, cx| {
9467 project.update(cx, |project, cx| {
9468 let language_server_name =
9469 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9470 project
9471 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9472 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9473 });
9474 language_server_name.map(|language_server_name| {
9475 project.open_local_buffer_via_lsp(
9476 lsp_location.uri.clone(),
9477 server_id,
9478 language_server_name,
9479 cx,
9480 )
9481 })
9482 })
9483 })?;
9484 let location = match location_task {
9485 Some(task) => Some({
9486 let target_buffer_handle = task.await.context("open local buffer")?;
9487 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9488 let target_start = target_buffer
9489 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9490 let target_end = target_buffer
9491 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9492 target_buffer.anchor_after(target_start)
9493 ..target_buffer.anchor_before(target_end)
9494 })?;
9495 Location {
9496 buffer: target_buffer_handle,
9497 range,
9498 }
9499 }),
9500 None => None,
9501 };
9502 Ok(location)
9503 })
9504 }
9505
9506 pub fn find_all_references(
9507 &mut self,
9508 _: &FindAllReferences,
9509 cx: &mut ViewContext<Self>,
9510 ) -> Option<Task<Result<Navigated>>> {
9511 let multi_buffer = self.buffer.read(cx);
9512 let selection = self.selections.newest::<usize>(cx);
9513 let head = selection.head();
9514
9515 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9516 let head_anchor = multi_buffer_snapshot.anchor_at(
9517 head,
9518 if head < selection.tail() {
9519 Bias::Right
9520 } else {
9521 Bias::Left
9522 },
9523 );
9524
9525 match self
9526 .find_all_references_task_sources
9527 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9528 {
9529 Ok(_) => {
9530 log::info!(
9531 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9532 );
9533 return None;
9534 }
9535 Err(i) => {
9536 self.find_all_references_task_sources.insert(i, head_anchor);
9537 }
9538 }
9539
9540 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9541 let replica_id = self.replica_id(cx);
9542 let workspace = self.workspace()?;
9543 let project = workspace.read(cx).project().clone();
9544 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9545 Some(cx.spawn(|editor, mut cx| async move {
9546 let _cleanup = defer({
9547 let mut cx = cx.clone();
9548 move || {
9549 let _ = editor.update(&mut cx, |editor, _| {
9550 if let Ok(i) =
9551 editor
9552 .find_all_references_task_sources
9553 .binary_search_by(|anchor| {
9554 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9555 })
9556 {
9557 editor.find_all_references_task_sources.remove(i);
9558 }
9559 });
9560 }
9561 });
9562
9563 let locations = references.await?;
9564 if locations.is_empty() {
9565 return anyhow::Ok(Navigated::No);
9566 }
9567
9568 workspace.update(&mut cx, |workspace, cx| {
9569 let title = locations
9570 .first()
9571 .as_ref()
9572 .map(|location| {
9573 let buffer = location.buffer.read(cx);
9574 format!(
9575 "References to `{}`",
9576 buffer
9577 .text_for_range(location.range.clone())
9578 .collect::<String>()
9579 )
9580 })
9581 .unwrap();
9582 Self::open_locations_in_multibuffer(
9583 workspace, locations, replica_id, title, false, cx,
9584 );
9585 Navigated::Yes
9586 })
9587 }))
9588 }
9589
9590 /// Opens a multibuffer with the given project locations in it
9591 pub fn open_locations_in_multibuffer(
9592 workspace: &mut Workspace,
9593 mut locations: Vec<Location>,
9594 replica_id: ReplicaId,
9595 title: String,
9596 split: bool,
9597 cx: &mut ViewContext<Workspace>,
9598 ) {
9599 // If there are multiple definitions, open them in a multibuffer
9600 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9601 let mut locations = locations.into_iter().peekable();
9602 let mut ranges_to_highlight = Vec::new();
9603 let capability = workspace.project().read(cx).capability();
9604
9605 let excerpt_buffer = cx.new_model(|cx| {
9606 let mut multibuffer = MultiBuffer::new(replica_id, capability);
9607 while let Some(location) = locations.next() {
9608 let buffer = location.buffer.read(cx);
9609 let mut ranges_for_buffer = Vec::new();
9610 let range = location.range.to_offset(buffer);
9611 ranges_for_buffer.push(range.clone());
9612
9613 while let Some(next_location) = locations.peek() {
9614 if next_location.buffer == location.buffer {
9615 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9616 locations.next();
9617 } else {
9618 break;
9619 }
9620 }
9621
9622 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9623 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9624 location.buffer.clone(),
9625 ranges_for_buffer,
9626 DEFAULT_MULTIBUFFER_CONTEXT,
9627 cx,
9628 ))
9629 }
9630
9631 multibuffer.with_title(title)
9632 });
9633
9634 let editor = cx.new_view(|cx| {
9635 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9636 });
9637 editor.update(cx, |editor, cx| {
9638 if let Some(first_range) = ranges_to_highlight.first() {
9639 editor.change_selections(None, cx, |selections| {
9640 selections.clear_disjoint();
9641 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9642 });
9643 }
9644 editor.highlight_background::<Self>(
9645 &ranges_to_highlight,
9646 |theme| theme.editor_highlighted_line_background,
9647 cx,
9648 );
9649 });
9650
9651 let item = Box::new(editor);
9652 let item_id = item.item_id();
9653
9654 if split {
9655 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9656 } else {
9657 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9658 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9659 pane.close_current_preview_item(cx)
9660 } else {
9661 None
9662 }
9663 });
9664 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9665 }
9666 workspace.active_pane().update(cx, |pane, cx| {
9667 pane.set_preview_item_id(Some(item_id), cx);
9668 });
9669 }
9670
9671 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9672 use language::ToOffset as _;
9673
9674 let project = self.project.clone()?;
9675 let selection = self.selections.newest_anchor().clone();
9676 let (cursor_buffer, cursor_buffer_position) = self
9677 .buffer
9678 .read(cx)
9679 .text_anchor_for_position(selection.head(), cx)?;
9680 let (tail_buffer, cursor_buffer_position_end) = self
9681 .buffer
9682 .read(cx)
9683 .text_anchor_for_position(selection.tail(), cx)?;
9684 if tail_buffer != cursor_buffer {
9685 return None;
9686 }
9687
9688 let snapshot = cursor_buffer.read(cx).snapshot();
9689 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9690 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9691 let prepare_rename = project.update(cx, |project, cx| {
9692 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
9693 });
9694 drop(snapshot);
9695
9696 Some(cx.spawn(|this, mut cx| async move {
9697 let rename_range = if let Some(range) = prepare_rename.await? {
9698 Some(range)
9699 } else {
9700 this.update(&mut cx, |this, cx| {
9701 let buffer = this.buffer.read(cx).snapshot(cx);
9702 let mut buffer_highlights = this
9703 .document_highlights_for_position(selection.head(), &buffer)
9704 .filter(|highlight| {
9705 highlight.start.excerpt_id == selection.head().excerpt_id
9706 && highlight.end.excerpt_id == selection.head().excerpt_id
9707 });
9708 buffer_highlights
9709 .next()
9710 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9711 })?
9712 };
9713 if let Some(rename_range) = rename_range {
9714 this.update(&mut cx, |this, cx| {
9715 let snapshot = cursor_buffer.read(cx).snapshot();
9716 let rename_buffer_range = rename_range.to_offset(&snapshot);
9717 let cursor_offset_in_rename_range =
9718 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9719 let cursor_offset_in_rename_range_end =
9720 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9721
9722 this.take_rename(false, cx);
9723 let buffer = this.buffer.read(cx).read(cx);
9724 let cursor_offset = selection.head().to_offset(&buffer);
9725 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9726 let rename_end = rename_start + rename_buffer_range.len();
9727 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9728 let mut old_highlight_id = None;
9729 let old_name: Arc<str> = buffer
9730 .chunks(rename_start..rename_end, true)
9731 .map(|chunk| {
9732 if old_highlight_id.is_none() {
9733 old_highlight_id = chunk.syntax_highlight_id;
9734 }
9735 chunk.text
9736 })
9737 .collect::<String>()
9738 .into();
9739
9740 drop(buffer);
9741
9742 // Position the selection in the rename editor so that it matches the current selection.
9743 this.show_local_selections = false;
9744 let rename_editor = cx.new_view(|cx| {
9745 let mut editor = Editor::single_line(cx);
9746 editor.buffer.update(cx, |buffer, cx| {
9747 buffer.edit([(0..0, old_name.clone())], None, cx)
9748 });
9749 let rename_selection_range = match cursor_offset_in_rename_range
9750 .cmp(&cursor_offset_in_rename_range_end)
9751 {
9752 Ordering::Equal => {
9753 editor.select_all(&SelectAll, cx);
9754 return editor;
9755 }
9756 Ordering::Less => {
9757 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9758 }
9759 Ordering::Greater => {
9760 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9761 }
9762 };
9763 if rename_selection_range.end > old_name.len() {
9764 editor.select_all(&SelectAll, cx);
9765 } else {
9766 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9767 s.select_ranges([rename_selection_range]);
9768 });
9769 }
9770 editor
9771 });
9772 cx.subscribe(&rename_editor, |_, _, e, cx| match e {
9773 EditorEvent::Focused => cx.emit(EditorEvent::FocusedIn),
9774 _ => {}
9775 })
9776 .detach();
9777
9778 let write_highlights =
9779 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
9780 let read_highlights =
9781 this.clear_background_highlights::<DocumentHighlightRead>(cx);
9782 let ranges = write_highlights
9783 .iter()
9784 .flat_map(|(_, ranges)| ranges.iter())
9785 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
9786 .cloned()
9787 .collect();
9788
9789 this.highlight_text::<Rename>(
9790 ranges,
9791 HighlightStyle {
9792 fade_out: Some(0.6),
9793 ..Default::default()
9794 },
9795 cx,
9796 );
9797 let rename_focus_handle = rename_editor.focus_handle(cx);
9798 cx.focus(&rename_focus_handle);
9799 let block_id = this.insert_blocks(
9800 [BlockProperties {
9801 style: BlockStyle::Flex,
9802 position: range.start,
9803 height: 1,
9804 render: Box::new({
9805 let rename_editor = rename_editor.clone();
9806 move |cx: &mut BlockContext| {
9807 let mut text_style = cx.editor_style.text.clone();
9808 if let Some(highlight_style) = old_highlight_id
9809 .and_then(|h| h.style(&cx.editor_style.syntax))
9810 {
9811 text_style = text_style.highlight(highlight_style);
9812 }
9813 div()
9814 .pl(cx.anchor_x)
9815 .child(EditorElement::new(
9816 &rename_editor,
9817 EditorStyle {
9818 background: cx.theme().system().transparent,
9819 local_player: cx.editor_style.local_player,
9820 text: text_style,
9821 scrollbar_width: cx.editor_style.scrollbar_width,
9822 syntax: cx.editor_style.syntax.clone(),
9823 status: cx.editor_style.status.clone(),
9824 inlay_hints_style: HighlightStyle {
9825 color: Some(cx.theme().status().hint),
9826 font_weight: Some(FontWeight::BOLD),
9827 ..HighlightStyle::default()
9828 },
9829 suggestions_style: HighlightStyle {
9830 color: Some(cx.theme().status().predictive),
9831 ..HighlightStyle::default()
9832 },
9833 ..EditorStyle::default()
9834 },
9835 ))
9836 .into_any_element()
9837 }
9838 }),
9839 disposition: BlockDisposition::Below,
9840 priority: 0,
9841 }],
9842 Some(Autoscroll::fit()),
9843 cx,
9844 )[0];
9845 this.pending_rename = Some(RenameState {
9846 range,
9847 old_name,
9848 editor: rename_editor,
9849 block_id,
9850 });
9851 })?;
9852 }
9853
9854 Ok(())
9855 }))
9856 }
9857
9858 pub fn confirm_rename(
9859 &mut self,
9860 _: &ConfirmRename,
9861 cx: &mut ViewContext<Self>,
9862 ) -> Option<Task<Result<()>>> {
9863 let rename = self.take_rename(false, cx)?;
9864 let workspace = self.workspace()?;
9865 let (start_buffer, start) = self
9866 .buffer
9867 .read(cx)
9868 .text_anchor_for_position(rename.range.start, cx)?;
9869 let (end_buffer, end) = self
9870 .buffer
9871 .read(cx)
9872 .text_anchor_for_position(rename.range.end, cx)?;
9873 if start_buffer != end_buffer {
9874 return None;
9875 }
9876
9877 let buffer = start_buffer;
9878 let range = start..end;
9879 let old_name = rename.old_name;
9880 let new_name = rename.editor.read(cx).text(cx);
9881
9882 let rename = workspace
9883 .read(cx)
9884 .project()
9885 .clone()
9886 .update(cx, |project, cx| {
9887 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
9888 });
9889 let workspace = workspace.downgrade();
9890
9891 Some(cx.spawn(|editor, mut cx| async move {
9892 let project_transaction = rename.await?;
9893 Self::open_project_transaction(
9894 &editor,
9895 workspace,
9896 project_transaction,
9897 format!("Rename: {} → {}", old_name, new_name),
9898 cx.clone(),
9899 )
9900 .await?;
9901
9902 editor.update(&mut cx, |editor, cx| {
9903 editor.refresh_document_highlights(cx);
9904 })?;
9905 Ok(())
9906 }))
9907 }
9908
9909 fn take_rename(
9910 &mut self,
9911 moving_cursor: bool,
9912 cx: &mut ViewContext<Self>,
9913 ) -> Option<RenameState> {
9914 let rename = self.pending_rename.take()?;
9915 if rename.editor.focus_handle(cx).is_focused(cx) {
9916 cx.focus(&self.focus_handle);
9917 }
9918
9919 self.remove_blocks(
9920 [rename.block_id].into_iter().collect(),
9921 Some(Autoscroll::fit()),
9922 cx,
9923 );
9924 self.clear_highlights::<Rename>(cx);
9925 self.show_local_selections = true;
9926
9927 if moving_cursor {
9928 let rename_editor = rename.editor.read(cx);
9929 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
9930
9931 // Update the selection to match the position of the selection inside
9932 // the rename editor.
9933 let snapshot = self.buffer.read(cx).read(cx);
9934 let rename_range = rename.range.to_offset(&snapshot);
9935 let cursor_in_editor = snapshot
9936 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
9937 .min(rename_range.end);
9938 drop(snapshot);
9939
9940 self.change_selections(None, cx, |s| {
9941 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
9942 });
9943 } else {
9944 self.refresh_document_highlights(cx);
9945 }
9946
9947 Some(rename)
9948 }
9949
9950 pub fn pending_rename(&self) -> Option<&RenameState> {
9951 self.pending_rename.as_ref()
9952 }
9953
9954 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9955 let project = match &self.project {
9956 Some(project) => project.clone(),
9957 None => return None,
9958 };
9959
9960 Some(self.perform_format(project, FormatTrigger::Manual, cx))
9961 }
9962
9963 fn perform_format(
9964 &mut self,
9965 project: Model<Project>,
9966 trigger: FormatTrigger,
9967 cx: &mut ViewContext<Self>,
9968 ) -> Task<Result<()>> {
9969 let buffer = self.buffer().clone();
9970 let mut buffers = buffer.read(cx).all_buffers();
9971 if trigger == FormatTrigger::Save {
9972 buffers.retain(|buffer| buffer.read(cx).is_dirty());
9973 }
9974
9975 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
9976 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
9977
9978 cx.spawn(|_, mut cx| async move {
9979 let transaction = futures::select_biased! {
9980 () = timeout => {
9981 log::warn!("timed out waiting for formatting");
9982 None
9983 }
9984 transaction = format.log_err().fuse() => transaction,
9985 };
9986
9987 buffer
9988 .update(&mut cx, |buffer, cx| {
9989 if let Some(transaction) = transaction {
9990 if !buffer.is_singleton() {
9991 buffer.push_transaction(&transaction.0, cx);
9992 }
9993 }
9994
9995 cx.notify();
9996 })
9997 .ok();
9998
9999 Ok(())
10000 })
10001 }
10002
10003 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10004 if let Some(project) = self.project.clone() {
10005 self.buffer.update(cx, |multi_buffer, cx| {
10006 project.update(cx, |project, cx| {
10007 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10008 });
10009 })
10010 }
10011 }
10012
10013 fn cancel_language_server_work(
10014 &mut self,
10015 _: &CancelLanguageServerWork,
10016 cx: &mut ViewContext<Self>,
10017 ) {
10018 if let Some(project) = self.project.clone() {
10019 self.buffer.update(cx, |multi_buffer, cx| {
10020 project.update(cx, |project, cx| {
10021 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10022 });
10023 })
10024 }
10025 }
10026
10027 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10028 cx.show_character_palette();
10029 }
10030
10031 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10032 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10033 let buffer = self.buffer.read(cx).snapshot(cx);
10034 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10035 let is_valid = buffer
10036 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10037 .any(|entry| {
10038 entry.diagnostic.is_primary
10039 && !entry.range.is_empty()
10040 && entry.range.start == primary_range_start
10041 && entry.diagnostic.message == active_diagnostics.primary_message
10042 });
10043
10044 if is_valid != active_diagnostics.is_valid {
10045 active_diagnostics.is_valid = is_valid;
10046 let mut new_styles = HashMap::default();
10047 for (block_id, diagnostic) in &active_diagnostics.blocks {
10048 new_styles.insert(
10049 *block_id,
10050 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10051 );
10052 }
10053 self.display_map.update(cx, |display_map, _cx| {
10054 display_map.replace_blocks(new_styles)
10055 });
10056 }
10057 }
10058 }
10059
10060 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10061 self.dismiss_diagnostics(cx);
10062 let snapshot = self.snapshot(cx);
10063 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10064 let buffer = self.buffer.read(cx).snapshot(cx);
10065
10066 let mut primary_range = None;
10067 let mut primary_message = None;
10068 let mut group_end = Point::zero();
10069 let diagnostic_group = buffer
10070 .diagnostic_group::<MultiBufferPoint>(group_id)
10071 .filter_map(|entry| {
10072 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10073 && (entry.range.start.row == entry.range.end.row
10074 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10075 {
10076 return None;
10077 }
10078 if entry.range.end > group_end {
10079 group_end = entry.range.end;
10080 }
10081 if entry.diagnostic.is_primary {
10082 primary_range = Some(entry.range.clone());
10083 primary_message = Some(entry.diagnostic.message.clone());
10084 }
10085 Some(entry)
10086 })
10087 .collect::<Vec<_>>();
10088 let primary_range = primary_range?;
10089 let primary_message = primary_message?;
10090 let primary_range =
10091 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10092
10093 let blocks = display_map
10094 .insert_blocks(
10095 diagnostic_group.iter().map(|entry| {
10096 let diagnostic = entry.diagnostic.clone();
10097 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10098 BlockProperties {
10099 style: BlockStyle::Fixed,
10100 position: buffer.anchor_after(entry.range.start),
10101 height: message_height,
10102 render: diagnostic_block_renderer(diagnostic, None, true, true),
10103 disposition: BlockDisposition::Below,
10104 priority: 0,
10105 }
10106 }),
10107 cx,
10108 )
10109 .into_iter()
10110 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10111 .collect();
10112
10113 Some(ActiveDiagnosticGroup {
10114 primary_range,
10115 primary_message,
10116 group_id,
10117 blocks,
10118 is_valid: true,
10119 })
10120 });
10121 self.active_diagnostics.is_some()
10122 }
10123
10124 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10125 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10126 self.display_map.update(cx, |display_map, cx| {
10127 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10128 });
10129 cx.notify();
10130 }
10131 }
10132
10133 pub fn set_selections_from_remote(
10134 &mut self,
10135 selections: Vec<Selection<Anchor>>,
10136 pending_selection: Option<Selection<Anchor>>,
10137 cx: &mut ViewContext<Self>,
10138 ) {
10139 let old_cursor_position = self.selections.newest_anchor().head();
10140 self.selections.change_with(cx, |s| {
10141 s.select_anchors(selections);
10142 if let Some(pending_selection) = pending_selection {
10143 s.set_pending(pending_selection, SelectMode::Character);
10144 } else {
10145 s.clear_pending();
10146 }
10147 });
10148 self.selections_did_change(false, &old_cursor_position, true, cx);
10149 }
10150
10151 fn push_to_selection_history(&mut self) {
10152 self.selection_history.push(SelectionHistoryEntry {
10153 selections: self.selections.disjoint_anchors(),
10154 select_next_state: self.select_next_state.clone(),
10155 select_prev_state: self.select_prev_state.clone(),
10156 add_selections_state: self.add_selections_state.clone(),
10157 });
10158 }
10159
10160 pub fn transact(
10161 &mut self,
10162 cx: &mut ViewContext<Self>,
10163 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10164 ) -> Option<TransactionId> {
10165 self.start_transaction_at(Instant::now(), cx);
10166 update(self, cx);
10167 self.end_transaction_at(Instant::now(), cx)
10168 }
10169
10170 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10171 self.end_selection(cx);
10172 if let Some(tx_id) = self
10173 .buffer
10174 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10175 {
10176 self.selection_history
10177 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10178 cx.emit(EditorEvent::TransactionBegun {
10179 transaction_id: tx_id,
10180 })
10181 }
10182 }
10183
10184 fn end_transaction_at(
10185 &mut self,
10186 now: Instant,
10187 cx: &mut ViewContext<Self>,
10188 ) -> Option<TransactionId> {
10189 if let Some(transaction_id) = self
10190 .buffer
10191 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10192 {
10193 if let Some((_, end_selections)) =
10194 self.selection_history.transaction_mut(transaction_id)
10195 {
10196 *end_selections = Some(self.selections.disjoint_anchors());
10197 } else {
10198 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10199 }
10200
10201 cx.emit(EditorEvent::Edited { transaction_id });
10202 Some(transaction_id)
10203 } else {
10204 None
10205 }
10206 }
10207
10208 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10209 let mut fold_ranges = Vec::new();
10210
10211 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10212
10213 let selections = self.selections.all_adjusted(cx);
10214 for selection in selections {
10215 let range = selection.range().sorted();
10216 let buffer_start_row = range.start.row;
10217
10218 for row in (0..=range.end.row).rev() {
10219 if let Some((foldable_range, fold_text)) =
10220 display_map.foldable_range(MultiBufferRow(row))
10221 {
10222 if foldable_range.end.row >= buffer_start_row {
10223 fold_ranges.push((foldable_range, fold_text));
10224 if row <= range.start.row {
10225 break;
10226 }
10227 }
10228 }
10229 }
10230 }
10231
10232 self.fold_ranges(fold_ranges, true, cx);
10233 }
10234
10235 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10236 let buffer_row = fold_at.buffer_row;
10237 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10238
10239 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10240 let autoscroll = self
10241 .selections
10242 .all::<Point>(cx)
10243 .iter()
10244 .any(|selection| fold_range.overlaps(&selection.range()));
10245
10246 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10247 }
10248 }
10249
10250 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10251 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10252 let buffer = &display_map.buffer_snapshot;
10253 let selections = self.selections.all::<Point>(cx);
10254 let ranges = selections
10255 .iter()
10256 .map(|s| {
10257 let range = s.display_range(&display_map).sorted();
10258 let mut start = range.start.to_point(&display_map);
10259 let mut end = range.end.to_point(&display_map);
10260 start.column = 0;
10261 end.column = buffer.line_len(MultiBufferRow(end.row));
10262 start..end
10263 })
10264 .collect::<Vec<_>>();
10265
10266 self.unfold_ranges(ranges, true, true, cx);
10267 }
10268
10269 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10270 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10271
10272 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10273 ..Point::new(
10274 unfold_at.buffer_row.0,
10275 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10276 );
10277
10278 let autoscroll = self
10279 .selections
10280 .all::<Point>(cx)
10281 .iter()
10282 .any(|selection| selection.range().overlaps(&intersection_range));
10283
10284 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10285 }
10286
10287 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10288 let selections = self.selections.all::<Point>(cx);
10289 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10290 let line_mode = self.selections.line_mode;
10291 let ranges = selections.into_iter().map(|s| {
10292 if line_mode {
10293 let start = Point::new(s.start.row, 0);
10294 let end = Point::new(
10295 s.end.row,
10296 display_map
10297 .buffer_snapshot
10298 .line_len(MultiBufferRow(s.end.row)),
10299 );
10300 (start..end, display_map.fold_placeholder.clone())
10301 } else {
10302 (s.start..s.end, display_map.fold_placeholder.clone())
10303 }
10304 });
10305 self.fold_ranges(ranges, true, cx);
10306 }
10307
10308 pub fn fold_ranges<T: ToOffset + Clone>(
10309 &mut self,
10310 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10311 auto_scroll: bool,
10312 cx: &mut ViewContext<Self>,
10313 ) {
10314 let mut fold_ranges = Vec::new();
10315 let mut buffers_affected = HashMap::default();
10316 let multi_buffer = self.buffer().read(cx);
10317 for (fold_range, fold_text) in ranges {
10318 if let Some((_, buffer, _)) =
10319 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10320 {
10321 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10322 };
10323 fold_ranges.push((fold_range, fold_text));
10324 }
10325
10326 let mut ranges = fold_ranges.into_iter().peekable();
10327 if ranges.peek().is_some() {
10328 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10329
10330 if auto_scroll {
10331 self.request_autoscroll(Autoscroll::fit(), cx);
10332 }
10333
10334 for buffer in buffers_affected.into_values() {
10335 self.sync_expanded_diff_hunks(buffer, cx);
10336 }
10337
10338 cx.notify();
10339
10340 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10341 // Clear diagnostics block when folding a range that contains it.
10342 let snapshot = self.snapshot(cx);
10343 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10344 drop(snapshot);
10345 self.active_diagnostics = Some(active_diagnostics);
10346 self.dismiss_diagnostics(cx);
10347 } else {
10348 self.active_diagnostics = Some(active_diagnostics);
10349 }
10350 }
10351
10352 self.scrollbar_marker_state.dirty = true;
10353 }
10354 }
10355
10356 pub fn unfold_ranges<T: ToOffset + Clone>(
10357 &mut self,
10358 ranges: impl IntoIterator<Item = Range<T>>,
10359 inclusive: bool,
10360 auto_scroll: bool,
10361 cx: &mut ViewContext<Self>,
10362 ) {
10363 let mut unfold_ranges = Vec::new();
10364 let mut buffers_affected = HashMap::default();
10365 let multi_buffer = self.buffer().read(cx);
10366 for range in ranges {
10367 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10368 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10369 };
10370 unfold_ranges.push(range);
10371 }
10372
10373 let mut ranges = unfold_ranges.into_iter().peekable();
10374 if ranges.peek().is_some() {
10375 self.display_map
10376 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10377 if auto_scroll {
10378 self.request_autoscroll(Autoscroll::fit(), cx);
10379 }
10380
10381 for buffer in buffers_affected.into_values() {
10382 self.sync_expanded_diff_hunks(buffer, cx);
10383 }
10384
10385 cx.notify();
10386 self.scrollbar_marker_state.dirty = true;
10387 self.active_indent_guides_state.dirty = true;
10388 }
10389 }
10390
10391 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10392 self.display_map.read(cx).fold_placeholder.clone()
10393 }
10394
10395 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10396 if hovered != self.gutter_hovered {
10397 self.gutter_hovered = hovered;
10398 cx.notify();
10399 }
10400 }
10401
10402 pub fn insert_blocks(
10403 &mut self,
10404 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10405 autoscroll: Option<Autoscroll>,
10406 cx: &mut ViewContext<Self>,
10407 ) -> Vec<CustomBlockId> {
10408 let blocks = self
10409 .display_map
10410 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10411 if let Some(autoscroll) = autoscroll {
10412 self.request_autoscroll(autoscroll, cx);
10413 }
10414 cx.notify();
10415 blocks
10416 }
10417
10418 pub fn resize_blocks(
10419 &mut self,
10420 heights: HashMap<CustomBlockId, u32>,
10421 autoscroll: Option<Autoscroll>,
10422 cx: &mut ViewContext<Self>,
10423 ) {
10424 self.display_map
10425 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10426 if let Some(autoscroll) = autoscroll {
10427 self.request_autoscroll(autoscroll, cx);
10428 }
10429 cx.notify();
10430 }
10431
10432 pub fn replace_blocks(
10433 &mut self,
10434 renderers: HashMap<CustomBlockId, RenderBlock>,
10435 autoscroll: Option<Autoscroll>,
10436 cx: &mut ViewContext<Self>,
10437 ) {
10438 self.display_map
10439 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10440 if let Some(autoscroll) = autoscroll {
10441 self.request_autoscroll(autoscroll, cx);
10442 }
10443 cx.notify();
10444 }
10445
10446 pub fn remove_blocks(
10447 &mut self,
10448 block_ids: HashSet<CustomBlockId>,
10449 autoscroll: Option<Autoscroll>,
10450 cx: &mut ViewContext<Self>,
10451 ) {
10452 self.display_map.update(cx, |display_map, cx| {
10453 display_map.remove_blocks(block_ids, cx)
10454 });
10455 if let Some(autoscroll) = autoscroll {
10456 self.request_autoscroll(autoscroll, cx);
10457 }
10458 cx.notify();
10459 }
10460
10461 pub fn row_for_block(
10462 &self,
10463 block_id: CustomBlockId,
10464 cx: &mut ViewContext<Self>,
10465 ) -> Option<DisplayRow> {
10466 self.display_map
10467 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10468 }
10469
10470 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10471 self.focused_block = Some(focused_block);
10472 }
10473
10474 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10475 self.focused_block.take()
10476 }
10477
10478 pub fn insert_creases(
10479 &mut self,
10480 creases: impl IntoIterator<Item = Crease>,
10481 cx: &mut ViewContext<Self>,
10482 ) -> Vec<CreaseId> {
10483 self.display_map
10484 .update(cx, |map, cx| map.insert_creases(creases, cx))
10485 }
10486
10487 pub fn remove_creases(
10488 &mut self,
10489 ids: impl IntoIterator<Item = CreaseId>,
10490 cx: &mut ViewContext<Self>,
10491 ) {
10492 self.display_map
10493 .update(cx, |map, cx| map.remove_creases(ids, cx));
10494 }
10495
10496 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10497 self.display_map
10498 .update(cx, |map, cx| map.snapshot(cx))
10499 .longest_row()
10500 }
10501
10502 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10503 self.display_map
10504 .update(cx, |map, cx| map.snapshot(cx))
10505 .max_point()
10506 }
10507
10508 pub fn text(&self, cx: &AppContext) -> String {
10509 self.buffer.read(cx).read(cx).text()
10510 }
10511
10512 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10513 let text = self.text(cx);
10514 let text = text.trim();
10515
10516 if text.is_empty() {
10517 return None;
10518 }
10519
10520 Some(text.to_string())
10521 }
10522
10523 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10524 self.transact(cx, |this, cx| {
10525 this.buffer
10526 .read(cx)
10527 .as_singleton()
10528 .expect("you can only call set_text on editors for singleton buffers")
10529 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10530 });
10531 }
10532
10533 pub fn display_text(&self, cx: &mut AppContext) -> String {
10534 self.display_map
10535 .update(cx, |map, cx| map.snapshot(cx))
10536 .text()
10537 }
10538
10539 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10540 let mut wrap_guides = smallvec::smallvec![];
10541
10542 if self.show_wrap_guides == Some(false) {
10543 return wrap_guides;
10544 }
10545
10546 let settings = self.buffer.read(cx).settings_at(0, cx);
10547 if settings.show_wrap_guides {
10548 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10549 wrap_guides.push((soft_wrap as usize, true));
10550 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
10551 wrap_guides.push((soft_wrap as usize, true));
10552 }
10553 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10554 }
10555
10556 wrap_guides
10557 }
10558
10559 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10560 let settings = self.buffer.read(cx).settings_at(0, cx);
10561 let mode = self
10562 .soft_wrap_mode_override
10563 .unwrap_or_else(|| settings.soft_wrap);
10564 match mode {
10565 language_settings::SoftWrap::None => SoftWrap::None,
10566 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10567 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10568 language_settings::SoftWrap::PreferredLineLength => {
10569 SoftWrap::Column(settings.preferred_line_length)
10570 }
10571 language_settings::SoftWrap::Bounded => {
10572 SoftWrap::Bounded(settings.preferred_line_length)
10573 }
10574 }
10575 }
10576
10577 pub fn set_soft_wrap_mode(
10578 &mut self,
10579 mode: language_settings::SoftWrap,
10580 cx: &mut ViewContext<Self>,
10581 ) {
10582 self.soft_wrap_mode_override = Some(mode);
10583 cx.notify();
10584 }
10585
10586 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10587 let rem_size = cx.rem_size();
10588 self.display_map.update(cx, |map, cx| {
10589 map.set_font(
10590 style.text.font(),
10591 style.text.font_size.to_pixels(rem_size),
10592 cx,
10593 )
10594 });
10595 self.style = Some(style);
10596 }
10597
10598 pub fn style(&self) -> Option<&EditorStyle> {
10599 self.style.as_ref()
10600 }
10601
10602 // Called by the element. This method is not designed to be called outside of the editor
10603 // element's layout code because it does not notify when rewrapping is computed synchronously.
10604 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10605 self.display_map
10606 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10607 }
10608
10609 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10610 if self.soft_wrap_mode_override.is_some() {
10611 self.soft_wrap_mode_override.take();
10612 } else {
10613 let soft_wrap = match self.soft_wrap_mode(cx) {
10614 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10615 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
10616 language_settings::SoftWrap::PreferLine
10617 }
10618 };
10619 self.soft_wrap_mode_override = Some(soft_wrap);
10620 }
10621 cx.notify();
10622 }
10623
10624 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10625 let Some(workspace) = self.workspace() else {
10626 return;
10627 };
10628 let fs = workspace.read(cx).app_state().fs.clone();
10629 let current_show = TabBarSettings::get_global(cx).show;
10630 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10631 setting.show = Some(!current_show);
10632 });
10633 }
10634
10635 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10636 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10637 self.buffer
10638 .read(cx)
10639 .settings_at(0, cx)
10640 .indent_guides
10641 .enabled
10642 });
10643 self.show_indent_guides = Some(!currently_enabled);
10644 cx.notify();
10645 }
10646
10647 fn should_show_indent_guides(&self) -> Option<bool> {
10648 self.show_indent_guides
10649 }
10650
10651 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10652 let mut editor_settings = EditorSettings::get_global(cx).clone();
10653 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10654 EditorSettings::override_global(editor_settings, cx);
10655 }
10656
10657 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
10658 self.use_relative_line_numbers
10659 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
10660 }
10661
10662 pub fn toggle_relative_line_numbers(
10663 &mut self,
10664 _: &ToggleRelativeLineNumbers,
10665 cx: &mut ViewContext<Self>,
10666 ) {
10667 let is_relative = self.should_use_relative_line_numbers(cx);
10668 self.set_relative_line_number(Some(!is_relative), cx)
10669 }
10670
10671 pub fn set_relative_line_number(
10672 &mut self,
10673 is_relative: Option<bool>,
10674 cx: &mut ViewContext<Self>,
10675 ) {
10676 self.use_relative_line_numbers = is_relative;
10677 cx.notify();
10678 }
10679
10680 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10681 self.show_gutter = show_gutter;
10682 cx.notify();
10683 }
10684
10685 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10686 self.show_line_numbers = Some(show_line_numbers);
10687 cx.notify();
10688 }
10689
10690 pub fn set_show_git_diff_gutter(
10691 &mut self,
10692 show_git_diff_gutter: bool,
10693 cx: &mut ViewContext<Self>,
10694 ) {
10695 self.show_git_diff_gutter = Some(show_git_diff_gutter);
10696 cx.notify();
10697 }
10698
10699 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10700 self.show_code_actions = Some(show_code_actions);
10701 cx.notify();
10702 }
10703
10704 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10705 self.show_runnables = Some(show_runnables);
10706 cx.notify();
10707 }
10708
10709 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
10710 if self.display_map.read(cx).masked != masked {
10711 self.display_map.update(cx, |map, _| map.masked = masked);
10712 }
10713 cx.notify()
10714 }
10715
10716 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10717 self.show_wrap_guides = Some(show_wrap_guides);
10718 cx.notify();
10719 }
10720
10721 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10722 self.show_indent_guides = Some(show_indent_guides);
10723 cx.notify();
10724 }
10725
10726 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10727 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10728 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10729 if let Some(dir) = file.abs_path(cx).parent() {
10730 return Some(dir.to_owned());
10731 }
10732 }
10733
10734 if let Some(project_path) = buffer.read(cx).project_path(cx) {
10735 return Some(project_path.path.to_path_buf());
10736 }
10737 }
10738
10739 None
10740 }
10741
10742 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10743 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10744 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10745 cx.reveal_path(&file.abs_path(cx));
10746 }
10747 }
10748 }
10749
10750 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10751 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10752 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10753 if let Some(path) = file.abs_path(cx).to_str() {
10754 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10755 }
10756 }
10757 }
10758 }
10759
10760 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10761 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10762 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10763 if let Some(path) = file.path().to_str() {
10764 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10765 }
10766 }
10767 }
10768 }
10769
10770 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10771 self.show_git_blame_gutter = !self.show_git_blame_gutter;
10772
10773 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10774 self.start_git_blame(true, cx);
10775 }
10776
10777 cx.notify();
10778 }
10779
10780 pub fn toggle_git_blame_inline(
10781 &mut self,
10782 _: &ToggleGitBlameInline,
10783 cx: &mut ViewContext<Self>,
10784 ) {
10785 self.toggle_git_blame_inline_internal(true, cx);
10786 cx.notify();
10787 }
10788
10789 pub fn git_blame_inline_enabled(&self) -> bool {
10790 self.git_blame_inline_enabled
10791 }
10792
10793 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10794 self.show_selection_menu = self
10795 .show_selection_menu
10796 .map(|show_selections_menu| !show_selections_menu)
10797 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10798
10799 cx.notify();
10800 }
10801
10802 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10803 self.show_selection_menu
10804 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10805 }
10806
10807 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10808 if let Some(project) = self.project.as_ref() {
10809 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10810 return;
10811 };
10812
10813 if buffer.read(cx).file().is_none() {
10814 return;
10815 }
10816
10817 let focused = self.focus_handle(cx).contains_focused(cx);
10818
10819 let project = project.clone();
10820 let blame =
10821 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10822 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10823 self.blame = Some(blame);
10824 }
10825 }
10826
10827 fn toggle_git_blame_inline_internal(
10828 &mut self,
10829 user_triggered: bool,
10830 cx: &mut ViewContext<Self>,
10831 ) {
10832 if self.git_blame_inline_enabled {
10833 self.git_blame_inline_enabled = false;
10834 self.show_git_blame_inline = false;
10835 self.show_git_blame_inline_delay_task.take();
10836 } else {
10837 self.git_blame_inline_enabled = true;
10838 self.start_git_blame_inline(user_triggered, cx);
10839 }
10840
10841 cx.notify();
10842 }
10843
10844 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10845 self.start_git_blame(user_triggered, cx);
10846
10847 if ProjectSettings::get_global(cx)
10848 .git
10849 .inline_blame_delay()
10850 .is_some()
10851 {
10852 self.start_inline_blame_timer(cx);
10853 } else {
10854 self.show_git_blame_inline = true
10855 }
10856 }
10857
10858 pub fn blame(&self) -> Option<&Model<GitBlame>> {
10859 self.blame.as_ref()
10860 }
10861
10862 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10863 self.show_git_blame_gutter && self.has_blame_entries(cx)
10864 }
10865
10866 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10867 self.show_git_blame_inline
10868 && self.focus_handle.is_focused(cx)
10869 && !self.newest_selection_head_on_empty_line(cx)
10870 && self.has_blame_entries(cx)
10871 }
10872
10873 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10874 self.blame()
10875 .map_or(false, |blame| blame.read(cx).has_generated_entries())
10876 }
10877
10878 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10879 let cursor_anchor = self.selections.newest_anchor().head();
10880
10881 let snapshot = self.buffer.read(cx).snapshot(cx);
10882 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10883
10884 snapshot.line_len(buffer_row) == 0
10885 }
10886
10887 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10888 let (path, selection, repo) = maybe!({
10889 let project_handle = self.project.as_ref()?.clone();
10890 let project = project_handle.read(cx);
10891
10892 let selection = self.selections.newest::<Point>(cx);
10893 let selection_range = selection.range();
10894
10895 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10896 (buffer, selection_range.start.row..selection_range.end.row)
10897 } else {
10898 let buffer_ranges = self
10899 .buffer()
10900 .read(cx)
10901 .range_to_buffer_ranges(selection_range, cx);
10902
10903 let (buffer, range, _) = if selection.reversed {
10904 buffer_ranges.first()
10905 } else {
10906 buffer_ranges.last()
10907 }?;
10908
10909 let snapshot = buffer.read(cx).snapshot();
10910 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10911 ..text::ToPoint::to_point(&range.end, &snapshot).row;
10912 (buffer.clone(), selection)
10913 };
10914
10915 let path = buffer
10916 .read(cx)
10917 .file()?
10918 .as_local()?
10919 .path()
10920 .to_str()?
10921 .to_string();
10922 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10923 Some((path, selection, repo))
10924 })
10925 .ok_or_else(|| anyhow!("unable to open git repository"))?;
10926
10927 const REMOTE_NAME: &str = "origin";
10928 let origin_url = repo
10929 .remote_url(REMOTE_NAME)
10930 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10931 let sha = repo
10932 .head_sha()
10933 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10934
10935 let (provider, remote) =
10936 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10937 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10938
10939 Ok(provider.build_permalink(
10940 remote,
10941 BuildPermalinkParams {
10942 sha: &sha,
10943 path: &path,
10944 selection: Some(selection),
10945 },
10946 ))
10947 }
10948
10949 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10950 let permalink = self.get_permalink_to_line(cx);
10951
10952 match permalink {
10953 Ok(permalink) => {
10954 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
10955 }
10956 Err(err) => {
10957 let message = format!("Failed to copy permalink: {err}");
10958
10959 Err::<(), anyhow::Error>(err).log_err();
10960
10961 if let Some(workspace) = self.workspace() {
10962 workspace.update(cx, |workspace, cx| {
10963 struct CopyPermalinkToLine;
10964
10965 workspace.show_toast(
10966 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10967 cx,
10968 )
10969 })
10970 }
10971 }
10972 }
10973 }
10974
10975 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
10976 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10977 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10978 if let Some(path) = file.path().to_str() {
10979 let selection = self.selections.newest::<Point>(cx).start.row + 1;
10980 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
10981 }
10982 }
10983 }
10984 }
10985
10986 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10987 let permalink = self.get_permalink_to_line(cx);
10988
10989 match permalink {
10990 Ok(permalink) => {
10991 cx.open_url(permalink.as_ref());
10992 }
10993 Err(err) => {
10994 let message = format!("Failed to open permalink: {err}");
10995
10996 Err::<(), anyhow::Error>(err).log_err();
10997
10998 if let Some(workspace) = self.workspace() {
10999 workspace.update(cx, |workspace, cx| {
11000 struct OpenPermalinkToLine;
11001
11002 workspace.show_toast(
11003 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11004 cx,
11005 )
11006 })
11007 }
11008 }
11009 }
11010 }
11011
11012 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
11013 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
11014 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
11015 pub fn highlight_rows<T: 'static>(
11016 &mut self,
11017 rows: RangeInclusive<Anchor>,
11018 color: Option<Hsla>,
11019 should_autoscroll: bool,
11020 cx: &mut ViewContext<Self>,
11021 ) {
11022 let snapshot = self.buffer().read(cx).snapshot(cx);
11023 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11024 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
11025 highlight
11026 .range
11027 .start()
11028 .cmp(&rows.start(), &snapshot)
11029 .then(highlight.range.end().cmp(&rows.end(), &snapshot))
11030 });
11031 match (color, existing_highlight_index) {
11032 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
11033 ix,
11034 RowHighlight {
11035 index: post_inc(&mut self.highlight_order),
11036 range: rows,
11037 should_autoscroll,
11038 color,
11039 },
11040 ),
11041 (None, Ok(i)) => {
11042 row_highlights.remove(i);
11043 }
11044 }
11045 }
11046
11047 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11048 pub fn clear_row_highlights<T: 'static>(&mut self) {
11049 self.highlighted_rows.remove(&TypeId::of::<T>());
11050 }
11051
11052 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11053 pub fn highlighted_rows<T: 'static>(
11054 &self,
11055 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
11056 Some(
11057 self.highlighted_rows
11058 .get(&TypeId::of::<T>())?
11059 .iter()
11060 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
11061 )
11062 }
11063
11064 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11065 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11066 /// Allows to ignore certain kinds of highlights.
11067 pub fn highlighted_display_rows(
11068 &mut self,
11069 cx: &mut WindowContext,
11070 ) -> BTreeMap<DisplayRow, Hsla> {
11071 let snapshot = self.snapshot(cx);
11072 let mut used_highlight_orders = HashMap::default();
11073 self.highlighted_rows
11074 .iter()
11075 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11076 .fold(
11077 BTreeMap::<DisplayRow, Hsla>::new(),
11078 |mut unique_rows, highlight| {
11079 let start_row = highlight.range.start().to_display_point(&snapshot).row();
11080 let end_row = highlight.range.end().to_display_point(&snapshot).row();
11081 for row in start_row.0..=end_row.0 {
11082 let used_index =
11083 used_highlight_orders.entry(row).or_insert(highlight.index);
11084 if highlight.index >= *used_index {
11085 *used_index = highlight.index;
11086 match highlight.color {
11087 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
11088 None => unique_rows.remove(&DisplayRow(row)),
11089 };
11090 }
11091 }
11092 unique_rows
11093 },
11094 )
11095 }
11096
11097 pub fn highlighted_display_row_for_autoscroll(
11098 &self,
11099 snapshot: &DisplaySnapshot,
11100 ) -> Option<DisplayRow> {
11101 self.highlighted_rows
11102 .values()
11103 .flat_map(|highlighted_rows| highlighted_rows.iter())
11104 .filter_map(|highlight| {
11105 if highlight.color.is_none() || !highlight.should_autoscroll {
11106 return None;
11107 }
11108 Some(highlight.range.start().to_display_point(&snapshot).row())
11109 })
11110 .min()
11111 }
11112
11113 pub fn set_search_within_ranges(
11114 &mut self,
11115 ranges: &[Range<Anchor>],
11116 cx: &mut ViewContext<Self>,
11117 ) {
11118 self.highlight_background::<SearchWithinRange>(
11119 ranges,
11120 |colors| colors.editor_document_highlight_read_background,
11121 cx,
11122 )
11123 }
11124
11125 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11126 self.breadcrumb_header = Some(new_header);
11127 }
11128
11129 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11130 self.clear_background_highlights::<SearchWithinRange>(cx);
11131 }
11132
11133 pub fn highlight_background<T: 'static>(
11134 &mut self,
11135 ranges: &[Range<Anchor>],
11136 color_fetcher: fn(&ThemeColors) -> Hsla,
11137 cx: &mut ViewContext<Self>,
11138 ) {
11139 self.background_highlights
11140 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11141 self.scrollbar_marker_state.dirty = true;
11142 cx.notify();
11143 }
11144
11145 pub fn clear_background_highlights<T: 'static>(
11146 &mut self,
11147 cx: &mut ViewContext<Self>,
11148 ) -> Option<BackgroundHighlight> {
11149 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11150 if !text_highlights.1.is_empty() {
11151 self.scrollbar_marker_state.dirty = true;
11152 cx.notify();
11153 }
11154 Some(text_highlights)
11155 }
11156
11157 pub fn highlight_gutter<T: 'static>(
11158 &mut self,
11159 ranges: &[Range<Anchor>],
11160 color_fetcher: fn(&AppContext) -> Hsla,
11161 cx: &mut ViewContext<Self>,
11162 ) {
11163 self.gutter_highlights
11164 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11165 cx.notify();
11166 }
11167
11168 pub fn clear_gutter_highlights<T: 'static>(
11169 &mut self,
11170 cx: &mut ViewContext<Self>,
11171 ) -> Option<GutterHighlight> {
11172 cx.notify();
11173 self.gutter_highlights.remove(&TypeId::of::<T>())
11174 }
11175
11176 #[cfg(feature = "test-support")]
11177 pub fn all_text_background_highlights(
11178 &mut self,
11179 cx: &mut ViewContext<Self>,
11180 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11181 let snapshot = self.snapshot(cx);
11182 let buffer = &snapshot.buffer_snapshot;
11183 let start = buffer.anchor_before(0);
11184 let end = buffer.anchor_after(buffer.len());
11185 let theme = cx.theme().colors();
11186 self.background_highlights_in_range(start..end, &snapshot, theme)
11187 }
11188
11189 #[cfg(feature = "test-support")]
11190 pub fn search_background_highlights(
11191 &mut self,
11192 cx: &mut ViewContext<Self>,
11193 ) -> Vec<Range<Point>> {
11194 let snapshot = self.buffer().read(cx).snapshot(cx);
11195
11196 let highlights = self
11197 .background_highlights
11198 .get(&TypeId::of::<items::BufferSearchHighlights>());
11199
11200 if let Some((_color, ranges)) = highlights {
11201 ranges
11202 .iter()
11203 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11204 .collect_vec()
11205 } else {
11206 vec![]
11207 }
11208 }
11209
11210 fn document_highlights_for_position<'a>(
11211 &'a self,
11212 position: Anchor,
11213 buffer: &'a MultiBufferSnapshot,
11214 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
11215 let read_highlights = self
11216 .background_highlights
11217 .get(&TypeId::of::<DocumentHighlightRead>())
11218 .map(|h| &h.1);
11219 let write_highlights = self
11220 .background_highlights
11221 .get(&TypeId::of::<DocumentHighlightWrite>())
11222 .map(|h| &h.1);
11223 let left_position = position.bias_left(buffer);
11224 let right_position = position.bias_right(buffer);
11225 read_highlights
11226 .into_iter()
11227 .chain(write_highlights)
11228 .flat_map(move |ranges| {
11229 let start_ix = match ranges.binary_search_by(|probe| {
11230 let cmp = probe.end.cmp(&left_position, buffer);
11231 if cmp.is_ge() {
11232 Ordering::Greater
11233 } else {
11234 Ordering::Less
11235 }
11236 }) {
11237 Ok(i) | Err(i) => i,
11238 };
11239
11240 ranges[start_ix..]
11241 .iter()
11242 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11243 })
11244 }
11245
11246 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11247 self.background_highlights
11248 .get(&TypeId::of::<T>())
11249 .map_or(false, |(_, highlights)| !highlights.is_empty())
11250 }
11251
11252 pub fn background_highlights_in_range(
11253 &self,
11254 search_range: Range<Anchor>,
11255 display_snapshot: &DisplaySnapshot,
11256 theme: &ThemeColors,
11257 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11258 let mut results = Vec::new();
11259 for (color_fetcher, ranges) in self.background_highlights.values() {
11260 let color = color_fetcher(theme);
11261 let start_ix = match ranges.binary_search_by(|probe| {
11262 let cmp = probe
11263 .end
11264 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11265 if cmp.is_gt() {
11266 Ordering::Greater
11267 } else {
11268 Ordering::Less
11269 }
11270 }) {
11271 Ok(i) | Err(i) => i,
11272 };
11273 for range in &ranges[start_ix..] {
11274 if range
11275 .start
11276 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11277 .is_ge()
11278 {
11279 break;
11280 }
11281
11282 let start = range.start.to_display_point(&display_snapshot);
11283 let end = range.end.to_display_point(&display_snapshot);
11284 results.push((start..end, color))
11285 }
11286 }
11287 results
11288 }
11289
11290 pub fn background_highlight_row_ranges<T: 'static>(
11291 &self,
11292 search_range: Range<Anchor>,
11293 display_snapshot: &DisplaySnapshot,
11294 count: usize,
11295 ) -> Vec<RangeInclusive<DisplayPoint>> {
11296 let mut results = Vec::new();
11297 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11298 return vec![];
11299 };
11300
11301 let start_ix = match ranges.binary_search_by(|probe| {
11302 let cmp = probe
11303 .end
11304 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11305 if cmp.is_gt() {
11306 Ordering::Greater
11307 } else {
11308 Ordering::Less
11309 }
11310 }) {
11311 Ok(i) | Err(i) => i,
11312 };
11313 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11314 if let (Some(start_display), Some(end_display)) = (start, end) {
11315 results.push(
11316 start_display.to_display_point(display_snapshot)
11317 ..=end_display.to_display_point(display_snapshot),
11318 );
11319 }
11320 };
11321 let mut start_row: Option<Point> = None;
11322 let mut end_row: Option<Point> = None;
11323 if ranges.len() > count {
11324 return Vec::new();
11325 }
11326 for range in &ranges[start_ix..] {
11327 if range
11328 .start
11329 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11330 .is_ge()
11331 {
11332 break;
11333 }
11334 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11335 if let Some(current_row) = &end_row {
11336 if end.row == current_row.row {
11337 continue;
11338 }
11339 }
11340 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11341 if start_row.is_none() {
11342 assert_eq!(end_row, None);
11343 start_row = Some(start);
11344 end_row = Some(end);
11345 continue;
11346 }
11347 if let Some(current_end) = end_row.as_mut() {
11348 if start.row > current_end.row + 1 {
11349 push_region(start_row, end_row);
11350 start_row = Some(start);
11351 end_row = Some(end);
11352 } else {
11353 // Merge two hunks.
11354 *current_end = end;
11355 }
11356 } else {
11357 unreachable!();
11358 }
11359 }
11360 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11361 push_region(start_row, end_row);
11362 results
11363 }
11364
11365 pub fn gutter_highlights_in_range(
11366 &self,
11367 search_range: Range<Anchor>,
11368 display_snapshot: &DisplaySnapshot,
11369 cx: &AppContext,
11370 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11371 let mut results = Vec::new();
11372 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11373 let color = color_fetcher(cx);
11374 let start_ix = match ranges.binary_search_by(|probe| {
11375 let cmp = probe
11376 .end
11377 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11378 if cmp.is_gt() {
11379 Ordering::Greater
11380 } else {
11381 Ordering::Less
11382 }
11383 }) {
11384 Ok(i) | Err(i) => i,
11385 };
11386 for range in &ranges[start_ix..] {
11387 if range
11388 .start
11389 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11390 .is_ge()
11391 {
11392 break;
11393 }
11394
11395 let start = range.start.to_display_point(&display_snapshot);
11396 let end = range.end.to_display_point(&display_snapshot);
11397 results.push((start..end, color))
11398 }
11399 }
11400 results
11401 }
11402
11403 /// Get the text ranges corresponding to the redaction query
11404 pub fn redacted_ranges(
11405 &self,
11406 search_range: Range<Anchor>,
11407 display_snapshot: &DisplaySnapshot,
11408 cx: &WindowContext,
11409 ) -> Vec<Range<DisplayPoint>> {
11410 display_snapshot
11411 .buffer_snapshot
11412 .redacted_ranges(search_range, |file| {
11413 if let Some(file) = file {
11414 file.is_private()
11415 && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
11416 } else {
11417 false
11418 }
11419 })
11420 .map(|range| {
11421 range.start.to_display_point(display_snapshot)
11422 ..range.end.to_display_point(display_snapshot)
11423 })
11424 .collect()
11425 }
11426
11427 pub fn highlight_text<T: 'static>(
11428 &mut self,
11429 ranges: Vec<Range<Anchor>>,
11430 style: HighlightStyle,
11431 cx: &mut ViewContext<Self>,
11432 ) {
11433 self.display_map.update(cx, |map, _| {
11434 map.highlight_text(TypeId::of::<T>(), ranges, style)
11435 });
11436 cx.notify();
11437 }
11438
11439 pub(crate) fn highlight_inlays<T: 'static>(
11440 &mut self,
11441 highlights: Vec<InlayHighlight>,
11442 style: HighlightStyle,
11443 cx: &mut ViewContext<Self>,
11444 ) {
11445 self.display_map.update(cx, |map, _| {
11446 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11447 });
11448 cx.notify();
11449 }
11450
11451 pub fn text_highlights<'a, T: 'static>(
11452 &'a self,
11453 cx: &'a AppContext,
11454 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11455 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11456 }
11457
11458 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11459 let cleared = self
11460 .display_map
11461 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11462 if cleared {
11463 cx.notify();
11464 }
11465 }
11466
11467 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11468 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11469 && self.focus_handle.is_focused(cx)
11470 }
11471
11472 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11473 self.show_cursor_when_unfocused = is_enabled;
11474 cx.notify();
11475 }
11476
11477 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11478 cx.notify();
11479 }
11480
11481 fn on_buffer_event(
11482 &mut self,
11483 multibuffer: Model<MultiBuffer>,
11484 event: &multi_buffer::Event,
11485 cx: &mut ViewContext<Self>,
11486 ) {
11487 match event {
11488 multi_buffer::Event::Edited {
11489 singleton_buffer_edited,
11490 } => {
11491 self.scrollbar_marker_state.dirty = true;
11492 self.active_indent_guides_state.dirty = true;
11493 self.refresh_active_diagnostics(cx);
11494 self.refresh_code_actions(cx);
11495 if self.has_active_inline_completion(cx) {
11496 self.update_visible_inline_completion(cx);
11497 }
11498 cx.emit(EditorEvent::BufferEdited);
11499 cx.emit(SearchEvent::MatchesInvalidated);
11500 if *singleton_buffer_edited {
11501 if let Some(project) = &self.project {
11502 let project = project.read(cx);
11503 #[allow(clippy::mutable_key_type)]
11504 let languages_affected = multibuffer
11505 .read(cx)
11506 .all_buffers()
11507 .into_iter()
11508 .filter_map(|buffer| {
11509 let buffer = buffer.read(cx);
11510 let language = buffer.language()?;
11511 if project.is_local_or_ssh()
11512 && project.language_servers_for_buffer(buffer, cx).count() == 0
11513 {
11514 None
11515 } else {
11516 Some(language)
11517 }
11518 })
11519 .cloned()
11520 .collect::<HashSet<_>>();
11521 if !languages_affected.is_empty() {
11522 self.refresh_inlay_hints(
11523 InlayHintRefreshReason::BufferEdited(languages_affected),
11524 cx,
11525 );
11526 }
11527 }
11528 }
11529
11530 let Some(project) = &self.project else { return };
11531 let telemetry = project.read(cx).client().telemetry().clone();
11532 refresh_linked_ranges(self, cx);
11533 telemetry.log_edit_event("editor");
11534 }
11535 multi_buffer::Event::ExcerptsAdded {
11536 buffer,
11537 predecessor,
11538 excerpts,
11539 } => {
11540 self.tasks_update_task = Some(self.refresh_runnables(cx));
11541 cx.emit(EditorEvent::ExcerptsAdded {
11542 buffer: buffer.clone(),
11543 predecessor: *predecessor,
11544 excerpts: excerpts.clone(),
11545 });
11546 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11547 }
11548 multi_buffer::Event::ExcerptsRemoved { ids } => {
11549 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11550 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11551 }
11552 multi_buffer::Event::ExcerptsEdited { ids } => {
11553 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11554 }
11555 multi_buffer::Event::ExcerptsExpanded { ids } => {
11556 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11557 }
11558 multi_buffer::Event::Reparsed(buffer_id) => {
11559 self.tasks_update_task = Some(self.refresh_runnables(cx));
11560
11561 cx.emit(EditorEvent::Reparsed(*buffer_id));
11562 }
11563 multi_buffer::Event::LanguageChanged(buffer_id) => {
11564 linked_editing_ranges::refresh_linked_ranges(self, cx);
11565 cx.emit(EditorEvent::Reparsed(*buffer_id));
11566 cx.notify();
11567 }
11568 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11569 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11570 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11571 cx.emit(EditorEvent::TitleChanged)
11572 }
11573 multi_buffer::Event::DiffBaseChanged => {
11574 self.scrollbar_marker_state.dirty = true;
11575 cx.emit(EditorEvent::DiffBaseChanged);
11576 cx.notify();
11577 }
11578 multi_buffer::Event::DiffUpdated { buffer } => {
11579 self.sync_expanded_diff_hunks(buffer.clone(), cx);
11580 cx.notify();
11581 }
11582 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11583 multi_buffer::Event::DiagnosticsUpdated => {
11584 self.refresh_active_diagnostics(cx);
11585 self.scrollbar_marker_state.dirty = true;
11586 cx.notify();
11587 }
11588 _ => {}
11589 };
11590 }
11591
11592 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11593 cx.notify();
11594 }
11595
11596 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11597 self.tasks_update_task = Some(self.refresh_runnables(cx));
11598 self.refresh_inline_completion(true, false, cx);
11599 self.refresh_inlay_hints(
11600 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11601 self.selections.newest_anchor().head(),
11602 &self.buffer.read(cx).snapshot(cx),
11603 cx,
11604 )),
11605 cx,
11606 );
11607 let editor_settings = EditorSettings::get_global(cx);
11608 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11609 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11610
11611 let project_settings = ProjectSettings::get_global(cx);
11612 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11613
11614 if self.mode == EditorMode::Full {
11615 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11616 if self.git_blame_inline_enabled != inline_blame_enabled {
11617 self.toggle_git_blame_inline_internal(false, cx);
11618 }
11619 }
11620
11621 cx.notify();
11622 }
11623
11624 pub fn set_searchable(&mut self, searchable: bool) {
11625 self.searchable = searchable;
11626 }
11627
11628 pub fn searchable(&self) -> bool {
11629 self.searchable
11630 }
11631
11632 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11633 self.open_excerpts_common(true, cx)
11634 }
11635
11636 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11637 self.open_excerpts_common(false, cx)
11638 }
11639
11640 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11641 let buffer = self.buffer.read(cx);
11642 if buffer.is_singleton() {
11643 cx.propagate();
11644 return;
11645 }
11646
11647 let Some(workspace) = self.workspace() else {
11648 cx.propagate();
11649 return;
11650 };
11651
11652 let mut new_selections_by_buffer = HashMap::default();
11653 for selection in self.selections.all::<usize>(cx) {
11654 for (buffer, mut range, _) in
11655 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11656 {
11657 if selection.reversed {
11658 mem::swap(&mut range.start, &mut range.end);
11659 }
11660 new_selections_by_buffer
11661 .entry(buffer)
11662 .or_insert(Vec::new())
11663 .push(range)
11664 }
11665 }
11666
11667 // We defer the pane interaction because we ourselves are a workspace item
11668 // and activating a new item causes the pane to call a method on us reentrantly,
11669 // which panics if we're on the stack.
11670 cx.window_context().defer(move |cx| {
11671 workspace.update(cx, |workspace, cx| {
11672 let pane = if split {
11673 workspace.adjacent_pane(cx)
11674 } else {
11675 workspace.active_pane().clone()
11676 };
11677
11678 for (buffer, ranges) in new_selections_by_buffer {
11679 let editor =
11680 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
11681 editor.update(cx, |editor, cx| {
11682 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11683 s.select_ranges(ranges);
11684 });
11685 });
11686 }
11687 })
11688 });
11689 }
11690
11691 fn jump(
11692 &mut self,
11693 path: ProjectPath,
11694 position: Point,
11695 anchor: language::Anchor,
11696 offset_from_top: u32,
11697 cx: &mut ViewContext<Self>,
11698 ) {
11699 let workspace = self.workspace();
11700 cx.spawn(|_, mut cx| async move {
11701 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11702 let editor = workspace.update(&mut cx, |workspace, cx| {
11703 // Reset the preview item id before opening the new item
11704 workspace.active_pane().update(cx, |pane, cx| {
11705 pane.set_preview_item_id(None, cx);
11706 });
11707 workspace.open_path_preview(path, None, true, true, cx)
11708 })?;
11709 let editor = editor
11710 .await?
11711 .downcast::<Editor>()
11712 .ok_or_else(|| anyhow!("opened item was not an editor"))?
11713 .downgrade();
11714 editor.update(&mut cx, |editor, cx| {
11715 let buffer = editor
11716 .buffer()
11717 .read(cx)
11718 .as_singleton()
11719 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11720 let buffer = buffer.read(cx);
11721 let cursor = if buffer.can_resolve(&anchor) {
11722 language::ToPoint::to_point(&anchor, buffer)
11723 } else {
11724 buffer.clip_point(position, Bias::Left)
11725 };
11726
11727 let nav_history = editor.nav_history.take();
11728 editor.change_selections(
11729 Some(Autoscroll::top_relative(offset_from_top as usize)),
11730 cx,
11731 |s| {
11732 s.select_ranges([cursor..cursor]);
11733 },
11734 );
11735 editor.nav_history = nav_history;
11736
11737 anyhow::Ok(())
11738 })??;
11739
11740 anyhow::Ok(())
11741 })
11742 .detach_and_log_err(cx);
11743 }
11744
11745 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11746 let snapshot = self.buffer.read(cx).read(cx);
11747 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11748 Some(
11749 ranges
11750 .iter()
11751 .map(move |range| {
11752 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11753 })
11754 .collect(),
11755 )
11756 }
11757
11758 fn selection_replacement_ranges(
11759 &self,
11760 range: Range<OffsetUtf16>,
11761 cx: &AppContext,
11762 ) -> Vec<Range<OffsetUtf16>> {
11763 let selections = self.selections.all::<OffsetUtf16>(cx);
11764 let newest_selection = selections
11765 .iter()
11766 .max_by_key(|selection| selection.id)
11767 .unwrap();
11768 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11769 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11770 let snapshot = self.buffer.read(cx).read(cx);
11771 selections
11772 .into_iter()
11773 .map(|mut selection| {
11774 selection.start.0 =
11775 (selection.start.0 as isize).saturating_add(start_delta) as usize;
11776 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11777 snapshot.clip_offset_utf16(selection.start, Bias::Left)
11778 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11779 })
11780 .collect()
11781 }
11782
11783 fn report_editor_event(
11784 &self,
11785 operation: &'static str,
11786 file_extension: Option<String>,
11787 cx: &AppContext,
11788 ) {
11789 if cfg!(any(test, feature = "test-support")) {
11790 return;
11791 }
11792
11793 let Some(project) = &self.project else { return };
11794
11795 // If None, we are in a file without an extension
11796 let file = self
11797 .buffer
11798 .read(cx)
11799 .as_singleton()
11800 .and_then(|b| b.read(cx).file());
11801 let file_extension = file_extension.or(file
11802 .as_ref()
11803 .and_then(|file| Path::new(file.file_name(cx)).extension())
11804 .and_then(|e| e.to_str())
11805 .map(|a| a.to_string()));
11806
11807 let vim_mode = cx
11808 .global::<SettingsStore>()
11809 .raw_user_settings()
11810 .get("vim_mode")
11811 == Some(&serde_json::Value::Bool(true));
11812
11813 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11814 == language::language_settings::InlineCompletionProvider::Copilot;
11815 let copilot_enabled_for_language = self
11816 .buffer
11817 .read(cx)
11818 .settings_at(0, cx)
11819 .show_inline_completions;
11820
11821 let telemetry = project.read(cx).client().telemetry().clone();
11822 telemetry.report_editor_event(
11823 file_extension,
11824 vim_mode,
11825 operation,
11826 copilot_enabled,
11827 copilot_enabled_for_language,
11828 )
11829 }
11830
11831 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11832 /// with each line being an array of {text, highlight} objects.
11833 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11834 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11835 return;
11836 };
11837
11838 #[derive(Serialize)]
11839 struct Chunk<'a> {
11840 text: String,
11841 highlight: Option<&'a str>,
11842 }
11843
11844 let snapshot = buffer.read(cx).snapshot();
11845 let range = self
11846 .selected_text_range(false, cx)
11847 .and_then(|selection| {
11848 if selection.range.is_empty() {
11849 None
11850 } else {
11851 Some(selection.range)
11852 }
11853 })
11854 .unwrap_or_else(|| 0..snapshot.len());
11855
11856 let chunks = snapshot.chunks(range, true);
11857 let mut lines = Vec::new();
11858 let mut line: VecDeque<Chunk> = VecDeque::new();
11859
11860 let Some(style) = self.style.as_ref() else {
11861 return;
11862 };
11863
11864 for chunk in chunks {
11865 let highlight = chunk
11866 .syntax_highlight_id
11867 .and_then(|id| id.name(&style.syntax));
11868 let mut chunk_lines = chunk.text.split('\n').peekable();
11869 while let Some(text) = chunk_lines.next() {
11870 let mut merged_with_last_token = false;
11871 if let Some(last_token) = line.back_mut() {
11872 if last_token.highlight == highlight {
11873 last_token.text.push_str(text);
11874 merged_with_last_token = true;
11875 }
11876 }
11877
11878 if !merged_with_last_token {
11879 line.push_back(Chunk {
11880 text: text.into(),
11881 highlight,
11882 });
11883 }
11884
11885 if chunk_lines.peek().is_some() {
11886 if line.len() > 1 && line.front().unwrap().text.is_empty() {
11887 line.pop_front();
11888 }
11889 if line.len() > 1 && line.back().unwrap().text.is_empty() {
11890 line.pop_back();
11891 }
11892
11893 lines.push(mem::take(&mut line));
11894 }
11895 }
11896 }
11897
11898 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11899 return;
11900 };
11901 cx.write_to_clipboard(ClipboardItem::new_string(lines));
11902 }
11903
11904 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11905 &self.inlay_hint_cache
11906 }
11907
11908 pub fn replay_insert_event(
11909 &mut self,
11910 text: &str,
11911 relative_utf16_range: Option<Range<isize>>,
11912 cx: &mut ViewContext<Self>,
11913 ) {
11914 if !self.input_enabled {
11915 cx.emit(EditorEvent::InputIgnored { text: text.into() });
11916 return;
11917 }
11918 if let Some(relative_utf16_range) = relative_utf16_range {
11919 let selections = self.selections.all::<OffsetUtf16>(cx);
11920 self.change_selections(None, cx, |s| {
11921 let new_ranges = selections.into_iter().map(|range| {
11922 let start = OffsetUtf16(
11923 range
11924 .head()
11925 .0
11926 .saturating_add_signed(relative_utf16_range.start),
11927 );
11928 let end = OffsetUtf16(
11929 range
11930 .head()
11931 .0
11932 .saturating_add_signed(relative_utf16_range.end),
11933 );
11934 start..end
11935 });
11936 s.select_ranges(new_ranges);
11937 });
11938 }
11939
11940 self.handle_input(text, cx);
11941 }
11942
11943 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11944 let Some(project) = self.project.as_ref() else {
11945 return false;
11946 };
11947 let project = project.read(cx);
11948
11949 let mut supports = false;
11950 self.buffer().read(cx).for_each_buffer(|buffer| {
11951 if !supports {
11952 supports = project
11953 .language_servers_for_buffer(buffer.read(cx), cx)
11954 .any(
11955 |(_, server)| match server.capabilities().inlay_hint_provider {
11956 Some(lsp::OneOf::Left(enabled)) => enabled,
11957 Some(lsp::OneOf::Right(_)) => true,
11958 None => false,
11959 },
11960 )
11961 }
11962 });
11963 supports
11964 }
11965
11966 pub fn focus(&self, cx: &mut WindowContext) {
11967 cx.focus(&self.focus_handle)
11968 }
11969
11970 pub fn is_focused(&self, cx: &WindowContext) -> bool {
11971 self.focus_handle.is_focused(cx)
11972 }
11973
11974 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11975 cx.emit(EditorEvent::Focused);
11976
11977 if let Some(descendant) = self
11978 .last_focused_descendant
11979 .take()
11980 .and_then(|descendant| descendant.upgrade())
11981 {
11982 cx.focus(&descendant);
11983 } else {
11984 if let Some(blame) = self.blame.as_ref() {
11985 blame.update(cx, GitBlame::focus)
11986 }
11987
11988 self.blink_manager.update(cx, BlinkManager::enable);
11989 self.show_cursor_names(cx);
11990 self.buffer.update(cx, |buffer, cx| {
11991 buffer.finalize_last_transaction(cx);
11992 if self.leader_peer_id.is_none() {
11993 buffer.set_active_selections(
11994 &self.selections.disjoint_anchors(),
11995 self.selections.line_mode,
11996 self.cursor_shape,
11997 cx,
11998 );
11999 }
12000 });
12001 }
12002 }
12003
12004 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12005 cx.emit(EditorEvent::FocusedIn)
12006 }
12007
12008 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12009 if event.blurred != self.focus_handle {
12010 self.last_focused_descendant = Some(event.blurred);
12011 }
12012 }
12013
12014 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12015 self.blink_manager.update(cx, BlinkManager::disable);
12016 self.buffer
12017 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12018
12019 if let Some(blame) = self.blame.as_ref() {
12020 blame.update(cx, GitBlame::blur)
12021 }
12022 if !self.hover_state.focused(cx) {
12023 hide_hover(self, cx);
12024 }
12025
12026 self.hide_context_menu(cx);
12027 cx.emit(EditorEvent::Blurred);
12028 cx.notify();
12029 }
12030
12031 pub fn register_action<A: Action>(
12032 &mut self,
12033 listener: impl Fn(&A, &mut WindowContext) + 'static,
12034 ) -> Subscription {
12035 let id = self.next_editor_action_id.post_inc();
12036 let listener = Arc::new(listener);
12037 self.editor_actions.borrow_mut().insert(
12038 id,
12039 Box::new(move |cx| {
12040 let cx = cx.window_context();
12041 let listener = listener.clone();
12042 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12043 let action = action.downcast_ref().unwrap();
12044 if phase == DispatchPhase::Bubble {
12045 listener(action, cx)
12046 }
12047 })
12048 }),
12049 );
12050
12051 let editor_actions = self.editor_actions.clone();
12052 Subscription::new(move || {
12053 editor_actions.borrow_mut().remove(&id);
12054 })
12055 }
12056
12057 pub fn file_header_size(&self) -> u32 {
12058 self.file_header_size
12059 }
12060
12061 pub fn revert(
12062 &mut self,
12063 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12064 cx: &mut ViewContext<Self>,
12065 ) {
12066 self.buffer().update(cx, |multi_buffer, cx| {
12067 for (buffer_id, changes) in revert_changes {
12068 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12069 buffer.update(cx, |buffer, cx| {
12070 buffer.edit(
12071 changes.into_iter().map(|(range, text)| {
12072 (range, text.to_string().map(Arc::<str>::from))
12073 }),
12074 None,
12075 cx,
12076 );
12077 });
12078 }
12079 }
12080 });
12081 self.change_selections(None, cx, |selections| selections.refresh());
12082 }
12083
12084 pub fn to_pixel_point(
12085 &mut self,
12086 source: multi_buffer::Anchor,
12087 editor_snapshot: &EditorSnapshot,
12088 cx: &mut ViewContext<Self>,
12089 ) -> Option<gpui::Point<Pixels>> {
12090 let source_point = source.to_display_point(editor_snapshot);
12091 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12092 }
12093
12094 pub fn display_to_pixel_point(
12095 &mut self,
12096 source: DisplayPoint,
12097 editor_snapshot: &EditorSnapshot,
12098 cx: &mut ViewContext<Self>,
12099 ) -> Option<gpui::Point<Pixels>> {
12100 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12101 let text_layout_details = self.text_layout_details(cx);
12102 let scroll_top = text_layout_details
12103 .scroll_anchor
12104 .scroll_position(editor_snapshot)
12105 .y;
12106
12107 if source.row().as_f32() < scroll_top.floor() {
12108 return None;
12109 }
12110 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12111 let source_y = line_height * (source.row().as_f32() - scroll_top);
12112 Some(gpui::Point::new(source_x, source_y))
12113 }
12114
12115 fn gutter_bounds(&self) -> Option<Bounds<Pixels>> {
12116 let bounds = self.last_bounds?;
12117 Some(element::gutter_bounds(bounds, self.gutter_dimensions))
12118 }
12119
12120 pub fn has_active_completions_menu(&self) -> bool {
12121 self.context_menu.read().as_ref().map_or(false, |menu| {
12122 menu.visible() && matches!(menu, ContextMenu::Completions(_))
12123 })
12124 }
12125
12126 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12127 self.addons
12128 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12129 }
12130
12131 pub fn unregister_addon<T: Addon>(&mut self) {
12132 self.addons.remove(&std::any::TypeId::of::<T>());
12133 }
12134
12135 pub fn addon<T: Addon>(&self) -> Option<&T> {
12136 let type_id = std::any::TypeId::of::<T>();
12137 self.addons
12138 .get(&type_id)
12139 .and_then(|item| item.to_any().downcast_ref::<T>())
12140 }
12141}
12142
12143fn hunks_for_selections(
12144 multi_buffer_snapshot: &MultiBufferSnapshot,
12145 selections: &[Selection<Anchor>],
12146) -> Vec<DiffHunk<MultiBufferRow>> {
12147 let buffer_rows_for_selections = selections.iter().map(|selection| {
12148 let head = selection.head();
12149 let tail = selection.tail();
12150 let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
12151 let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
12152 if start > end {
12153 end..start
12154 } else {
12155 start..end
12156 }
12157 });
12158
12159 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12160}
12161
12162pub fn hunks_for_rows(
12163 rows: impl Iterator<Item = Range<MultiBufferRow>>,
12164 multi_buffer_snapshot: &MultiBufferSnapshot,
12165) -> Vec<DiffHunk<MultiBufferRow>> {
12166 let mut hunks = Vec::new();
12167 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12168 HashMap::default();
12169 for selected_multi_buffer_rows in rows {
12170 let query_rows =
12171 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12172 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12173 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12174 // when the caret is just above or just below the deleted hunk.
12175 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12176 let related_to_selection = if allow_adjacent {
12177 hunk.associated_range.overlaps(&query_rows)
12178 || hunk.associated_range.start == query_rows.end
12179 || hunk.associated_range.end == query_rows.start
12180 } else {
12181 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12182 // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12183 hunk.associated_range.overlaps(&selected_multi_buffer_rows)
12184 || selected_multi_buffer_rows.end == hunk.associated_range.start
12185 };
12186 if related_to_selection {
12187 if !processed_buffer_rows
12188 .entry(hunk.buffer_id)
12189 .or_default()
12190 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12191 {
12192 continue;
12193 }
12194 hunks.push(hunk);
12195 }
12196 }
12197 }
12198
12199 hunks
12200}
12201
12202pub trait CollaborationHub {
12203 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12204 fn user_participant_indices<'a>(
12205 &self,
12206 cx: &'a AppContext,
12207 ) -> &'a HashMap<u64, ParticipantIndex>;
12208 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12209}
12210
12211impl CollaborationHub for Model<Project> {
12212 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12213 self.read(cx).collaborators()
12214 }
12215
12216 fn user_participant_indices<'a>(
12217 &self,
12218 cx: &'a AppContext,
12219 ) -> &'a HashMap<u64, ParticipantIndex> {
12220 self.read(cx).user_store().read(cx).participant_indices()
12221 }
12222
12223 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12224 let this = self.read(cx);
12225 let user_ids = this.collaborators().values().map(|c| c.user_id);
12226 this.user_store().read_with(cx, |user_store, cx| {
12227 user_store.participant_names(user_ids, cx)
12228 })
12229 }
12230}
12231
12232pub trait CompletionProvider {
12233 fn completions(
12234 &self,
12235 buffer: &Model<Buffer>,
12236 buffer_position: text::Anchor,
12237 trigger: CompletionContext,
12238 cx: &mut ViewContext<Editor>,
12239 ) -> Task<Result<Vec<Completion>>>;
12240
12241 fn resolve_completions(
12242 &self,
12243 buffer: Model<Buffer>,
12244 completion_indices: Vec<usize>,
12245 completions: Arc<RwLock<Box<[Completion]>>>,
12246 cx: &mut ViewContext<Editor>,
12247 ) -> Task<Result<bool>>;
12248
12249 fn apply_additional_edits_for_completion(
12250 &self,
12251 buffer: Model<Buffer>,
12252 completion: Completion,
12253 push_to_history: bool,
12254 cx: &mut ViewContext<Editor>,
12255 ) -> Task<Result<Option<language::Transaction>>>;
12256
12257 fn is_completion_trigger(
12258 &self,
12259 buffer: &Model<Buffer>,
12260 position: language::Anchor,
12261 text: &str,
12262 trigger_in_words: bool,
12263 cx: &mut ViewContext<Editor>,
12264 ) -> bool;
12265
12266 fn sort_completions(&self) -> bool {
12267 true
12268 }
12269}
12270
12271fn snippet_completions(
12272 project: &Project,
12273 buffer: &Model<Buffer>,
12274 buffer_position: text::Anchor,
12275 cx: &mut AppContext,
12276) -> Vec<Completion> {
12277 let language = buffer.read(cx).language_at(buffer_position);
12278 let language_name = language.as_ref().map(|language| language.lsp_id());
12279 let snippet_store = project.snippets().read(cx);
12280 let snippets = snippet_store.snippets_for(language_name, cx);
12281
12282 if snippets.is_empty() {
12283 return vec![];
12284 }
12285 let snapshot = buffer.read(cx).text_snapshot();
12286 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12287
12288 let mut lines = chunks.lines();
12289 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12290 return vec![];
12291 };
12292
12293 let scope = language.map(|language| language.default_scope());
12294 let mut last_word = line_at
12295 .chars()
12296 .rev()
12297 .take_while(|c| char_kind(&scope, *c) == CharKind::Word)
12298 .collect::<String>();
12299 last_word = last_word.chars().rev().collect();
12300 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12301 let to_lsp = |point: &text::Anchor| {
12302 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12303 point_to_lsp(end)
12304 };
12305 let lsp_end = to_lsp(&buffer_position);
12306 snippets
12307 .into_iter()
12308 .filter_map(|snippet| {
12309 let matching_prefix = snippet
12310 .prefix
12311 .iter()
12312 .find(|prefix| prefix.starts_with(&last_word))?;
12313 let start = as_offset - last_word.len();
12314 let start = snapshot.anchor_before(start);
12315 let range = start..buffer_position;
12316 let lsp_start = to_lsp(&start);
12317 let lsp_range = lsp::Range {
12318 start: lsp_start,
12319 end: lsp_end,
12320 };
12321 Some(Completion {
12322 old_range: range,
12323 new_text: snippet.body.clone(),
12324 label: CodeLabel {
12325 text: matching_prefix.clone(),
12326 runs: vec![],
12327 filter_range: 0..matching_prefix.len(),
12328 },
12329 server_id: LanguageServerId(usize::MAX),
12330 documentation: snippet
12331 .description
12332 .clone()
12333 .map(|description| Documentation::SingleLine(description)),
12334 lsp_completion: lsp::CompletionItem {
12335 label: snippet.prefix.first().unwrap().clone(),
12336 kind: Some(CompletionItemKind::SNIPPET),
12337 label_details: snippet.description.as_ref().map(|description| {
12338 lsp::CompletionItemLabelDetails {
12339 detail: Some(description.clone()),
12340 description: None,
12341 }
12342 }),
12343 insert_text_format: Some(InsertTextFormat::SNIPPET),
12344 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12345 lsp::InsertReplaceEdit {
12346 new_text: snippet.body.clone(),
12347 insert: lsp_range,
12348 replace: lsp_range,
12349 },
12350 )),
12351 filter_text: Some(snippet.body.clone()),
12352 sort_text: Some(char::MAX.to_string()),
12353 ..Default::default()
12354 },
12355 confirm: None,
12356 })
12357 })
12358 .collect()
12359}
12360
12361impl CompletionProvider for Model<Project> {
12362 fn completions(
12363 &self,
12364 buffer: &Model<Buffer>,
12365 buffer_position: text::Anchor,
12366 options: CompletionContext,
12367 cx: &mut ViewContext<Editor>,
12368 ) -> Task<Result<Vec<Completion>>> {
12369 self.update(cx, |project, cx| {
12370 let snippets = snippet_completions(project, buffer, buffer_position, cx);
12371 let project_completions = project.completions(&buffer, buffer_position, options, cx);
12372 cx.background_executor().spawn(async move {
12373 let mut completions = project_completions.await?;
12374 //let snippets = snippets.into_iter().;
12375 completions.extend(snippets);
12376 Ok(completions)
12377 })
12378 })
12379 }
12380
12381 fn resolve_completions(
12382 &self,
12383 buffer: Model<Buffer>,
12384 completion_indices: Vec<usize>,
12385 completions: Arc<RwLock<Box<[Completion]>>>,
12386 cx: &mut ViewContext<Editor>,
12387 ) -> Task<Result<bool>> {
12388 self.update(cx, |project, cx| {
12389 project.resolve_completions(buffer, completion_indices, completions, cx)
12390 })
12391 }
12392
12393 fn apply_additional_edits_for_completion(
12394 &self,
12395 buffer: Model<Buffer>,
12396 completion: Completion,
12397 push_to_history: bool,
12398 cx: &mut ViewContext<Editor>,
12399 ) -> Task<Result<Option<language::Transaction>>> {
12400 self.update(cx, |project, cx| {
12401 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12402 })
12403 }
12404
12405 fn is_completion_trigger(
12406 &self,
12407 buffer: &Model<Buffer>,
12408 position: language::Anchor,
12409 text: &str,
12410 trigger_in_words: bool,
12411 cx: &mut ViewContext<Editor>,
12412 ) -> bool {
12413 if !EditorSettings::get_global(cx).show_completions_on_input {
12414 return false;
12415 }
12416
12417 let mut chars = text.chars();
12418 let char = if let Some(char) = chars.next() {
12419 char
12420 } else {
12421 return false;
12422 };
12423 if chars.next().is_some() {
12424 return false;
12425 }
12426
12427 let buffer = buffer.read(cx);
12428 let scope = buffer.snapshot().language_scope_at(position);
12429 if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
12430 return true;
12431 }
12432
12433 buffer
12434 .completion_triggers()
12435 .iter()
12436 .any(|string| string == text)
12437 }
12438}
12439
12440fn inlay_hint_settings(
12441 location: Anchor,
12442 snapshot: &MultiBufferSnapshot,
12443 cx: &mut ViewContext<'_, Editor>,
12444) -> InlayHintSettings {
12445 let file = snapshot.file_at(location);
12446 let language = snapshot.language_at(location);
12447 let settings = all_language_settings(file, cx);
12448 settings
12449 .language(language.map(|l| l.name()).as_deref())
12450 .inlay_hints
12451}
12452
12453fn consume_contiguous_rows(
12454 contiguous_row_selections: &mut Vec<Selection<Point>>,
12455 selection: &Selection<Point>,
12456 display_map: &DisplaySnapshot,
12457 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12458) -> (MultiBufferRow, MultiBufferRow) {
12459 contiguous_row_selections.push(selection.clone());
12460 let start_row = MultiBufferRow(selection.start.row);
12461 let mut end_row = ending_row(selection, display_map);
12462
12463 while let Some(next_selection) = selections.peek() {
12464 if next_selection.start.row <= end_row.0 {
12465 end_row = ending_row(next_selection, display_map);
12466 contiguous_row_selections.push(selections.next().unwrap().clone());
12467 } else {
12468 break;
12469 }
12470 }
12471 (start_row, end_row)
12472}
12473
12474fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12475 if next_selection.end.column > 0 || next_selection.is_empty() {
12476 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12477 } else {
12478 MultiBufferRow(next_selection.end.row)
12479 }
12480}
12481
12482impl EditorSnapshot {
12483 pub fn remote_selections_in_range<'a>(
12484 &'a self,
12485 range: &'a Range<Anchor>,
12486 collaboration_hub: &dyn CollaborationHub,
12487 cx: &'a AppContext,
12488 ) -> impl 'a + Iterator<Item = RemoteSelection> {
12489 let participant_names = collaboration_hub.user_names(cx);
12490 let participant_indices = collaboration_hub.user_participant_indices(cx);
12491 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12492 let collaborators_by_replica_id = collaborators_by_peer_id
12493 .iter()
12494 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12495 .collect::<HashMap<_, _>>();
12496 self.buffer_snapshot
12497 .selections_in_range(range, false)
12498 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12499 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12500 let participant_index = participant_indices.get(&collaborator.user_id).copied();
12501 let user_name = participant_names.get(&collaborator.user_id).cloned();
12502 Some(RemoteSelection {
12503 replica_id,
12504 selection,
12505 cursor_shape,
12506 line_mode,
12507 participant_index,
12508 peer_id: collaborator.peer_id,
12509 user_name,
12510 })
12511 })
12512 }
12513
12514 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12515 self.display_snapshot.buffer_snapshot.language_at(position)
12516 }
12517
12518 pub fn is_focused(&self) -> bool {
12519 self.is_focused
12520 }
12521
12522 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12523 self.placeholder_text.as_ref()
12524 }
12525
12526 pub fn scroll_position(&self) -> gpui::Point<f32> {
12527 self.scroll_anchor.scroll_position(&self.display_snapshot)
12528 }
12529
12530 fn gutter_dimensions(
12531 &self,
12532 font_id: FontId,
12533 font_size: Pixels,
12534 em_width: Pixels,
12535 max_line_number_width: Pixels,
12536 cx: &AppContext,
12537 ) -> GutterDimensions {
12538 if !self.show_gutter {
12539 return GutterDimensions::default();
12540 }
12541 let descent = cx.text_system().descent(font_id, font_size);
12542
12543 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12544 matches!(
12545 ProjectSettings::get_global(cx).git.git_gutter,
12546 Some(GitGutterSetting::TrackedFiles)
12547 )
12548 });
12549 let gutter_settings = EditorSettings::get_global(cx).gutter;
12550 let show_line_numbers = self
12551 .show_line_numbers
12552 .unwrap_or(gutter_settings.line_numbers);
12553 let line_gutter_width = if show_line_numbers {
12554 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12555 let min_width_for_number_on_gutter = em_width * 4.0;
12556 max_line_number_width.max(min_width_for_number_on_gutter)
12557 } else {
12558 0.0.into()
12559 };
12560
12561 let show_code_actions = self
12562 .show_code_actions
12563 .unwrap_or(gutter_settings.code_actions);
12564
12565 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12566
12567 let git_blame_entries_width = self
12568 .render_git_blame_gutter
12569 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12570
12571 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12572 left_padding += if show_code_actions || show_runnables {
12573 em_width * 3.0
12574 } else if show_git_gutter && show_line_numbers {
12575 em_width * 2.0
12576 } else if show_git_gutter || show_line_numbers {
12577 em_width
12578 } else {
12579 px(0.)
12580 };
12581
12582 let right_padding = if gutter_settings.folds && show_line_numbers {
12583 em_width * 4.0
12584 } else if gutter_settings.folds {
12585 em_width * 3.0
12586 } else if show_line_numbers {
12587 em_width
12588 } else {
12589 px(0.)
12590 };
12591
12592 GutterDimensions {
12593 left_padding,
12594 right_padding,
12595 width: line_gutter_width + left_padding + right_padding,
12596 margin: -descent,
12597 git_blame_entries_width,
12598 }
12599 }
12600
12601 pub fn render_fold_toggle(
12602 &self,
12603 buffer_row: MultiBufferRow,
12604 row_contains_cursor: bool,
12605 editor: View<Editor>,
12606 cx: &mut WindowContext,
12607 ) -> Option<AnyElement> {
12608 let folded = self.is_line_folded(buffer_row);
12609
12610 if let Some(crease) = self
12611 .crease_snapshot
12612 .query_row(buffer_row, &self.buffer_snapshot)
12613 {
12614 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12615 if folded {
12616 editor.update(cx, |editor, cx| {
12617 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12618 });
12619 } else {
12620 editor.update(cx, |editor, cx| {
12621 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12622 });
12623 }
12624 });
12625
12626 Some((crease.render_toggle)(
12627 buffer_row,
12628 folded,
12629 toggle_callback,
12630 cx,
12631 ))
12632 } else if folded
12633 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12634 {
12635 Some(
12636 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12637 .selected(folded)
12638 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12639 if folded {
12640 this.unfold_at(&UnfoldAt { buffer_row }, cx);
12641 } else {
12642 this.fold_at(&FoldAt { buffer_row }, cx);
12643 }
12644 }))
12645 .into_any_element(),
12646 )
12647 } else {
12648 None
12649 }
12650 }
12651
12652 pub fn render_crease_trailer(
12653 &self,
12654 buffer_row: MultiBufferRow,
12655 cx: &mut WindowContext,
12656 ) -> Option<AnyElement> {
12657 let folded = self.is_line_folded(buffer_row);
12658 let crease = self
12659 .crease_snapshot
12660 .query_row(buffer_row, &self.buffer_snapshot)?;
12661 Some((crease.render_trailer)(buffer_row, folded, cx))
12662 }
12663}
12664
12665impl Deref for EditorSnapshot {
12666 type Target = DisplaySnapshot;
12667
12668 fn deref(&self) -> &Self::Target {
12669 &self.display_snapshot
12670 }
12671}
12672
12673#[derive(Clone, Debug, PartialEq, Eq)]
12674pub enum EditorEvent {
12675 InputIgnored {
12676 text: Arc<str>,
12677 },
12678 InputHandled {
12679 utf16_range_to_replace: Option<Range<isize>>,
12680 text: Arc<str>,
12681 },
12682 ExcerptsAdded {
12683 buffer: Model<Buffer>,
12684 predecessor: ExcerptId,
12685 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12686 },
12687 ExcerptsRemoved {
12688 ids: Vec<ExcerptId>,
12689 },
12690 ExcerptsEdited {
12691 ids: Vec<ExcerptId>,
12692 },
12693 ExcerptsExpanded {
12694 ids: Vec<ExcerptId>,
12695 },
12696 BufferEdited,
12697 Edited {
12698 transaction_id: clock::Lamport,
12699 },
12700 Reparsed(BufferId),
12701 Focused,
12702 FocusedIn,
12703 Blurred,
12704 DirtyChanged,
12705 Saved,
12706 TitleChanged,
12707 DiffBaseChanged,
12708 SelectionsChanged {
12709 local: bool,
12710 },
12711 ScrollPositionChanged {
12712 local: bool,
12713 autoscroll: bool,
12714 },
12715 Closed,
12716 TransactionUndone {
12717 transaction_id: clock::Lamport,
12718 },
12719 TransactionBegun {
12720 transaction_id: clock::Lamport,
12721 },
12722}
12723
12724impl EventEmitter<EditorEvent> for Editor {}
12725
12726impl FocusableView for Editor {
12727 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12728 self.focus_handle.clone()
12729 }
12730}
12731
12732impl Render for Editor {
12733 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12734 let settings = ThemeSettings::get_global(cx);
12735
12736 let text_style = match self.mode {
12737 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12738 color: cx.theme().colors().editor_foreground,
12739 font_family: settings.ui_font.family.clone(),
12740 font_features: settings.ui_font.features.clone(),
12741 font_fallbacks: settings.ui_font.fallbacks.clone(),
12742 font_size: rems(0.875).into(),
12743 font_weight: settings.ui_font.weight,
12744 line_height: relative(settings.buffer_line_height.value()),
12745 ..Default::default()
12746 },
12747 EditorMode::Full => TextStyle {
12748 color: cx.theme().colors().editor_foreground,
12749 font_family: settings.buffer_font.family.clone(),
12750 font_features: settings.buffer_font.features.clone(),
12751 font_fallbacks: settings.buffer_font.fallbacks.clone(),
12752 font_size: settings.buffer_font_size(cx).into(),
12753 font_weight: settings.buffer_font.weight,
12754 line_height: relative(settings.buffer_line_height.value()),
12755 ..Default::default()
12756 },
12757 };
12758
12759 let background = match self.mode {
12760 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12761 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12762 EditorMode::Full => cx.theme().colors().editor_background,
12763 };
12764
12765 EditorElement::new(
12766 cx.view(),
12767 EditorStyle {
12768 background,
12769 local_player: cx.theme().players().local(),
12770 text: text_style,
12771 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12772 syntax: cx.theme().syntax().clone(),
12773 status: cx.theme().status().clone(),
12774 inlay_hints_style: HighlightStyle {
12775 color: Some(cx.theme().status().hint),
12776 ..HighlightStyle::default()
12777 },
12778 suggestions_style: HighlightStyle {
12779 color: Some(cx.theme().status().predictive),
12780 ..HighlightStyle::default()
12781 },
12782 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
12783 },
12784 )
12785 }
12786}
12787
12788impl ViewInputHandler for Editor {
12789 fn text_for_range(
12790 &mut self,
12791 range_utf16: Range<usize>,
12792 cx: &mut ViewContext<Self>,
12793 ) -> Option<String> {
12794 Some(
12795 self.buffer
12796 .read(cx)
12797 .read(cx)
12798 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12799 .collect(),
12800 )
12801 }
12802
12803 fn selected_text_range(
12804 &mut self,
12805 ignore_disabled_input: bool,
12806 cx: &mut ViewContext<Self>,
12807 ) -> Option<UTF16Selection> {
12808 // Prevent the IME menu from appearing when holding down an alphabetic key
12809 // while input is disabled.
12810 if !ignore_disabled_input && !self.input_enabled {
12811 return None;
12812 }
12813
12814 let selection = self.selections.newest::<OffsetUtf16>(cx);
12815 let range = selection.range();
12816
12817 Some(UTF16Selection {
12818 range: range.start.0..range.end.0,
12819 reversed: selection.reversed,
12820 })
12821 }
12822
12823 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12824 let snapshot = self.buffer.read(cx).read(cx);
12825 let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
12826 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12827 }
12828
12829 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12830 self.clear_highlights::<InputComposition>(cx);
12831 self.ime_transaction.take();
12832 }
12833
12834 fn replace_text_in_range(
12835 &mut self,
12836 range_utf16: Option<Range<usize>>,
12837 text: &str,
12838 cx: &mut ViewContext<Self>,
12839 ) {
12840 if !self.input_enabled {
12841 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12842 return;
12843 }
12844
12845 self.transact(cx, |this, cx| {
12846 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12847 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12848 Some(this.selection_replacement_ranges(range_utf16, cx))
12849 } else {
12850 this.marked_text_ranges(cx)
12851 };
12852
12853 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12854 let newest_selection_id = this.selections.newest_anchor().id;
12855 this.selections
12856 .all::<OffsetUtf16>(cx)
12857 .iter()
12858 .zip(ranges_to_replace.iter())
12859 .find_map(|(selection, range)| {
12860 if selection.id == newest_selection_id {
12861 Some(
12862 (range.start.0 as isize - selection.head().0 as isize)
12863 ..(range.end.0 as isize - selection.head().0 as isize),
12864 )
12865 } else {
12866 None
12867 }
12868 })
12869 });
12870
12871 cx.emit(EditorEvent::InputHandled {
12872 utf16_range_to_replace: range_to_replace,
12873 text: text.into(),
12874 });
12875
12876 if let Some(new_selected_ranges) = new_selected_ranges {
12877 this.change_selections(None, cx, |selections| {
12878 selections.select_ranges(new_selected_ranges)
12879 });
12880 this.backspace(&Default::default(), cx);
12881 }
12882
12883 this.handle_input(text, cx);
12884 });
12885
12886 if let Some(transaction) = self.ime_transaction {
12887 self.buffer.update(cx, |buffer, cx| {
12888 buffer.group_until_transaction(transaction, cx);
12889 });
12890 }
12891
12892 self.unmark_text(cx);
12893 }
12894
12895 fn replace_and_mark_text_in_range(
12896 &mut self,
12897 range_utf16: Option<Range<usize>>,
12898 text: &str,
12899 new_selected_range_utf16: Option<Range<usize>>,
12900 cx: &mut ViewContext<Self>,
12901 ) {
12902 if !self.input_enabled {
12903 return;
12904 }
12905
12906 let transaction = self.transact(cx, |this, cx| {
12907 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12908 let snapshot = this.buffer.read(cx).read(cx);
12909 if let Some(relative_range_utf16) = range_utf16.as_ref() {
12910 for marked_range in &mut marked_ranges {
12911 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12912 marked_range.start.0 += relative_range_utf16.start;
12913 marked_range.start =
12914 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12915 marked_range.end =
12916 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12917 }
12918 }
12919 Some(marked_ranges)
12920 } else if let Some(range_utf16) = range_utf16 {
12921 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12922 Some(this.selection_replacement_ranges(range_utf16, cx))
12923 } else {
12924 None
12925 };
12926
12927 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12928 let newest_selection_id = this.selections.newest_anchor().id;
12929 this.selections
12930 .all::<OffsetUtf16>(cx)
12931 .iter()
12932 .zip(ranges_to_replace.iter())
12933 .find_map(|(selection, range)| {
12934 if selection.id == newest_selection_id {
12935 Some(
12936 (range.start.0 as isize - selection.head().0 as isize)
12937 ..(range.end.0 as isize - selection.head().0 as isize),
12938 )
12939 } else {
12940 None
12941 }
12942 })
12943 });
12944
12945 cx.emit(EditorEvent::InputHandled {
12946 utf16_range_to_replace: range_to_replace,
12947 text: text.into(),
12948 });
12949
12950 if let Some(ranges) = ranges_to_replace {
12951 this.change_selections(None, cx, |s| s.select_ranges(ranges));
12952 }
12953
12954 let marked_ranges = {
12955 let snapshot = this.buffer.read(cx).read(cx);
12956 this.selections
12957 .disjoint_anchors()
12958 .iter()
12959 .map(|selection| {
12960 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12961 })
12962 .collect::<Vec<_>>()
12963 };
12964
12965 if text.is_empty() {
12966 this.unmark_text(cx);
12967 } else {
12968 this.highlight_text::<InputComposition>(
12969 marked_ranges.clone(),
12970 HighlightStyle {
12971 underline: Some(UnderlineStyle {
12972 thickness: px(1.),
12973 color: None,
12974 wavy: false,
12975 }),
12976 ..Default::default()
12977 },
12978 cx,
12979 );
12980 }
12981
12982 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12983 let use_autoclose = this.use_autoclose;
12984 let use_auto_surround = this.use_auto_surround;
12985 this.set_use_autoclose(false);
12986 this.set_use_auto_surround(false);
12987 this.handle_input(text, cx);
12988 this.set_use_autoclose(use_autoclose);
12989 this.set_use_auto_surround(use_auto_surround);
12990
12991 if let Some(new_selected_range) = new_selected_range_utf16 {
12992 let snapshot = this.buffer.read(cx).read(cx);
12993 let new_selected_ranges = marked_ranges
12994 .into_iter()
12995 .map(|marked_range| {
12996 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
12997 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
12998 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
12999 snapshot.clip_offset_utf16(new_start, Bias::Left)
13000 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13001 })
13002 .collect::<Vec<_>>();
13003
13004 drop(snapshot);
13005 this.change_selections(None, cx, |selections| {
13006 selections.select_ranges(new_selected_ranges)
13007 });
13008 }
13009 });
13010
13011 self.ime_transaction = self.ime_transaction.or(transaction);
13012 if let Some(transaction) = self.ime_transaction {
13013 self.buffer.update(cx, |buffer, cx| {
13014 buffer.group_until_transaction(transaction, cx);
13015 });
13016 }
13017
13018 if self.text_highlights::<InputComposition>(cx).is_none() {
13019 self.ime_transaction.take();
13020 }
13021 }
13022
13023 fn bounds_for_range(
13024 &mut self,
13025 range_utf16: Range<usize>,
13026 element_bounds: gpui::Bounds<Pixels>,
13027 cx: &mut ViewContext<Self>,
13028 ) -> Option<gpui::Bounds<Pixels>> {
13029 let text_layout_details = self.text_layout_details(cx);
13030 let style = &text_layout_details.editor_style;
13031 let font_id = cx.text_system().resolve_font(&style.text.font());
13032 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13033 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13034
13035 let em_width = cx
13036 .text_system()
13037 .typographic_bounds(font_id, font_size, 'm')
13038 .unwrap()
13039 .size
13040 .width;
13041
13042 let snapshot = self.snapshot(cx);
13043 let scroll_position = snapshot.scroll_position();
13044 let scroll_left = scroll_position.x * em_width;
13045
13046 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13047 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13048 + self.gutter_dimensions.width;
13049 let y = line_height * (start.row().as_f32() - scroll_position.y);
13050
13051 Some(Bounds {
13052 origin: element_bounds.origin + point(x, y),
13053 size: size(em_width, line_height),
13054 })
13055 }
13056}
13057
13058trait SelectionExt {
13059 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13060 fn spanned_rows(
13061 &self,
13062 include_end_if_at_line_start: bool,
13063 map: &DisplaySnapshot,
13064 ) -> Range<MultiBufferRow>;
13065}
13066
13067impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
13068 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
13069 let start = self
13070 .start
13071 .to_point(&map.buffer_snapshot)
13072 .to_display_point(map);
13073 let end = self
13074 .end
13075 .to_point(&map.buffer_snapshot)
13076 .to_display_point(map);
13077 if self.reversed {
13078 end..start
13079 } else {
13080 start..end
13081 }
13082 }
13083
13084 fn spanned_rows(
13085 &self,
13086 include_end_if_at_line_start: bool,
13087 map: &DisplaySnapshot,
13088 ) -> Range<MultiBufferRow> {
13089 let start = self.start.to_point(&map.buffer_snapshot);
13090 let mut end = self.end.to_point(&map.buffer_snapshot);
13091 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
13092 end.row -= 1;
13093 }
13094
13095 let buffer_start = map.prev_line_boundary(start).0;
13096 let buffer_end = map.next_line_boundary(end).0;
13097 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
13098 }
13099}
13100
13101impl<T: InvalidationRegion> InvalidationStack<T> {
13102 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
13103 where
13104 S: Clone + ToOffset,
13105 {
13106 while let Some(region) = self.last() {
13107 let all_selections_inside_invalidation_ranges =
13108 if selections.len() == region.ranges().len() {
13109 selections
13110 .iter()
13111 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
13112 .all(|(selection, invalidation_range)| {
13113 let head = selection.head().to_offset(buffer);
13114 invalidation_range.start <= head && invalidation_range.end >= head
13115 })
13116 } else {
13117 false
13118 };
13119
13120 if all_selections_inside_invalidation_ranges {
13121 break;
13122 } else {
13123 self.pop();
13124 }
13125 }
13126 }
13127}
13128
13129impl<T> Default for InvalidationStack<T> {
13130 fn default() -> Self {
13131 Self(Default::default())
13132 }
13133}
13134
13135impl<T> Deref for InvalidationStack<T> {
13136 type Target = Vec<T>;
13137
13138 fn deref(&self) -> &Self::Target {
13139 &self.0
13140 }
13141}
13142
13143impl<T> DerefMut for InvalidationStack<T> {
13144 fn deref_mut(&mut self) -> &mut Self::Target {
13145 &mut self.0
13146 }
13147}
13148
13149impl InvalidationRegion for SnippetState {
13150 fn ranges(&self) -> &[Range<Anchor>] {
13151 &self.ranges[self.active_index]
13152 }
13153}
13154
13155pub fn diagnostic_block_renderer(
13156 diagnostic: Diagnostic,
13157 max_message_rows: Option<u8>,
13158 allow_closing: bool,
13159 _is_valid: bool,
13160) -> RenderBlock {
13161 let (text_without_backticks, code_ranges) =
13162 highlight_diagnostic_message(&diagnostic, max_message_rows);
13163
13164 Box::new(move |cx: &mut BlockContext| {
13165 let group_id: SharedString = cx.block_id.to_string().into();
13166
13167 let mut text_style = cx.text_style().clone();
13168 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13169 let theme_settings = ThemeSettings::get_global(cx);
13170 text_style.font_family = theme_settings.buffer_font.family.clone();
13171 text_style.font_style = theme_settings.buffer_font.style;
13172 text_style.font_features = theme_settings.buffer_font.features.clone();
13173 text_style.font_weight = theme_settings.buffer_font.weight;
13174
13175 let multi_line_diagnostic = diagnostic.message.contains('\n');
13176
13177 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13178 if multi_line_diagnostic {
13179 v_flex()
13180 } else {
13181 h_flex()
13182 }
13183 .when(allow_closing, |div| {
13184 div.children(diagnostic.is_primary.then(|| {
13185 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13186 .icon_color(Color::Muted)
13187 .size(ButtonSize::Compact)
13188 .style(ButtonStyle::Transparent)
13189 .visible_on_hover(group_id.clone())
13190 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13191 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13192 }))
13193 })
13194 .child(
13195 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13196 .icon_color(Color::Muted)
13197 .size(ButtonSize::Compact)
13198 .style(ButtonStyle::Transparent)
13199 .visible_on_hover(group_id.clone())
13200 .on_click({
13201 let message = diagnostic.message.clone();
13202 move |_click, cx| {
13203 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13204 }
13205 })
13206 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13207 )
13208 };
13209
13210 let icon_size = buttons(&diagnostic, cx.block_id)
13211 .into_any_element()
13212 .layout_as_root(AvailableSpace::min_size(), cx);
13213
13214 h_flex()
13215 .id(cx.block_id)
13216 .group(group_id.clone())
13217 .relative()
13218 .size_full()
13219 .pl(cx.gutter_dimensions.width)
13220 .w(cx.max_width + cx.gutter_dimensions.width)
13221 .child(
13222 div()
13223 .flex()
13224 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13225 .flex_shrink(),
13226 )
13227 .child(buttons(&diagnostic, cx.block_id))
13228 .child(div().flex().flex_shrink_0().child(
13229 StyledText::new(text_without_backticks.clone()).with_highlights(
13230 &text_style,
13231 code_ranges.iter().map(|range| {
13232 (
13233 range.clone(),
13234 HighlightStyle {
13235 font_weight: Some(FontWeight::BOLD),
13236 ..Default::default()
13237 },
13238 )
13239 }),
13240 ),
13241 ))
13242 .into_any_element()
13243 })
13244}
13245
13246pub fn highlight_diagnostic_message(
13247 diagnostic: &Diagnostic,
13248 mut max_message_rows: Option<u8>,
13249) -> (SharedString, Vec<Range<usize>>) {
13250 let mut text_without_backticks = String::new();
13251 let mut code_ranges = Vec::new();
13252
13253 if let Some(source) = &diagnostic.source {
13254 text_without_backticks.push_str(&source);
13255 code_ranges.push(0..source.len());
13256 text_without_backticks.push_str(": ");
13257 }
13258
13259 let mut prev_offset = 0;
13260 let mut in_code_block = false;
13261 let has_row_limit = max_message_rows.is_some();
13262 let mut newline_indices = diagnostic
13263 .message
13264 .match_indices('\n')
13265 .filter(|_| has_row_limit)
13266 .map(|(ix, _)| ix)
13267 .fuse()
13268 .peekable();
13269
13270 for (quote_ix, _) in diagnostic
13271 .message
13272 .match_indices('`')
13273 .chain([(diagnostic.message.len(), "")])
13274 {
13275 let mut first_newline_ix = None;
13276 let mut last_newline_ix = None;
13277 while let Some(newline_ix) = newline_indices.peek() {
13278 if *newline_ix < quote_ix {
13279 if first_newline_ix.is_none() {
13280 first_newline_ix = Some(*newline_ix);
13281 }
13282 last_newline_ix = Some(*newline_ix);
13283
13284 if let Some(rows_left) = &mut max_message_rows {
13285 if *rows_left == 0 {
13286 break;
13287 } else {
13288 *rows_left -= 1;
13289 }
13290 }
13291 let _ = newline_indices.next();
13292 } else {
13293 break;
13294 }
13295 }
13296 let prev_len = text_without_backticks.len();
13297 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
13298 text_without_backticks.push_str(new_text);
13299 if in_code_block {
13300 code_ranges.push(prev_len..text_without_backticks.len());
13301 }
13302 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13303 in_code_block = !in_code_block;
13304 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13305 text_without_backticks.push_str("...");
13306 break;
13307 }
13308 }
13309
13310 (text_without_backticks.into(), code_ranges)
13311}
13312
13313fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13314 match severity {
13315 DiagnosticSeverity::ERROR => colors.error,
13316 DiagnosticSeverity::WARNING => colors.warning,
13317 DiagnosticSeverity::INFORMATION => colors.info,
13318 DiagnosticSeverity::HINT => colors.info,
13319 _ => colors.ignored,
13320 }
13321}
13322
13323pub fn styled_runs_for_code_label<'a>(
13324 label: &'a CodeLabel,
13325 syntax_theme: &'a theme::SyntaxTheme,
13326) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13327 let fade_out = HighlightStyle {
13328 fade_out: Some(0.35),
13329 ..Default::default()
13330 };
13331
13332 let mut prev_end = label.filter_range.end;
13333 label
13334 .runs
13335 .iter()
13336 .enumerate()
13337 .flat_map(move |(ix, (range, highlight_id))| {
13338 let style = if let Some(style) = highlight_id.style(syntax_theme) {
13339 style
13340 } else {
13341 return Default::default();
13342 };
13343 let mut muted_style = style;
13344 muted_style.highlight(fade_out);
13345
13346 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13347 if range.start >= label.filter_range.end {
13348 if range.start > prev_end {
13349 runs.push((prev_end..range.start, fade_out));
13350 }
13351 runs.push((range.clone(), muted_style));
13352 } else if range.end <= label.filter_range.end {
13353 runs.push((range.clone(), style));
13354 } else {
13355 runs.push((range.start..label.filter_range.end, style));
13356 runs.push((label.filter_range.end..range.end, muted_style));
13357 }
13358 prev_end = cmp::max(prev_end, range.end);
13359
13360 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13361 runs.push((prev_end..label.text.len(), fade_out));
13362 }
13363
13364 runs
13365 })
13366}
13367
13368pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13369 let mut prev_index = 0;
13370 let mut prev_codepoint: Option<char> = None;
13371 text.char_indices()
13372 .chain([(text.len(), '\0')])
13373 .filter_map(move |(index, codepoint)| {
13374 let prev_codepoint = prev_codepoint.replace(codepoint)?;
13375 let is_boundary = index == text.len()
13376 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13377 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13378 if is_boundary {
13379 let chunk = &text[prev_index..index];
13380 prev_index = index;
13381 Some(chunk)
13382 } else {
13383 None
13384 }
13385 })
13386}
13387
13388pub trait RangeToAnchorExt: Sized {
13389 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13390
13391 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13392 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13393 anchor_range.start.to_display_point(&snapshot)..anchor_range.end.to_display_point(&snapshot)
13394 }
13395}
13396
13397impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13398 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13399 let start_offset = self.start.to_offset(snapshot);
13400 let end_offset = self.end.to_offset(snapshot);
13401 if start_offset == end_offset {
13402 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13403 } else {
13404 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13405 }
13406 }
13407}
13408
13409pub trait RowExt {
13410 fn as_f32(&self) -> f32;
13411
13412 fn next_row(&self) -> Self;
13413
13414 fn previous_row(&self) -> Self;
13415
13416 fn minus(&self, other: Self) -> u32;
13417}
13418
13419impl RowExt for DisplayRow {
13420 fn as_f32(&self) -> f32 {
13421 self.0 as f32
13422 }
13423
13424 fn next_row(&self) -> Self {
13425 Self(self.0 + 1)
13426 }
13427
13428 fn previous_row(&self) -> Self {
13429 Self(self.0.saturating_sub(1))
13430 }
13431
13432 fn minus(&self, other: Self) -> u32 {
13433 self.0 - other.0
13434 }
13435}
13436
13437impl RowExt for MultiBufferRow {
13438 fn as_f32(&self) -> f32 {
13439 self.0 as f32
13440 }
13441
13442 fn next_row(&self) -> Self {
13443 Self(self.0 + 1)
13444 }
13445
13446 fn previous_row(&self) -> Self {
13447 Self(self.0.saturating_sub(1))
13448 }
13449
13450 fn minus(&self, other: Self) -> u32 {
13451 self.0 - other.0
13452 }
13453}
13454
13455trait RowRangeExt {
13456 type Row;
13457
13458 fn len(&self) -> usize;
13459
13460 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13461}
13462
13463impl RowRangeExt for Range<MultiBufferRow> {
13464 type Row = MultiBufferRow;
13465
13466 fn len(&self) -> usize {
13467 (self.end.0 - self.start.0) as usize
13468 }
13469
13470 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13471 (self.start.0..self.end.0).map(MultiBufferRow)
13472 }
13473}
13474
13475impl RowRangeExt for Range<DisplayRow> {
13476 type Row = DisplayRow;
13477
13478 fn len(&self) -> usize {
13479 (self.end.0 - self.start.0) as usize
13480 }
13481
13482 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13483 (self.start.0..self.end.0).map(DisplayRow)
13484 }
13485}
13486
13487fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13488 if hunk.diff_base_byte_range.is_empty() {
13489 DiffHunkStatus::Added
13490 } else if hunk.associated_range.is_empty() {
13491 DiffHunkStatus::Removed
13492 } else {
13493 DiffHunkStatus::Modified
13494 }
13495}
13496
13497/// If select range has more than one line, we
13498/// just point the cursor to range.start.
13499fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
13500 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
13501 range
13502 } else {
13503 range.start..range.start
13504 }
13505}