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 debounced_delay;
19pub mod display_map;
20mod editor_settings;
21mod editor_settings_controls;
22mod element;
23mod git;
24mod highlight_matching_bracket;
25mod hover_links;
26mod hover_popover;
27mod hunk_diff;
28mod indent_guides;
29mod inlay_hint_cache;
30mod inline_completion_provider;
31pub mod items;
32mod linked_editing_ranges;
33mod mouse_context_menu;
34pub mod movement;
35mod persistence;
36mod rust_analyzer_ext;
37pub mod scroll;
38mod selections_collection;
39pub mod tasks;
40
41#[cfg(test)]
42mod editor_tests;
43mod signature_help;
44#[cfg(any(test, feature = "test-support"))]
45pub mod test;
46
47use ::git::diff::{DiffHunk, DiffHunkStatus};
48use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
49pub(crate) use actions::*;
50use aho_corasick::AhoCorasick;
51use anyhow::{anyhow, Context as _, Result};
52use blink_manager::BlinkManager;
53use client::{Collaborator, ParticipantIndex};
54use clock::ReplicaId;
55use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
56use convert_case::{Case, Casing};
57use debounced_delay::DebouncedDelay;
58use display_map::*;
59pub use display_map::{DisplayPoint, FoldPlaceholder};
60pub use editor_settings::{CurrentLineHighlight, EditorSettings};
61pub use editor_settings_controls::*;
62use element::LineWithInvisibles;
63pub use element::{
64 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
65};
66use futures::FutureExt;
67use fuzzy::{StringMatch, StringMatchCandidate};
68use git::blame::GitBlame;
69use git::diff_hunk_to_display;
70use gpui::{
71 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
72 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardItem,
73 Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle, FocusOutEvent,
74 FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText, KeyContext,
75 ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString,
76 Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle, UnderlineStyle,
77 UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
78 WeakView, WindowContext,
79};
80use highlight_matching_bracket::refresh_matching_bracket_highlights;
81use hover_popover::{hide_hover, HoverState};
82use hunk_diff::ExpandedHunks;
83pub(crate) use hunk_diff::HoveredHunk;
84use indent_guides::ActiveIndentGuidesState;
85use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
86pub use inline_completion_provider::*;
87pub use items::MAX_TAB_TITLE_LEN;
88use itertools::Itertools;
89use language::{
90 char_kind,
91 language_settings::{self, all_language_settings, InlayHintSettings},
92 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
93 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
94 Point, Selection, SelectionGoal, TransactionId,
95};
96use language::{point_to_lsp, BufferRow, Runnable, RunnableRange};
97use linked_editing_ranges::refresh_linked_ranges;
98use task::{ResolvedTask, TaskTemplate, TaskVariables};
99
100use hover_links::{HoverLink, HoveredLinkState, InlayHighlight};
101pub use lsp::CompletionContext;
102use lsp::{
103 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
104 LanguageServerId,
105};
106use mouse_context_menu::MouseContextMenu;
107use movement::TextLayoutDetails;
108pub use multi_buffer::{
109 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
110 ToPoint,
111};
112use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
113use ordered_float::OrderedFloat;
114use parking_lot::{Mutex, RwLock};
115use project::project_settings::{GitGutterSetting, ProjectSettings};
116use project::{
117 CodeAction, Completion, FormatTrigger, Item, Location, Project, ProjectPath,
118 ProjectTransaction, TaskSourceKind, WorktreeId,
119};
120use rand::prelude::*;
121use rpc::{proto::*, ErrorExt};
122use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
123use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
124use serde::{Deserialize, Serialize};
125use settings::{update_settings_file, Settings, SettingsStore};
126use smallvec::SmallVec;
127use snippet::Snippet;
128use std::{
129 any::TypeId,
130 borrow::Cow,
131 cell::RefCell,
132 cmp::{self, Ordering, Reverse},
133 mem,
134 num::NonZeroU32,
135 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
136 path::{Path, PathBuf},
137 rc::Rc,
138 sync::Arc,
139 time::{Duration, Instant},
140};
141pub use sum_tree::Bias;
142use sum_tree::TreeMap;
143use text::{BufferId, OffsetUtf16, Rope};
144use theme::{
145 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
146 ThemeColors, ThemeSettings,
147};
148use ui::{
149 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
150 ListItem, Popover, Tooltip,
151};
152use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
153use workspace::item::{ItemHandle, PreviewTabsSettings};
154use workspace::notifications::{DetachAndPromptErr, NotificationId};
155use workspace::{
156 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
157};
158use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
159
160use crate::hover_links::find_url;
161use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
162
163pub const FILE_HEADER_HEIGHT: u8 = 1;
164pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u8 = 1;
165pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u8 = 1;
166pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
167const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
168const MAX_LINE_LEN: usize = 1024;
169const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
170const MAX_SELECTION_HISTORY_LEN: usize = 1024;
171pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
172#[doc(hidden)]
173pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
174#[doc(hidden)]
175pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
176
177pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
178
179pub fn render_parsed_markdown(
180 element_id: impl Into<ElementId>,
181 parsed: &language::ParsedMarkdown,
182 editor_style: &EditorStyle,
183 workspace: Option<WeakView<Workspace>>,
184 cx: &mut WindowContext,
185) -> InteractiveText {
186 let code_span_background_color = cx
187 .theme()
188 .colors()
189 .editor_document_highlight_read_background;
190
191 let highlights = gpui::combine_highlights(
192 parsed.highlights.iter().filter_map(|(range, highlight)| {
193 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
194 Some((range.clone(), highlight))
195 }),
196 parsed
197 .regions
198 .iter()
199 .zip(&parsed.region_ranges)
200 .filter_map(|(region, range)| {
201 if region.code {
202 Some((
203 range.clone(),
204 HighlightStyle {
205 background_color: Some(code_span_background_color),
206 ..Default::default()
207 },
208 ))
209 } else {
210 None
211 }
212 }),
213 );
214
215 let mut links = Vec::new();
216 let mut link_ranges = Vec::new();
217 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
218 if let Some(link) = region.link.clone() {
219 links.push(link);
220 link_ranges.push(range.clone());
221 }
222 }
223
224 InteractiveText::new(
225 element_id,
226 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
227 )
228 .on_click(link_ranges, move |clicked_range_ix, cx| {
229 match &links[clicked_range_ix] {
230 markdown::Link::Web { url } => cx.open_url(url),
231 markdown::Link::Path { path } => {
232 if let Some(workspace) = &workspace {
233 _ = workspace.update(cx, |workspace, cx| {
234 workspace.open_abs_path(path.clone(), false, cx).detach();
235 });
236 }
237 }
238 }
239 })
240}
241
242#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
243pub(crate) enum InlayId {
244 Suggestion(usize),
245 Hint(usize),
246}
247
248impl InlayId {
249 fn id(&self) -> usize {
250 match self {
251 Self::Suggestion(id) => *id,
252 Self::Hint(id) => *id,
253 }
254 }
255}
256
257enum DiffRowHighlight {}
258enum DocumentHighlightRead {}
259enum DocumentHighlightWrite {}
260enum InputComposition {}
261
262#[derive(Copy, Clone, PartialEq, Eq)]
263pub enum Direction {
264 Prev,
265 Next,
266}
267
268pub fn init_settings(cx: &mut AppContext) {
269 EditorSettings::register(cx);
270}
271
272pub fn init(cx: &mut AppContext) {
273 init_settings(cx);
274
275 workspace::register_project_item::<Editor>(cx);
276 workspace::FollowableViewRegistry::register::<Editor>(cx);
277 workspace::register_serializable_item::<Editor>(cx);
278
279 cx.observe_new_views(
280 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
281 workspace.register_action(Editor::new_file);
282 workspace.register_action(Editor::new_file_in_direction);
283 },
284 )
285 .detach();
286
287 cx.on_action(move |_: &workspace::NewFile, cx| {
288 let app_state = workspace::AppState::global(cx);
289 if let Some(app_state) = app_state.upgrade() {
290 workspace::open_new(app_state, cx, |workspace, cx| {
291 Editor::new_file(workspace, &Default::default(), cx)
292 })
293 .detach();
294 }
295 });
296 cx.on_action(move |_: &workspace::NewWindow, cx| {
297 let app_state = workspace::AppState::global(cx);
298 if let Some(app_state) = app_state.upgrade() {
299 workspace::open_new(app_state, cx, |workspace, cx| {
300 Editor::new_file(workspace, &Default::default(), cx)
301 })
302 .detach();
303 }
304 });
305}
306
307pub struct SearchWithinRange;
308
309trait InvalidationRegion {
310 fn ranges(&self) -> &[Range<Anchor>];
311}
312
313#[derive(Clone, Debug, PartialEq)]
314pub enum SelectPhase {
315 Begin {
316 position: DisplayPoint,
317 add: bool,
318 click_count: usize,
319 },
320 BeginColumnar {
321 position: DisplayPoint,
322 reset: bool,
323 goal_column: u32,
324 },
325 Extend {
326 position: DisplayPoint,
327 click_count: usize,
328 },
329 Update {
330 position: DisplayPoint,
331 goal_column: u32,
332 scroll_delta: gpui::Point<f32>,
333 },
334 End,
335}
336
337#[derive(Clone, Debug)]
338pub enum SelectMode {
339 Character,
340 Word(Range<Anchor>),
341 Line(Range<Anchor>),
342 All,
343}
344
345#[derive(Copy, Clone, PartialEq, Eq, Debug)]
346pub enum EditorMode {
347 SingleLine { auto_width: bool },
348 AutoHeight { max_lines: usize },
349 Full,
350}
351
352#[derive(Clone, Debug)]
353pub enum SoftWrap {
354 None,
355 PreferLine,
356 EditorWidth,
357 Column(u32),
358}
359
360#[derive(Clone)]
361pub struct EditorStyle {
362 pub background: Hsla,
363 pub local_player: PlayerColor,
364 pub text: TextStyle,
365 pub scrollbar_width: Pixels,
366 pub syntax: Arc<SyntaxTheme>,
367 pub status: StatusColors,
368 pub inlay_hints_style: HighlightStyle,
369 pub suggestions_style: HighlightStyle,
370}
371
372impl Default for EditorStyle {
373 fn default() -> Self {
374 Self {
375 background: Hsla::default(),
376 local_player: PlayerColor::default(),
377 text: TextStyle::default(),
378 scrollbar_width: Pixels::default(),
379 syntax: Default::default(),
380 // HACK: Status colors don't have a real default.
381 // We should look into removing the status colors from the editor
382 // style and retrieve them directly from the theme.
383 status: StatusColors::dark(),
384 inlay_hints_style: HighlightStyle::default(),
385 suggestions_style: HighlightStyle::default(),
386 }
387 }
388}
389
390type CompletionId = usize;
391
392#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
393struct EditorActionId(usize);
394
395impl EditorActionId {
396 pub fn post_inc(&mut self) -> Self {
397 let answer = self.0;
398
399 *self = Self(answer + 1);
400
401 Self(answer)
402 }
403}
404
405// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
406// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
407
408type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
409type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
410
411struct ScrollbarMarkerState {
412 scrollbar_size: Size<Pixels>,
413 dirty: bool,
414 markers: Arc<[PaintQuad]>,
415 pending_refresh: Option<Task<Result<()>>>,
416}
417
418impl ScrollbarMarkerState {
419 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
420 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
421 }
422}
423
424impl Default for ScrollbarMarkerState {
425 fn default() -> Self {
426 Self {
427 scrollbar_size: Size::default(),
428 dirty: false,
429 markers: Arc::from([]),
430 pending_refresh: None,
431 }
432 }
433}
434
435#[derive(Clone, Debug)]
436struct RunnableTasks {
437 templates: Vec<(TaskSourceKind, TaskTemplate)>,
438 offset: MultiBufferOffset,
439 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
440 column: u32,
441 // Values of all named captures, including those starting with '_'
442 extra_variables: HashMap<String, String>,
443 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
444 context_range: Range<BufferOffset>,
445}
446
447#[derive(Clone)]
448struct ResolvedTasks {
449 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
450 position: Anchor,
451}
452#[derive(Copy, Clone, Debug)]
453struct MultiBufferOffset(usize);
454#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
455struct BufferOffset(usize);
456/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
457///
458/// See the [module level documentation](self) for more information.
459pub struct Editor {
460 focus_handle: FocusHandle,
461 last_focused_descendant: Option<WeakFocusHandle>,
462 /// The text buffer being edited
463 buffer: Model<MultiBuffer>,
464 /// Map of how text in the buffer should be displayed.
465 /// Handles soft wraps, folds, fake inlay text insertions, etc.
466 pub display_map: Model<DisplayMap>,
467 pub selections: SelectionsCollection,
468 pub scroll_manager: ScrollManager,
469 /// When inline assist editors are linked, they all render cursors because
470 /// typing enters text into each of them, even the ones that aren't focused.
471 pub(crate) show_cursor_when_unfocused: bool,
472 columnar_selection_tail: Option<Anchor>,
473 add_selections_state: Option<AddSelectionsState>,
474 select_next_state: Option<SelectNextState>,
475 select_prev_state: Option<SelectNextState>,
476 selection_history: SelectionHistory,
477 autoclose_regions: Vec<AutocloseRegion>,
478 snippet_stack: InvalidationStack<SnippetState>,
479 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
480 ime_transaction: Option<TransactionId>,
481 active_diagnostics: Option<ActiveDiagnosticGroup>,
482 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
483 project: Option<Model<Project>>,
484 completion_provider: Option<Box<dyn CompletionProvider>>,
485 collaboration_hub: Option<Box<dyn CollaborationHub>>,
486 blink_manager: Model<BlinkManager>,
487 show_cursor_names: bool,
488 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
489 pub show_local_selections: bool,
490 mode: EditorMode,
491 show_breadcrumbs: bool,
492 show_gutter: bool,
493 redact_all: bool,
494 show_line_numbers: Option<bool>,
495 show_git_diff_gutter: Option<bool>,
496 show_code_actions: Option<bool>,
497 show_runnables: Option<bool>,
498 show_wrap_guides: Option<bool>,
499 show_indent_guides: Option<bool>,
500 placeholder_text: Option<Arc<str>>,
501 highlight_order: usize,
502 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
503 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
504 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
505 scrollbar_marker_state: ScrollbarMarkerState,
506 active_indent_guides_state: ActiveIndentGuidesState,
507 nav_history: Option<ItemNavHistory>,
508 context_menu: RwLock<Option<ContextMenu>>,
509 mouse_context_menu: Option<MouseContextMenu>,
510 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
511 signature_help_state: SignatureHelpState,
512 auto_signature_help: Option<bool>,
513 find_all_references_task_sources: Vec<Anchor>,
514 next_completion_id: CompletionId,
515 completion_documentation_pre_resolve_debounce: DebouncedDelay,
516 available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
517 code_actions_task: Option<Task<()>>,
518 document_highlights_task: Option<Task<()>>,
519 linked_editing_range_task: Option<Task<Option<()>>>,
520 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
521 pending_rename: Option<RenameState>,
522 searchable: bool,
523 cursor_shape: CursorShape,
524 current_line_highlight: Option<CurrentLineHighlight>,
525 collapse_matches: bool,
526 autoindent_mode: Option<AutoindentMode>,
527 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
528 keymap_context_layers: BTreeMap<TypeId, KeyContext>,
529 input_enabled: bool,
530 use_modal_editing: bool,
531 read_only: bool,
532 leader_peer_id: Option<PeerId>,
533 remote_id: Option<ViewId>,
534 hover_state: HoverState,
535 gutter_hovered: bool,
536 hovered_link_state: Option<HoveredLinkState>,
537 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
538 active_inline_completion: Option<(Inlay, Option<Range<Anchor>>)>,
539 show_inline_completions: bool,
540 inlay_hint_cache: InlayHintCache,
541 expanded_hunks: ExpandedHunks,
542 next_inlay_id: usize,
543 _subscriptions: Vec<Subscription>,
544 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
545 gutter_dimensions: GutterDimensions,
546 pub vim_replace_map: HashMap<Range<usize>, String>,
547 style: Option<EditorStyle>,
548 next_editor_action_id: EditorActionId,
549 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
550 use_autoclose: bool,
551 use_auto_surround: bool,
552 auto_replace_emoji_shortcode: bool,
553 show_git_blame_gutter: bool,
554 show_git_blame_inline: bool,
555 show_git_blame_inline_delay_task: Option<Task<()>>,
556 git_blame_inline_enabled: bool,
557 serialize_dirty_buffers: bool,
558 show_selection_menu: Option<bool>,
559 blame: Option<Model<GitBlame>>,
560 blame_subscription: Option<Subscription>,
561 custom_context_menu: Option<
562 Box<
563 dyn 'static
564 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
565 >,
566 >,
567 last_bounds: Option<Bounds<Pixels>>,
568 expect_bounds_change: Option<Bounds<Pixels>>,
569 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
570 tasks_update_task: Option<Task<()>>,
571 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
572 file_header_size: u8,
573 breadcrumb_header: Option<String>,
574 focused_block: Option<FocusedBlock>,
575}
576
577#[derive(Clone)]
578pub struct EditorSnapshot {
579 pub mode: EditorMode,
580 show_gutter: bool,
581 show_line_numbers: Option<bool>,
582 show_git_diff_gutter: Option<bool>,
583 show_code_actions: Option<bool>,
584 show_runnables: Option<bool>,
585 render_git_blame_gutter: bool,
586 pub display_snapshot: DisplaySnapshot,
587 pub placeholder_text: Option<Arc<str>>,
588 is_focused: bool,
589 scroll_anchor: ScrollAnchor,
590 ongoing_scroll: OngoingScroll,
591 current_line_highlight: CurrentLineHighlight,
592 gutter_hovered: bool,
593}
594
595const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
596
597#[derive(Debug, Clone, Copy)]
598pub struct GutterDimensions {
599 pub left_padding: Pixels,
600 pub right_padding: Pixels,
601 pub width: Pixels,
602 pub margin: Pixels,
603 pub git_blame_entries_width: Option<Pixels>,
604}
605
606impl GutterDimensions {
607 /// The full width of the space taken up by the gutter.
608 pub fn full_width(&self) -> Pixels {
609 self.margin + self.width
610 }
611
612 /// The width of the space reserved for the fold indicators,
613 /// use alongside 'justify_end' and `gutter_width` to
614 /// right align content with the line numbers
615 pub fn fold_area_width(&self) -> Pixels {
616 self.margin + self.right_padding
617 }
618}
619
620impl Default for GutterDimensions {
621 fn default() -> Self {
622 Self {
623 left_padding: Pixels::ZERO,
624 right_padding: Pixels::ZERO,
625 width: Pixels::ZERO,
626 margin: Pixels::ZERO,
627 git_blame_entries_width: None,
628 }
629 }
630}
631
632#[derive(Debug)]
633pub struct RemoteSelection {
634 pub replica_id: ReplicaId,
635 pub selection: Selection<Anchor>,
636 pub cursor_shape: CursorShape,
637 pub peer_id: PeerId,
638 pub line_mode: bool,
639 pub participant_index: Option<ParticipantIndex>,
640 pub user_name: Option<SharedString>,
641}
642
643#[derive(Clone, Debug)]
644struct SelectionHistoryEntry {
645 selections: Arc<[Selection<Anchor>]>,
646 select_next_state: Option<SelectNextState>,
647 select_prev_state: Option<SelectNextState>,
648 add_selections_state: Option<AddSelectionsState>,
649}
650
651enum SelectionHistoryMode {
652 Normal,
653 Undoing,
654 Redoing,
655}
656
657#[derive(Clone, PartialEq, Eq, Hash)]
658struct HoveredCursor {
659 replica_id: u16,
660 selection_id: usize,
661}
662
663impl Default for SelectionHistoryMode {
664 fn default() -> Self {
665 Self::Normal
666 }
667}
668
669#[derive(Default)]
670struct SelectionHistory {
671 #[allow(clippy::type_complexity)]
672 selections_by_transaction:
673 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
674 mode: SelectionHistoryMode,
675 undo_stack: VecDeque<SelectionHistoryEntry>,
676 redo_stack: VecDeque<SelectionHistoryEntry>,
677}
678
679impl SelectionHistory {
680 fn insert_transaction(
681 &mut self,
682 transaction_id: TransactionId,
683 selections: Arc<[Selection<Anchor>]>,
684 ) {
685 self.selections_by_transaction
686 .insert(transaction_id, (selections, None));
687 }
688
689 #[allow(clippy::type_complexity)]
690 fn transaction(
691 &self,
692 transaction_id: TransactionId,
693 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
694 self.selections_by_transaction.get(&transaction_id)
695 }
696
697 #[allow(clippy::type_complexity)]
698 fn transaction_mut(
699 &mut self,
700 transaction_id: TransactionId,
701 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
702 self.selections_by_transaction.get_mut(&transaction_id)
703 }
704
705 fn push(&mut self, entry: SelectionHistoryEntry) {
706 if !entry.selections.is_empty() {
707 match self.mode {
708 SelectionHistoryMode::Normal => {
709 self.push_undo(entry);
710 self.redo_stack.clear();
711 }
712 SelectionHistoryMode::Undoing => self.push_redo(entry),
713 SelectionHistoryMode::Redoing => self.push_undo(entry),
714 }
715 }
716 }
717
718 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
719 if self
720 .undo_stack
721 .back()
722 .map_or(true, |e| e.selections != entry.selections)
723 {
724 self.undo_stack.push_back(entry);
725 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
726 self.undo_stack.pop_front();
727 }
728 }
729 }
730
731 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
732 if self
733 .redo_stack
734 .back()
735 .map_or(true, |e| e.selections != entry.selections)
736 {
737 self.redo_stack.push_back(entry);
738 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
739 self.redo_stack.pop_front();
740 }
741 }
742 }
743}
744
745struct RowHighlight {
746 index: usize,
747 range: RangeInclusive<Anchor>,
748 color: Option<Hsla>,
749 should_autoscroll: bool,
750}
751
752#[derive(Clone, Debug)]
753struct AddSelectionsState {
754 above: bool,
755 stack: Vec<usize>,
756}
757
758#[derive(Clone)]
759struct SelectNextState {
760 query: AhoCorasick,
761 wordwise: bool,
762 done: bool,
763}
764
765impl std::fmt::Debug for SelectNextState {
766 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
767 f.debug_struct(std::any::type_name::<Self>())
768 .field("wordwise", &self.wordwise)
769 .field("done", &self.done)
770 .finish()
771 }
772}
773
774#[derive(Debug)]
775struct AutocloseRegion {
776 selection_id: usize,
777 range: Range<Anchor>,
778 pair: BracketPair,
779}
780
781#[derive(Debug)]
782struct SnippetState {
783 ranges: Vec<Vec<Range<Anchor>>>,
784 active_index: usize,
785}
786
787#[doc(hidden)]
788pub struct RenameState {
789 pub range: Range<Anchor>,
790 pub old_name: Arc<str>,
791 pub editor: View<Editor>,
792 block_id: CustomBlockId,
793}
794
795struct InvalidationStack<T>(Vec<T>);
796
797struct RegisteredInlineCompletionProvider {
798 provider: Arc<dyn InlineCompletionProviderHandle>,
799 _subscription: Subscription,
800}
801
802enum ContextMenu {
803 Completions(CompletionsMenu),
804 CodeActions(CodeActionsMenu),
805}
806
807impl ContextMenu {
808 fn select_first(
809 &mut self,
810 project: Option<&Model<Project>>,
811 cx: &mut ViewContext<Editor>,
812 ) -> bool {
813 if self.visible() {
814 match self {
815 ContextMenu::Completions(menu) => menu.select_first(project, cx),
816 ContextMenu::CodeActions(menu) => menu.select_first(cx),
817 }
818 true
819 } else {
820 false
821 }
822 }
823
824 fn select_prev(
825 &mut self,
826 project: Option<&Model<Project>>,
827 cx: &mut ViewContext<Editor>,
828 ) -> bool {
829 if self.visible() {
830 match self {
831 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
832 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
833 }
834 true
835 } else {
836 false
837 }
838 }
839
840 fn select_next(
841 &mut self,
842 project: Option<&Model<Project>>,
843 cx: &mut ViewContext<Editor>,
844 ) -> bool {
845 if self.visible() {
846 match self {
847 ContextMenu::Completions(menu) => menu.select_next(project, cx),
848 ContextMenu::CodeActions(menu) => menu.select_next(cx),
849 }
850 true
851 } else {
852 false
853 }
854 }
855
856 fn select_last(
857 &mut self,
858 project: Option<&Model<Project>>,
859 cx: &mut ViewContext<Editor>,
860 ) -> bool {
861 if self.visible() {
862 match self {
863 ContextMenu::Completions(menu) => menu.select_last(project, cx),
864 ContextMenu::CodeActions(menu) => menu.select_last(cx),
865 }
866 true
867 } else {
868 false
869 }
870 }
871
872 fn visible(&self) -> bool {
873 match self {
874 ContextMenu::Completions(menu) => menu.visible(),
875 ContextMenu::CodeActions(menu) => menu.visible(),
876 }
877 }
878
879 fn render(
880 &self,
881 cursor_position: DisplayPoint,
882 style: &EditorStyle,
883 max_height: Pixels,
884 workspace: Option<WeakView<Workspace>>,
885 cx: &mut ViewContext<Editor>,
886 ) -> (ContextMenuOrigin, AnyElement) {
887 match self {
888 ContextMenu::Completions(menu) => (
889 ContextMenuOrigin::EditorPoint(cursor_position),
890 menu.render(style, max_height, workspace, cx),
891 ),
892 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
893 }
894 }
895}
896
897enum ContextMenuOrigin {
898 EditorPoint(DisplayPoint),
899 GutterIndicator(DisplayRow),
900}
901
902#[derive(Clone)]
903struct CompletionsMenu {
904 id: CompletionId,
905 initial_position: Anchor,
906 buffer: Model<Buffer>,
907 completions: Arc<RwLock<Box<[Completion]>>>,
908 match_candidates: Arc<[StringMatchCandidate]>,
909 matches: Arc<[StringMatch]>,
910 selected_item: usize,
911 scroll_handle: UniformListScrollHandle,
912 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
913}
914
915impl CompletionsMenu {
916 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
917 self.selected_item = 0;
918 self.scroll_handle.scroll_to_item(self.selected_item);
919 self.attempt_resolve_selected_completion_documentation(project, cx);
920 cx.notify();
921 }
922
923 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
924 if self.selected_item > 0 {
925 self.selected_item -= 1;
926 } else {
927 self.selected_item = self.matches.len() - 1;
928 }
929 self.scroll_handle.scroll_to_item(self.selected_item);
930 self.attempt_resolve_selected_completion_documentation(project, cx);
931 cx.notify();
932 }
933
934 fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
935 if self.selected_item + 1 < self.matches.len() {
936 self.selected_item += 1;
937 } else {
938 self.selected_item = 0;
939 }
940 self.scroll_handle.scroll_to_item(self.selected_item);
941 self.attempt_resolve_selected_completion_documentation(project, cx);
942 cx.notify();
943 }
944
945 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
946 self.selected_item = self.matches.len() - 1;
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 pre_resolve_completion_documentation(
953 buffer: Model<Buffer>,
954 completions: Arc<RwLock<Box<[Completion]>>>,
955 matches: Arc<[StringMatch]>,
956 editor: &Editor,
957 cx: &mut ViewContext<Editor>,
958 ) -> Task<()> {
959 let settings = EditorSettings::get_global(cx);
960 if !settings.show_completion_documentation {
961 return Task::ready(());
962 }
963
964 let Some(provider) = editor.completion_provider.as_ref() else {
965 return Task::ready(());
966 };
967
968 let resolve_task = provider.resolve_completions(
969 buffer,
970 matches.iter().map(|m| m.candidate_id).collect(),
971 completions.clone(),
972 cx,
973 );
974
975 return cx.spawn(move |this, mut cx| async move {
976 if let Some(true) = resolve_task.await.log_err() {
977 this.update(&mut cx, |_, cx| cx.notify()).ok();
978 }
979 });
980 }
981
982 fn attempt_resolve_selected_completion_documentation(
983 &mut self,
984 project: Option<&Model<Project>>,
985 cx: &mut ViewContext<Editor>,
986 ) {
987 let settings = EditorSettings::get_global(cx);
988 if !settings.show_completion_documentation {
989 return;
990 }
991
992 let completion_index = self.matches[self.selected_item].candidate_id;
993 let Some(project) = project else {
994 return;
995 };
996
997 let resolve_task = project.update(cx, |project, cx| {
998 project.resolve_completions(
999 self.buffer.clone(),
1000 vec![completion_index],
1001 self.completions.clone(),
1002 cx,
1003 )
1004 });
1005
1006 let delay_ms =
1007 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1008 let delay = Duration::from_millis(delay_ms);
1009
1010 self.selected_completion_documentation_resolve_debounce
1011 .lock()
1012 .fire_new(delay, cx, |_, cx| {
1013 cx.spawn(move |this, mut cx| async move {
1014 if let Some(true) = resolve_task.await.log_err() {
1015 this.update(&mut cx, |_, cx| cx.notify()).ok();
1016 }
1017 })
1018 });
1019 }
1020
1021 fn visible(&self) -> bool {
1022 !self.matches.is_empty()
1023 }
1024
1025 fn render(
1026 &self,
1027 style: &EditorStyle,
1028 max_height: Pixels,
1029 workspace: Option<WeakView<Workspace>>,
1030 cx: &mut ViewContext<Editor>,
1031 ) -> AnyElement {
1032 let settings = EditorSettings::get_global(cx);
1033 let show_completion_documentation = settings.show_completion_documentation;
1034
1035 let widest_completion_ix = self
1036 .matches
1037 .iter()
1038 .enumerate()
1039 .max_by_key(|(_, mat)| {
1040 let completions = self.completions.read();
1041 let completion = &completions[mat.candidate_id];
1042 let documentation = &completion.documentation;
1043
1044 let mut len = completion.label.text.chars().count();
1045 if let Some(Documentation::SingleLine(text)) = documentation {
1046 if show_completion_documentation {
1047 len += text.chars().count();
1048 }
1049 }
1050
1051 len
1052 })
1053 .map(|(ix, _)| ix);
1054
1055 let completions = self.completions.clone();
1056 let matches = self.matches.clone();
1057 let selected_item = self.selected_item;
1058 let style = style.clone();
1059
1060 let multiline_docs = if show_completion_documentation {
1061 let mat = &self.matches[selected_item];
1062 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1063 Some(Documentation::MultiLinePlainText(text)) => {
1064 Some(div().child(SharedString::from(text.clone())))
1065 }
1066 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1067 Some(div().child(render_parsed_markdown(
1068 "completions_markdown",
1069 parsed,
1070 &style,
1071 workspace,
1072 cx,
1073 )))
1074 }
1075 _ => None,
1076 };
1077 multiline_docs.map(|div| {
1078 div.id("multiline_docs")
1079 .max_h(max_height)
1080 .flex_1()
1081 .px_1p5()
1082 .py_1()
1083 .min_w(px(260.))
1084 .max_w(px(640.))
1085 .w(px(500.))
1086 .overflow_y_scroll()
1087 .occlude()
1088 })
1089 } else {
1090 None
1091 };
1092
1093 let list = uniform_list(
1094 cx.view().clone(),
1095 "completions",
1096 matches.len(),
1097 move |_editor, range, cx| {
1098 let start_ix = range.start;
1099 let completions_guard = completions.read();
1100
1101 matches[range]
1102 .iter()
1103 .enumerate()
1104 .map(|(ix, mat)| {
1105 let item_ix = start_ix + ix;
1106 let candidate_id = mat.candidate_id;
1107 let completion = &completions_guard[candidate_id];
1108
1109 let documentation = if show_completion_documentation {
1110 &completion.documentation
1111 } else {
1112 &None
1113 };
1114
1115 let highlights = gpui::combine_highlights(
1116 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1117 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1118 |(range, mut highlight)| {
1119 // Ignore font weight for syntax highlighting, as we'll use it
1120 // for fuzzy matches.
1121 highlight.font_weight = None;
1122
1123 if completion.lsp_completion.deprecated.unwrap_or(false) {
1124 highlight.strikethrough = Some(StrikethroughStyle {
1125 thickness: 1.0.into(),
1126 ..Default::default()
1127 });
1128 highlight.color = Some(cx.theme().colors().text_muted);
1129 }
1130
1131 (range, highlight)
1132 },
1133 ),
1134 );
1135 let completion_label = StyledText::new(completion.label.text.clone())
1136 .with_highlights(&style.text, highlights);
1137 let documentation_label =
1138 if let Some(Documentation::SingleLine(text)) = documentation {
1139 if text.trim().is_empty() {
1140 None
1141 } else {
1142 Some(
1143 Label::new(text.clone())
1144 .ml_4()
1145 .size(LabelSize::Small)
1146 .color(Color::Muted),
1147 )
1148 }
1149 } else {
1150 None
1151 };
1152
1153 div().min_w(px(220.)).max_w(px(540.)).child(
1154 ListItem::new(mat.candidate_id)
1155 .inset(true)
1156 .selected(item_ix == selected_item)
1157 .on_click(cx.listener(move |editor, _event, cx| {
1158 cx.stop_propagation();
1159 if let Some(task) = editor.confirm_completion(
1160 &ConfirmCompletion {
1161 item_ix: Some(item_ix),
1162 },
1163 cx,
1164 ) {
1165 task.detach_and_log_err(cx)
1166 }
1167 }))
1168 .child(h_flex().overflow_hidden().child(completion_label))
1169 .end_slot::<Label>(documentation_label),
1170 )
1171 })
1172 .collect()
1173 },
1174 )
1175 .occlude()
1176 .max_h(max_height)
1177 .track_scroll(self.scroll_handle.clone())
1178 .with_width_from_item(widest_completion_ix)
1179 .with_sizing_behavior(ListSizingBehavior::Infer);
1180
1181 Popover::new()
1182 .child(list)
1183 .when_some(multiline_docs, |popover, multiline_docs| {
1184 popover.aside(multiline_docs)
1185 })
1186 .into_any_element()
1187 }
1188
1189 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1190 let mut matches = if let Some(query) = query {
1191 fuzzy::match_strings(
1192 &self.match_candidates,
1193 query,
1194 query.chars().any(|c| c.is_uppercase()),
1195 100,
1196 &Default::default(),
1197 executor,
1198 )
1199 .await
1200 } else {
1201 self.match_candidates
1202 .iter()
1203 .enumerate()
1204 .map(|(candidate_id, candidate)| StringMatch {
1205 candidate_id,
1206 score: Default::default(),
1207 positions: Default::default(),
1208 string: candidate.string.clone(),
1209 })
1210 .collect()
1211 };
1212
1213 // Remove all candidates where the query's start does not match the start of any word in the candidate
1214 if let Some(query) = query {
1215 if let Some(query_start) = query.chars().next() {
1216 matches.retain(|string_match| {
1217 split_words(&string_match.string).any(|word| {
1218 // Check that the first codepoint of the word as lowercase matches the first
1219 // codepoint of the query as lowercase
1220 word.chars()
1221 .flat_map(|codepoint| codepoint.to_lowercase())
1222 .zip(query_start.to_lowercase())
1223 .all(|(word_cp, query_cp)| word_cp == query_cp)
1224 })
1225 });
1226 }
1227 }
1228
1229 let completions = self.completions.read();
1230 matches.sort_unstable_by_key(|mat| {
1231 // We do want to strike a balance here between what the language server tells us
1232 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1233 // `Creat` and there is a local variable called `CreateComponent`).
1234 // So what we do is: we bucket all matches into two buckets
1235 // - Strong matches
1236 // - Weak matches
1237 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1238 // and the Weak matches are the rest.
1239 //
1240 // For the strong matches, we sort by the language-servers score first and for the weak
1241 // matches, we prefer our fuzzy finder first.
1242 //
1243 // The thinking behind that: it's useless to take the sort_text the language-server gives
1244 // us into account when it's obviously a bad match.
1245
1246 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1247 enum MatchScore<'a> {
1248 Strong {
1249 sort_text: Option<&'a str>,
1250 score: Reverse<OrderedFloat<f64>>,
1251 sort_key: (usize, &'a str),
1252 },
1253 Weak {
1254 score: Reverse<OrderedFloat<f64>>,
1255 sort_text: Option<&'a str>,
1256 sort_key: (usize, &'a str),
1257 },
1258 }
1259
1260 let completion = &completions[mat.candidate_id];
1261 let sort_key = completion.sort_key();
1262 let sort_text = completion.lsp_completion.sort_text.as_deref();
1263 let score = Reverse(OrderedFloat(mat.score));
1264
1265 if mat.score >= 0.2 {
1266 MatchScore::Strong {
1267 sort_text,
1268 score,
1269 sort_key,
1270 }
1271 } else {
1272 MatchScore::Weak {
1273 score,
1274 sort_text,
1275 sort_key,
1276 }
1277 }
1278 });
1279
1280 for mat in &mut matches {
1281 let completion = &completions[mat.candidate_id];
1282 mat.string.clone_from(&completion.label.text);
1283 for position in &mut mat.positions {
1284 *position += completion.label.filter_range.start;
1285 }
1286 }
1287 drop(completions);
1288
1289 self.matches = matches.into();
1290 self.selected_item = 0;
1291 }
1292}
1293
1294#[derive(Clone)]
1295struct CodeActionContents {
1296 tasks: Option<Arc<ResolvedTasks>>,
1297 actions: Option<Arc<[CodeAction]>>,
1298}
1299
1300impl CodeActionContents {
1301 fn len(&self) -> usize {
1302 match (&self.tasks, &self.actions) {
1303 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1304 (Some(tasks), None) => tasks.templates.len(),
1305 (None, Some(actions)) => actions.len(),
1306 (None, None) => 0,
1307 }
1308 }
1309
1310 fn is_empty(&self) -> bool {
1311 match (&self.tasks, &self.actions) {
1312 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1313 (Some(tasks), None) => tasks.templates.is_empty(),
1314 (None, Some(actions)) => actions.is_empty(),
1315 (None, None) => true,
1316 }
1317 }
1318
1319 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1320 self.tasks
1321 .iter()
1322 .flat_map(|tasks| {
1323 tasks
1324 .templates
1325 .iter()
1326 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1327 })
1328 .chain(self.actions.iter().flat_map(|actions| {
1329 actions
1330 .iter()
1331 .map(|action| CodeActionsItem::CodeAction(action.clone()))
1332 }))
1333 }
1334 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1335 match (&self.tasks, &self.actions) {
1336 (Some(tasks), Some(actions)) => {
1337 if index < tasks.templates.len() {
1338 tasks
1339 .templates
1340 .get(index)
1341 .cloned()
1342 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1343 } else {
1344 actions
1345 .get(index - tasks.templates.len())
1346 .cloned()
1347 .map(CodeActionsItem::CodeAction)
1348 }
1349 }
1350 (Some(tasks), None) => tasks
1351 .templates
1352 .get(index)
1353 .cloned()
1354 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1355 (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
1356 (None, None) => None,
1357 }
1358 }
1359}
1360
1361#[allow(clippy::large_enum_variant)]
1362#[derive(Clone)]
1363enum CodeActionsItem {
1364 Task(TaskSourceKind, ResolvedTask),
1365 CodeAction(CodeAction),
1366}
1367
1368impl CodeActionsItem {
1369 fn as_task(&self) -> Option<&ResolvedTask> {
1370 let Self::Task(_, task) = self else {
1371 return None;
1372 };
1373 Some(task)
1374 }
1375 fn as_code_action(&self) -> Option<&CodeAction> {
1376 let Self::CodeAction(action) = self else {
1377 return None;
1378 };
1379 Some(action)
1380 }
1381 fn label(&self) -> String {
1382 match self {
1383 Self::CodeAction(action) => action.lsp_action.title.clone(),
1384 Self::Task(_, task) => task.resolved_label.clone(),
1385 }
1386 }
1387}
1388
1389struct CodeActionsMenu {
1390 actions: CodeActionContents,
1391 buffer: Model<Buffer>,
1392 selected_item: usize,
1393 scroll_handle: UniformListScrollHandle,
1394 deployed_from_indicator: Option<DisplayRow>,
1395}
1396
1397impl CodeActionsMenu {
1398 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1399 self.selected_item = 0;
1400 self.scroll_handle.scroll_to_item(self.selected_item);
1401 cx.notify()
1402 }
1403
1404 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1405 if self.selected_item > 0 {
1406 self.selected_item -= 1;
1407 } else {
1408 self.selected_item = self.actions.len() - 1;
1409 }
1410 self.scroll_handle.scroll_to_item(self.selected_item);
1411 cx.notify();
1412 }
1413
1414 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1415 if self.selected_item + 1 < self.actions.len() {
1416 self.selected_item += 1;
1417 } else {
1418 self.selected_item = 0;
1419 }
1420 self.scroll_handle.scroll_to_item(self.selected_item);
1421 cx.notify();
1422 }
1423
1424 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1425 self.selected_item = self.actions.len() - 1;
1426 self.scroll_handle.scroll_to_item(self.selected_item);
1427 cx.notify()
1428 }
1429
1430 fn visible(&self) -> bool {
1431 !self.actions.is_empty()
1432 }
1433
1434 fn render(
1435 &self,
1436 cursor_position: DisplayPoint,
1437 _style: &EditorStyle,
1438 max_height: Pixels,
1439 cx: &mut ViewContext<Editor>,
1440 ) -> (ContextMenuOrigin, AnyElement) {
1441 let actions = self.actions.clone();
1442 let selected_item = self.selected_item;
1443 let element = uniform_list(
1444 cx.view().clone(),
1445 "code_actions_menu",
1446 self.actions.len(),
1447 move |_this, range, cx| {
1448 actions
1449 .iter()
1450 .skip(range.start)
1451 .take(range.end - range.start)
1452 .enumerate()
1453 .map(|(ix, action)| {
1454 let item_ix = range.start + ix;
1455 let selected = selected_item == item_ix;
1456 let colors = cx.theme().colors();
1457 div()
1458 .px_2()
1459 .text_color(colors.text)
1460 .when(selected, |style| {
1461 style
1462 .bg(colors.element_active)
1463 .text_color(colors.text_accent)
1464 })
1465 .hover(|style| {
1466 style
1467 .bg(colors.element_hover)
1468 .text_color(colors.text_accent)
1469 })
1470 .whitespace_nowrap()
1471 .when_some(action.as_code_action(), |this, action| {
1472 this.on_mouse_down(
1473 MouseButton::Left,
1474 cx.listener(move |editor, _, cx| {
1475 cx.stop_propagation();
1476 if let Some(task) = editor.confirm_code_action(
1477 &ConfirmCodeAction {
1478 item_ix: Some(item_ix),
1479 },
1480 cx,
1481 ) {
1482 task.detach_and_log_err(cx)
1483 }
1484 }),
1485 )
1486 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1487 .child(SharedString::from(action.lsp_action.title.clone()))
1488 })
1489 .when_some(action.as_task(), |this, task| {
1490 this.on_mouse_down(
1491 MouseButton::Left,
1492 cx.listener(move |editor, _, cx| {
1493 cx.stop_propagation();
1494 if let Some(task) = editor.confirm_code_action(
1495 &ConfirmCodeAction {
1496 item_ix: Some(item_ix),
1497 },
1498 cx,
1499 ) {
1500 task.detach_and_log_err(cx)
1501 }
1502 }),
1503 )
1504 .child(SharedString::from(task.resolved_label.clone()))
1505 })
1506 })
1507 .collect()
1508 },
1509 )
1510 .elevation_1(cx)
1511 .px_2()
1512 .py_1()
1513 .max_h(max_height)
1514 .occlude()
1515 .track_scroll(self.scroll_handle.clone())
1516 .with_width_from_item(
1517 self.actions
1518 .iter()
1519 .enumerate()
1520 .max_by_key(|(_, action)| match action {
1521 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1522 CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
1523 })
1524 .map(|(ix, _)| ix),
1525 )
1526 .with_sizing_behavior(ListSizingBehavior::Infer)
1527 .into_any_element();
1528
1529 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1530 ContextMenuOrigin::GutterIndicator(row)
1531 } else {
1532 ContextMenuOrigin::EditorPoint(cursor_position)
1533 };
1534
1535 (cursor_position, element)
1536 }
1537}
1538
1539#[derive(Debug)]
1540struct ActiveDiagnosticGroup {
1541 primary_range: Range<Anchor>,
1542 primary_message: String,
1543 group_id: usize,
1544 blocks: HashMap<CustomBlockId, Diagnostic>,
1545 is_valid: bool,
1546}
1547
1548#[derive(Serialize, Deserialize, Clone, Debug)]
1549pub struct ClipboardSelection {
1550 pub len: usize,
1551 pub is_entire_line: bool,
1552 pub first_line_indent: u32,
1553}
1554
1555#[derive(Debug)]
1556pub(crate) struct NavigationData {
1557 cursor_anchor: Anchor,
1558 cursor_position: Point,
1559 scroll_anchor: ScrollAnchor,
1560 scroll_top_row: u32,
1561}
1562
1563enum GotoDefinitionKind {
1564 Symbol,
1565 Type,
1566 Implementation,
1567}
1568
1569#[derive(Debug, Clone)]
1570enum InlayHintRefreshReason {
1571 Toggle(bool),
1572 SettingsChange(InlayHintSettings),
1573 NewLinesShown,
1574 BufferEdited(HashSet<Arc<Language>>),
1575 RefreshRequested,
1576 ExcerptsRemoved(Vec<ExcerptId>),
1577}
1578
1579impl InlayHintRefreshReason {
1580 fn description(&self) -> &'static str {
1581 match self {
1582 Self::Toggle(_) => "toggle",
1583 Self::SettingsChange(_) => "settings change",
1584 Self::NewLinesShown => "new lines shown",
1585 Self::BufferEdited(_) => "buffer edited",
1586 Self::RefreshRequested => "refresh requested",
1587 Self::ExcerptsRemoved(_) => "excerpts removed",
1588 }
1589 }
1590}
1591
1592pub(crate) struct FocusedBlock {
1593 id: BlockId,
1594 focus_handle: WeakFocusHandle,
1595}
1596
1597impl Editor {
1598 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1599 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1600 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1601 Self::new(
1602 EditorMode::SingleLine { auto_width: false },
1603 buffer,
1604 None,
1605 false,
1606 cx,
1607 )
1608 }
1609
1610 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1611 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1612 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1613 Self::new(EditorMode::Full, buffer, None, false, cx)
1614 }
1615
1616 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1617 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1618 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1619 Self::new(
1620 EditorMode::SingleLine { auto_width: true },
1621 buffer,
1622 None,
1623 false,
1624 cx,
1625 )
1626 }
1627
1628 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1629 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1630 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1631 Self::new(
1632 EditorMode::AutoHeight { max_lines },
1633 buffer,
1634 None,
1635 false,
1636 cx,
1637 )
1638 }
1639
1640 pub fn for_buffer(
1641 buffer: Model<Buffer>,
1642 project: Option<Model<Project>>,
1643 cx: &mut ViewContext<Self>,
1644 ) -> Self {
1645 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1646 Self::new(EditorMode::Full, buffer, project, false, cx)
1647 }
1648
1649 pub fn for_multibuffer(
1650 buffer: Model<MultiBuffer>,
1651 project: Option<Model<Project>>,
1652 show_excerpt_controls: bool,
1653 cx: &mut ViewContext<Self>,
1654 ) -> Self {
1655 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1656 }
1657
1658 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1659 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1660 let mut clone = Self::new(
1661 self.mode,
1662 self.buffer.clone(),
1663 self.project.clone(),
1664 show_excerpt_controls,
1665 cx,
1666 );
1667 self.display_map.update(cx, |display_map, cx| {
1668 let snapshot = display_map.snapshot(cx);
1669 clone.display_map.update(cx, |display_map, cx| {
1670 display_map.set_state(&snapshot, cx);
1671 });
1672 });
1673 clone.selections.clone_state(&self.selections);
1674 clone.scroll_manager.clone_state(&self.scroll_manager);
1675 clone.searchable = self.searchable;
1676 clone
1677 }
1678
1679 pub fn new(
1680 mode: EditorMode,
1681 buffer: Model<MultiBuffer>,
1682 project: Option<Model<Project>>,
1683 show_excerpt_controls: bool,
1684 cx: &mut ViewContext<Self>,
1685 ) -> Self {
1686 let style = cx.text_style();
1687 let font_size = style.font_size.to_pixels(cx.rem_size());
1688 let editor = cx.view().downgrade();
1689 let fold_placeholder = FoldPlaceholder {
1690 constrain_width: true,
1691 render: Arc::new(move |fold_id, fold_range, cx| {
1692 let editor = editor.clone();
1693 div()
1694 .id(fold_id)
1695 .bg(cx.theme().colors().ghost_element_background)
1696 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1697 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1698 .rounded_sm()
1699 .size_full()
1700 .cursor_pointer()
1701 .child("⋯")
1702 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1703 .on_click(move |_, cx| {
1704 editor
1705 .update(cx, |editor, cx| {
1706 editor.unfold_ranges(
1707 [fold_range.start..fold_range.end],
1708 true,
1709 false,
1710 cx,
1711 );
1712 cx.stop_propagation();
1713 })
1714 .ok();
1715 })
1716 .into_any()
1717 }),
1718 merge_adjacent: true,
1719 };
1720 let file_header_size = if show_excerpt_controls { 3 } else { 2 };
1721 let display_map = cx.new_model(|cx| {
1722 DisplayMap::new(
1723 buffer.clone(),
1724 style.font(),
1725 font_size,
1726 None,
1727 show_excerpt_controls,
1728 file_header_size,
1729 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1730 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1731 fold_placeholder,
1732 cx,
1733 )
1734 });
1735
1736 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1737
1738 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1739
1740 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1741 .then(|| language_settings::SoftWrap::PreferLine);
1742
1743 let mut project_subscriptions = Vec::new();
1744 if mode == EditorMode::Full {
1745 if let Some(project) = project.as_ref() {
1746 if buffer.read(cx).is_singleton() {
1747 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1748 cx.emit(EditorEvent::TitleChanged);
1749 }));
1750 }
1751 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1752 if let project::Event::RefreshInlayHints = event {
1753 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1754 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1755 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1756 let focus_handle = editor.focus_handle(cx);
1757 if focus_handle.is_focused(cx) {
1758 let snapshot = buffer.read(cx).snapshot();
1759 for (range, snippet) in snippet_edits {
1760 let editor_range =
1761 language::range_from_lsp(*range).to_offset(&snapshot);
1762 editor
1763 .insert_snippet(&[editor_range], snippet.clone(), cx)
1764 .ok();
1765 }
1766 }
1767 }
1768 }
1769 }));
1770 let task_inventory = project.read(cx).task_inventory().clone();
1771 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1772 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1773 }));
1774 }
1775 }
1776
1777 let inlay_hint_settings = inlay_hint_settings(
1778 selections.newest_anchor().head(),
1779 &buffer.read(cx).snapshot(cx),
1780 cx,
1781 );
1782 let focus_handle = cx.focus_handle();
1783 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1784 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1785 .detach();
1786 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1787 .detach();
1788 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1789
1790 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1791 Some(false)
1792 } else {
1793 None
1794 };
1795
1796 let mut this = Self {
1797 focus_handle,
1798 show_cursor_when_unfocused: false,
1799 last_focused_descendant: None,
1800 buffer: buffer.clone(),
1801 display_map: display_map.clone(),
1802 selections,
1803 scroll_manager: ScrollManager::new(cx),
1804 columnar_selection_tail: None,
1805 add_selections_state: None,
1806 select_next_state: None,
1807 select_prev_state: None,
1808 selection_history: Default::default(),
1809 autoclose_regions: Default::default(),
1810 snippet_stack: Default::default(),
1811 select_larger_syntax_node_stack: Vec::new(),
1812 ime_transaction: Default::default(),
1813 active_diagnostics: None,
1814 soft_wrap_mode_override,
1815 completion_provider: project.clone().map(|project| Box::new(project) as _),
1816 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1817 project,
1818 blink_manager: blink_manager.clone(),
1819 show_local_selections: true,
1820 mode,
1821 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1822 show_gutter: mode == EditorMode::Full,
1823 show_line_numbers: None,
1824 show_git_diff_gutter: None,
1825 show_code_actions: None,
1826 show_runnables: None,
1827 show_wrap_guides: None,
1828 redact_all: false,
1829 show_indent_guides,
1830 placeholder_text: None,
1831 highlight_order: 0,
1832 highlighted_rows: HashMap::default(),
1833 background_highlights: Default::default(),
1834 gutter_highlights: TreeMap::default(),
1835 scrollbar_marker_state: ScrollbarMarkerState::default(),
1836 active_indent_guides_state: ActiveIndentGuidesState::default(),
1837 nav_history: None,
1838 context_menu: RwLock::new(None),
1839 mouse_context_menu: None,
1840 completion_tasks: Default::default(),
1841 signature_help_state: SignatureHelpState::default(),
1842 auto_signature_help: None,
1843 find_all_references_task_sources: Vec::new(),
1844 next_completion_id: 0,
1845 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1846 next_inlay_id: 0,
1847 available_code_actions: Default::default(),
1848 code_actions_task: Default::default(),
1849 document_highlights_task: Default::default(),
1850 linked_editing_range_task: Default::default(),
1851 pending_rename: Default::default(),
1852 searchable: true,
1853 cursor_shape: Default::default(),
1854 current_line_highlight: None,
1855 autoindent_mode: Some(AutoindentMode::EachLine),
1856 collapse_matches: false,
1857 workspace: None,
1858 keymap_context_layers: Default::default(),
1859 input_enabled: true,
1860 use_modal_editing: mode == EditorMode::Full,
1861 read_only: false,
1862 use_autoclose: true,
1863 use_auto_surround: true,
1864 auto_replace_emoji_shortcode: false,
1865 leader_peer_id: None,
1866 remote_id: None,
1867 hover_state: Default::default(),
1868 hovered_link_state: Default::default(),
1869 inline_completion_provider: None,
1870 active_inline_completion: None,
1871 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1872 expanded_hunks: ExpandedHunks::default(),
1873 gutter_hovered: false,
1874 pixel_position_of_newest_cursor: None,
1875 last_bounds: None,
1876 expect_bounds_change: None,
1877 gutter_dimensions: GutterDimensions::default(),
1878 style: None,
1879 show_cursor_names: false,
1880 hovered_cursors: Default::default(),
1881 next_editor_action_id: EditorActionId::default(),
1882 editor_actions: Rc::default(),
1883 vim_replace_map: Default::default(),
1884 show_inline_completions: mode == EditorMode::Full,
1885 custom_context_menu: None,
1886 show_git_blame_gutter: false,
1887 show_git_blame_inline: false,
1888 show_selection_menu: None,
1889 show_git_blame_inline_delay_task: None,
1890 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1891 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1892 .session
1893 .restore_unsaved_buffers,
1894 blame: None,
1895 blame_subscription: None,
1896 file_header_size,
1897 tasks: Default::default(),
1898 _subscriptions: vec![
1899 cx.observe(&buffer, Self::on_buffer_changed),
1900 cx.subscribe(&buffer, Self::on_buffer_event),
1901 cx.observe(&display_map, Self::on_display_map_changed),
1902 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1903 cx.observe_global::<SettingsStore>(Self::settings_changed),
1904 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1905 cx.observe_window_activation(|editor, cx| {
1906 let active = cx.is_window_active();
1907 editor.blink_manager.update(cx, |blink_manager, cx| {
1908 if active {
1909 blink_manager.enable(cx);
1910 } else {
1911 blink_manager.show_cursor(cx);
1912 blink_manager.disable(cx);
1913 }
1914 });
1915 }),
1916 ],
1917 tasks_update_task: None,
1918 linked_edit_ranges: Default::default(),
1919 previous_search_ranges: None,
1920 breadcrumb_header: None,
1921 focused_block: None,
1922 };
1923 this.tasks_update_task = Some(this.refresh_runnables(cx));
1924 this._subscriptions.extend(project_subscriptions);
1925
1926 this.end_selection(cx);
1927 this.scroll_manager.show_scrollbar(cx);
1928
1929 if mode == EditorMode::Full {
1930 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1931 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1932
1933 if this.git_blame_inline_enabled {
1934 this.git_blame_inline_enabled = true;
1935 this.start_git_blame_inline(false, cx);
1936 }
1937 }
1938
1939 this.report_editor_event("open", None, cx);
1940 this
1941 }
1942
1943 pub fn mouse_menu_is_focused(&self, cx: &mut WindowContext) -> bool {
1944 self.mouse_context_menu
1945 .as_ref()
1946 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1947 }
1948
1949 fn key_context(&self, cx: &AppContext) -> KeyContext {
1950 let mut key_context = KeyContext::new_with_defaults();
1951 key_context.add("Editor");
1952 let mode = match self.mode {
1953 EditorMode::SingleLine { .. } => "single_line",
1954 EditorMode::AutoHeight { .. } => "auto_height",
1955 EditorMode::Full => "full",
1956 };
1957
1958 if EditorSettings::jupyter_enabled(cx) {
1959 key_context.add("jupyter");
1960 }
1961
1962 key_context.set("mode", mode);
1963 if self.pending_rename.is_some() {
1964 key_context.add("renaming");
1965 }
1966 if self.context_menu_visible() {
1967 match self.context_menu.read().as_ref() {
1968 Some(ContextMenu::Completions(_)) => {
1969 key_context.add("menu");
1970 key_context.add("showing_completions")
1971 }
1972 Some(ContextMenu::CodeActions(_)) => {
1973 key_context.add("menu");
1974 key_context.add("showing_code_actions")
1975 }
1976 None => {}
1977 }
1978 }
1979
1980 for layer in self.keymap_context_layers.values() {
1981 key_context.extend(layer);
1982 }
1983
1984 if let Some(extension) = self
1985 .buffer
1986 .read(cx)
1987 .as_singleton()
1988 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1989 {
1990 key_context.set("extension", extension.to_string());
1991 }
1992
1993 if self.has_active_inline_completion(cx) {
1994 key_context.add("copilot_suggestion");
1995 key_context.add("inline_completion");
1996 }
1997
1998 key_context
1999 }
2000
2001 pub fn new_file(
2002 workspace: &mut Workspace,
2003 _: &workspace::NewFile,
2004 cx: &mut ViewContext<Workspace>,
2005 ) {
2006 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2007 "Failed to create buffer",
2008 cx,
2009 |e, _| match e.error_code() {
2010 ErrorCode::RemoteUpgradeRequired => Some(format!(
2011 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2012 e.error_tag("required").unwrap_or("the latest version")
2013 )),
2014 _ => None,
2015 },
2016 );
2017 }
2018
2019 pub fn new_in_workspace(
2020 workspace: &mut Workspace,
2021 cx: &mut ViewContext<Workspace>,
2022 ) -> Task<Result<View<Editor>>> {
2023 let project = workspace.project().clone();
2024 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2025
2026 cx.spawn(|workspace, mut cx| async move {
2027 let buffer = create.await?;
2028 workspace.update(&mut cx, |workspace, cx| {
2029 let editor =
2030 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2031 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2032 editor
2033 })
2034 })
2035 }
2036
2037 pub fn new_file_in_direction(
2038 workspace: &mut Workspace,
2039 action: &workspace::NewFileInDirection,
2040 cx: &mut ViewContext<Workspace>,
2041 ) {
2042 let project = workspace.project().clone();
2043 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2044 let direction = action.0;
2045
2046 cx.spawn(|workspace, mut cx| async move {
2047 let buffer = create.await?;
2048 workspace.update(&mut cx, move |workspace, cx| {
2049 workspace.split_item(
2050 direction,
2051 Box::new(
2052 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2053 ),
2054 cx,
2055 )
2056 })?;
2057 anyhow::Ok(())
2058 })
2059 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2060 ErrorCode::RemoteUpgradeRequired => Some(format!(
2061 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2062 e.error_tag("required").unwrap_or("the latest version")
2063 )),
2064 _ => None,
2065 });
2066 }
2067
2068 pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
2069 self.buffer.read(cx).replica_id()
2070 }
2071
2072 pub fn leader_peer_id(&self) -> Option<PeerId> {
2073 self.leader_peer_id
2074 }
2075
2076 pub fn buffer(&self) -> &Model<MultiBuffer> {
2077 &self.buffer
2078 }
2079
2080 pub fn workspace(&self) -> Option<View<Workspace>> {
2081 self.workspace.as_ref()?.0.upgrade()
2082 }
2083
2084 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2085 self.buffer().read(cx).title(cx)
2086 }
2087
2088 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2089 EditorSnapshot {
2090 mode: self.mode,
2091 show_gutter: self.show_gutter,
2092 show_line_numbers: self.show_line_numbers,
2093 show_git_diff_gutter: self.show_git_diff_gutter,
2094 show_code_actions: self.show_code_actions,
2095 show_runnables: self.show_runnables,
2096 render_git_blame_gutter: self.render_git_blame_gutter(cx),
2097 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2098 scroll_anchor: self.scroll_manager.anchor(),
2099 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2100 placeholder_text: self.placeholder_text.clone(),
2101 is_focused: self.focus_handle.is_focused(cx),
2102 current_line_highlight: self
2103 .current_line_highlight
2104 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2105 gutter_hovered: self.gutter_hovered,
2106 }
2107 }
2108
2109 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2110 self.buffer.read(cx).language_at(point, cx)
2111 }
2112
2113 pub fn file_at<T: ToOffset>(
2114 &self,
2115 point: T,
2116 cx: &AppContext,
2117 ) -> Option<Arc<dyn language::File>> {
2118 self.buffer.read(cx).read(cx).file_at(point).cloned()
2119 }
2120
2121 pub fn active_excerpt(
2122 &self,
2123 cx: &AppContext,
2124 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2125 self.buffer
2126 .read(cx)
2127 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2128 }
2129
2130 pub fn mode(&self) -> EditorMode {
2131 self.mode
2132 }
2133
2134 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2135 self.collaboration_hub.as_deref()
2136 }
2137
2138 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2139 self.collaboration_hub = Some(hub);
2140 }
2141
2142 pub fn set_custom_context_menu(
2143 &mut self,
2144 f: impl 'static
2145 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2146 ) {
2147 self.custom_context_menu = Some(Box::new(f))
2148 }
2149
2150 pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
2151 self.completion_provider = Some(provider);
2152 }
2153
2154 pub fn set_inline_completion_provider<T>(
2155 &mut self,
2156 provider: Option<Model<T>>,
2157 cx: &mut ViewContext<Self>,
2158 ) where
2159 T: InlineCompletionProvider,
2160 {
2161 self.inline_completion_provider =
2162 provider.map(|provider| RegisteredInlineCompletionProvider {
2163 _subscription: cx.observe(&provider, |this, _, cx| {
2164 if this.focus_handle.is_focused(cx) {
2165 this.update_visible_inline_completion(cx);
2166 }
2167 }),
2168 provider: Arc::new(provider),
2169 });
2170 self.refresh_inline_completion(false, cx);
2171 }
2172
2173 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2174 self.placeholder_text.as_deref()
2175 }
2176
2177 pub fn set_placeholder_text(
2178 &mut self,
2179 placeholder_text: impl Into<Arc<str>>,
2180 cx: &mut ViewContext<Self>,
2181 ) {
2182 let placeholder_text = Some(placeholder_text.into());
2183 if self.placeholder_text != placeholder_text {
2184 self.placeholder_text = placeholder_text;
2185 cx.notify();
2186 }
2187 }
2188
2189 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2190 self.cursor_shape = cursor_shape;
2191
2192 // Disrupt blink for immediate user feedback that the cursor shape has changed
2193 self.blink_manager.update(cx, BlinkManager::show_cursor);
2194
2195 cx.notify();
2196 }
2197
2198 pub fn set_current_line_highlight(
2199 &mut self,
2200 current_line_highlight: Option<CurrentLineHighlight>,
2201 ) {
2202 self.current_line_highlight = current_line_highlight;
2203 }
2204
2205 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2206 self.collapse_matches = collapse_matches;
2207 }
2208
2209 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2210 if self.collapse_matches {
2211 return range.start..range.start;
2212 }
2213 range.clone()
2214 }
2215
2216 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2217 if self.display_map.read(cx).clip_at_line_ends != clip {
2218 self.display_map
2219 .update(cx, |map, _| map.clip_at_line_ends = clip);
2220 }
2221 }
2222
2223 pub fn set_keymap_context_layer<Tag: 'static>(
2224 &mut self,
2225 context: KeyContext,
2226 cx: &mut ViewContext<Self>,
2227 ) {
2228 self.keymap_context_layers
2229 .insert(TypeId::of::<Tag>(), context);
2230 cx.notify();
2231 }
2232
2233 pub fn remove_keymap_context_layer<Tag: 'static>(&mut self, cx: &mut ViewContext<Self>) {
2234 self.keymap_context_layers.remove(&TypeId::of::<Tag>());
2235 cx.notify();
2236 }
2237
2238 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2239 self.input_enabled = input_enabled;
2240 }
2241
2242 pub fn set_autoindent(&mut self, autoindent: bool) {
2243 if autoindent {
2244 self.autoindent_mode = Some(AutoindentMode::EachLine);
2245 } else {
2246 self.autoindent_mode = None;
2247 }
2248 }
2249
2250 pub fn read_only(&self, cx: &AppContext) -> bool {
2251 self.read_only || self.buffer.read(cx).read_only()
2252 }
2253
2254 pub fn set_read_only(&mut self, read_only: bool) {
2255 self.read_only = read_only;
2256 }
2257
2258 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2259 self.use_autoclose = autoclose;
2260 }
2261
2262 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2263 self.use_auto_surround = auto_surround;
2264 }
2265
2266 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2267 self.auto_replace_emoji_shortcode = auto_replace;
2268 }
2269
2270 pub fn set_show_inline_completions(&mut self, show_inline_completions: bool) {
2271 self.show_inline_completions = show_inline_completions;
2272 }
2273
2274 pub fn set_use_modal_editing(&mut self, to: bool) {
2275 self.use_modal_editing = to;
2276 }
2277
2278 pub fn use_modal_editing(&self) -> bool {
2279 self.use_modal_editing
2280 }
2281
2282 fn selections_did_change(
2283 &mut self,
2284 local: bool,
2285 old_cursor_position: &Anchor,
2286 show_completions: bool,
2287 cx: &mut ViewContext<Self>,
2288 ) {
2289 // Copy selections to primary selection buffer
2290 #[cfg(target_os = "linux")]
2291 if local {
2292 let selections = self.selections.all::<usize>(cx);
2293 let buffer_handle = self.buffer.read(cx).read(cx);
2294
2295 let mut text = String::new();
2296 for (index, selection) in selections.iter().enumerate() {
2297 let text_for_selection = buffer_handle
2298 .text_for_range(selection.start..selection.end)
2299 .collect::<String>();
2300
2301 text.push_str(&text_for_selection);
2302 if index != selections.len() - 1 {
2303 text.push('\n');
2304 }
2305 }
2306
2307 if !text.is_empty() {
2308 cx.write_to_primary(ClipboardItem::new(text));
2309 }
2310 }
2311
2312 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2313 self.buffer.update(cx, |buffer, cx| {
2314 buffer.set_active_selections(
2315 &self.selections.disjoint_anchors(),
2316 self.selections.line_mode,
2317 self.cursor_shape,
2318 cx,
2319 )
2320 });
2321 }
2322 let display_map = self
2323 .display_map
2324 .update(cx, |display_map, cx| display_map.snapshot(cx));
2325 let buffer = &display_map.buffer_snapshot;
2326 self.add_selections_state = None;
2327 self.select_next_state = None;
2328 self.select_prev_state = None;
2329 self.select_larger_syntax_node_stack.clear();
2330 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2331 self.snippet_stack
2332 .invalidate(&self.selections.disjoint_anchors(), buffer);
2333 self.take_rename(false, cx);
2334
2335 let new_cursor_position = self.selections.newest_anchor().head();
2336
2337 self.push_to_nav_history(
2338 *old_cursor_position,
2339 Some(new_cursor_position.to_point(buffer)),
2340 cx,
2341 );
2342
2343 if local {
2344 let new_cursor_position = self.selections.newest_anchor().head();
2345 let mut context_menu = self.context_menu.write();
2346 let completion_menu = match context_menu.as_ref() {
2347 Some(ContextMenu::Completions(menu)) => Some(menu),
2348
2349 _ => {
2350 *context_menu = None;
2351 None
2352 }
2353 };
2354
2355 if let Some(completion_menu) = completion_menu {
2356 let cursor_position = new_cursor_position.to_offset(buffer);
2357 let (word_range, kind) = buffer.surrounding_word(completion_menu.initial_position);
2358 if kind == Some(CharKind::Word)
2359 && word_range.to_inclusive().contains(&cursor_position)
2360 {
2361 let mut completion_menu = completion_menu.clone();
2362 drop(context_menu);
2363
2364 let query = Self::completion_query(buffer, cursor_position);
2365 cx.spawn(move |this, mut cx| async move {
2366 completion_menu
2367 .filter(query.as_deref(), cx.background_executor().clone())
2368 .await;
2369
2370 this.update(&mut cx, |this, cx| {
2371 let mut context_menu = this.context_menu.write();
2372 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2373 return;
2374 };
2375
2376 if menu.id > completion_menu.id {
2377 return;
2378 }
2379
2380 *context_menu = Some(ContextMenu::Completions(completion_menu));
2381 drop(context_menu);
2382 cx.notify();
2383 })
2384 })
2385 .detach();
2386
2387 if show_completions {
2388 self.show_completions(&ShowCompletions { trigger: None }, cx);
2389 }
2390 } else {
2391 drop(context_menu);
2392 self.hide_context_menu(cx);
2393 }
2394 } else {
2395 drop(context_menu);
2396 }
2397
2398 hide_hover(self, cx);
2399
2400 if old_cursor_position.to_display_point(&display_map).row()
2401 != new_cursor_position.to_display_point(&display_map).row()
2402 {
2403 self.available_code_actions.take();
2404 }
2405 self.refresh_code_actions(cx);
2406 self.refresh_document_highlights(cx);
2407 refresh_matching_bracket_highlights(self, cx);
2408 self.discard_inline_completion(false, cx);
2409 linked_editing_ranges::refresh_linked_ranges(self, cx);
2410 if self.git_blame_inline_enabled {
2411 self.start_inline_blame_timer(cx);
2412 }
2413 }
2414
2415 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2416 cx.emit(EditorEvent::SelectionsChanged { local });
2417
2418 if self.selections.disjoint_anchors().len() == 1 {
2419 cx.emit(SearchEvent::ActiveMatchChanged)
2420 }
2421 cx.notify();
2422 }
2423
2424 pub fn change_selections<R>(
2425 &mut self,
2426 autoscroll: Option<Autoscroll>,
2427 cx: &mut ViewContext<Self>,
2428 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2429 ) -> R {
2430 self.change_selections_inner(autoscroll, true, cx, change)
2431 }
2432
2433 pub fn change_selections_inner<R>(
2434 &mut self,
2435 autoscroll: Option<Autoscroll>,
2436 request_completions: bool,
2437 cx: &mut ViewContext<Self>,
2438 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2439 ) -> R {
2440 let old_cursor_position = self.selections.newest_anchor().head();
2441 self.push_to_selection_history();
2442
2443 let (changed, result) = self.selections.change_with(cx, change);
2444
2445 if changed {
2446 if let Some(autoscroll) = autoscroll {
2447 self.request_autoscroll(autoscroll, cx);
2448 }
2449 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2450
2451 if self.should_open_signature_help_automatically(
2452 &old_cursor_position,
2453 self.signature_help_state.backspace_pressed(),
2454 cx,
2455 ) {
2456 self.show_signature_help(&ShowSignatureHelp, cx);
2457 }
2458 self.signature_help_state.set_backspace_pressed(false);
2459 }
2460
2461 result
2462 }
2463
2464 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2465 where
2466 I: IntoIterator<Item = (Range<S>, T)>,
2467 S: ToOffset,
2468 T: Into<Arc<str>>,
2469 {
2470 if self.read_only(cx) {
2471 return;
2472 }
2473
2474 self.buffer
2475 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2476 }
2477
2478 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2479 where
2480 I: IntoIterator<Item = (Range<S>, T)>,
2481 S: ToOffset,
2482 T: Into<Arc<str>>,
2483 {
2484 if self.read_only(cx) {
2485 return;
2486 }
2487
2488 self.buffer.update(cx, |buffer, cx| {
2489 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2490 });
2491 }
2492
2493 pub fn edit_with_block_indent<I, S, T>(
2494 &mut self,
2495 edits: I,
2496 original_indent_columns: Vec<u32>,
2497 cx: &mut ViewContext<Self>,
2498 ) where
2499 I: IntoIterator<Item = (Range<S>, T)>,
2500 S: ToOffset,
2501 T: Into<Arc<str>>,
2502 {
2503 if self.read_only(cx) {
2504 return;
2505 }
2506
2507 self.buffer.update(cx, |buffer, cx| {
2508 buffer.edit(
2509 edits,
2510 Some(AutoindentMode::Block {
2511 original_indent_columns,
2512 }),
2513 cx,
2514 )
2515 });
2516 }
2517
2518 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2519 self.hide_context_menu(cx);
2520
2521 match phase {
2522 SelectPhase::Begin {
2523 position,
2524 add,
2525 click_count,
2526 } => self.begin_selection(position, add, click_count, cx),
2527 SelectPhase::BeginColumnar {
2528 position,
2529 goal_column,
2530 reset,
2531 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2532 SelectPhase::Extend {
2533 position,
2534 click_count,
2535 } => self.extend_selection(position, click_count, cx),
2536 SelectPhase::Update {
2537 position,
2538 goal_column,
2539 scroll_delta,
2540 } => self.update_selection(position, goal_column, scroll_delta, cx),
2541 SelectPhase::End => self.end_selection(cx),
2542 }
2543 }
2544
2545 fn extend_selection(
2546 &mut self,
2547 position: DisplayPoint,
2548 click_count: usize,
2549 cx: &mut ViewContext<Self>,
2550 ) {
2551 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2552 let tail = self.selections.newest::<usize>(cx).tail();
2553 self.begin_selection(position, false, click_count, cx);
2554
2555 let position = position.to_offset(&display_map, Bias::Left);
2556 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2557
2558 let mut pending_selection = self
2559 .selections
2560 .pending_anchor()
2561 .expect("extend_selection not called with pending selection");
2562 if position >= tail {
2563 pending_selection.start = tail_anchor;
2564 } else {
2565 pending_selection.end = tail_anchor;
2566 pending_selection.reversed = true;
2567 }
2568
2569 let mut pending_mode = self.selections.pending_mode().unwrap();
2570 match &mut pending_mode {
2571 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2572 _ => {}
2573 }
2574
2575 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2576 s.set_pending(pending_selection, pending_mode)
2577 });
2578 }
2579
2580 fn begin_selection(
2581 &mut self,
2582 position: DisplayPoint,
2583 add: bool,
2584 click_count: usize,
2585 cx: &mut ViewContext<Self>,
2586 ) {
2587 if !self.focus_handle.is_focused(cx) {
2588 self.last_focused_descendant = None;
2589 cx.focus(&self.focus_handle);
2590 }
2591
2592 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2593 let buffer = &display_map.buffer_snapshot;
2594 let newest_selection = self.selections.newest_anchor().clone();
2595 let position = display_map.clip_point(position, Bias::Left);
2596
2597 let start;
2598 let end;
2599 let mode;
2600 let auto_scroll;
2601 match click_count {
2602 1 => {
2603 start = buffer.anchor_before(position.to_point(&display_map));
2604 end = start;
2605 mode = SelectMode::Character;
2606 auto_scroll = true;
2607 }
2608 2 => {
2609 let range = movement::surrounding_word(&display_map, position);
2610 start = buffer.anchor_before(range.start.to_point(&display_map));
2611 end = buffer.anchor_before(range.end.to_point(&display_map));
2612 mode = SelectMode::Word(start..end);
2613 auto_scroll = true;
2614 }
2615 3 => {
2616 let position = display_map
2617 .clip_point(position, Bias::Left)
2618 .to_point(&display_map);
2619 let line_start = display_map.prev_line_boundary(position).0;
2620 let next_line_start = buffer.clip_point(
2621 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2622 Bias::Left,
2623 );
2624 start = buffer.anchor_before(line_start);
2625 end = buffer.anchor_before(next_line_start);
2626 mode = SelectMode::Line(start..end);
2627 auto_scroll = true;
2628 }
2629 _ => {
2630 start = buffer.anchor_before(0);
2631 end = buffer.anchor_before(buffer.len());
2632 mode = SelectMode::All;
2633 auto_scroll = false;
2634 }
2635 }
2636
2637 let point_to_delete: Option<usize> = {
2638 let selected_points: Vec<Selection<Point>> =
2639 self.selections.disjoint_in_range(start..end, cx);
2640
2641 if !add || click_count > 1 {
2642 None
2643 } else if selected_points.len() > 0 {
2644 Some(selected_points[0].id)
2645 } else {
2646 let clicked_point_already_selected =
2647 self.selections.disjoint.iter().find(|selection| {
2648 selection.start.to_point(buffer) == start.to_point(buffer)
2649 || selection.end.to_point(buffer) == end.to_point(buffer)
2650 });
2651
2652 if let Some(selection) = clicked_point_already_selected {
2653 Some(selection.id)
2654 } else {
2655 None
2656 }
2657 }
2658 };
2659
2660 let selections_count = self.selections.count();
2661
2662 self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
2663 if let Some(point_to_delete) = point_to_delete {
2664 s.delete(point_to_delete);
2665
2666 if selections_count == 1 {
2667 s.set_pending_anchor_range(start..end, mode);
2668 }
2669 } else {
2670 if !add {
2671 s.clear_disjoint();
2672 } else if click_count > 1 {
2673 s.delete(newest_selection.id)
2674 }
2675
2676 s.set_pending_anchor_range(start..end, mode);
2677 }
2678 });
2679 }
2680
2681 fn begin_columnar_selection(
2682 &mut self,
2683 position: DisplayPoint,
2684 goal_column: u32,
2685 reset: bool,
2686 cx: &mut ViewContext<Self>,
2687 ) {
2688 if !self.focus_handle.is_focused(cx) {
2689 self.last_focused_descendant = None;
2690 cx.focus(&self.focus_handle);
2691 }
2692
2693 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2694
2695 if reset {
2696 let pointer_position = display_map
2697 .buffer_snapshot
2698 .anchor_before(position.to_point(&display_map));
2699
2700 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2701 s.clear_disjoint();
2702 s.set_pending_anchor_range(
2703 pointer_position..pointer_position,
2704 SelectMode::Character,
2705 );
2706 });
2707 }
2708
2709 let tail = self.selections.newest::<Point>(cx).tail();
2710 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2711
2712 if !reset {
2713 self.select_columns(
2714 tail.to_display_point(&display_map),
2715 position,
2716 goal_column,
2717 &display_map,
2718 cx,
2719 );
2720 }
2721 }
2722
2723 fn update_selection(
2724 &mut self,
2725 position: DisplayPoint,
2726 goal_column: u32,
2727 scroll_delta: gpui::Point<f32>,
2728 cx: &mut ViewContext<Self>,
2729 ) {
2730 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2731
2732 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2733 let tail = tail.to_display_point(&display_map);
2734 self.select_columns(tail, position, goal_column, &display_map, cx);
2735 } else if let Some(mut pending) = self.selections.pending_anchor() {
2736 let buffer = self.buffer.read(cx).snapshot(cx);
2737 let head;
2738 let tail;
2739 let mode = self.selections.pending_mode().unwrap();
2740 match &mode {
2741 SelectMode::Character => {
2742 head = position.to_point(&display_map);
2743 tail = pending.tail().to_point(&buffer);
2744 }
2745 SelectMode::Word(original_range) => {
2746 let original_display_range = original_range.start.to_display_point(&display_map)
2747 ..original_range.end.to_display_point(&display_map);
2748 let original_buffer_range = original_display_range.start.to_point(&display_map)
2749 ..original_display_range.end.to_point(&display_map);
2750 if movement::is_inside_word(&display_map, position)
2751 || original_display_range.contains(&position)
2752 {
2753 let word_range = movement::surrounding_word(&display_map, position);
2754 if word_range.start < original_display_range.start {
2755 head = word_range.start.to_point(&display_map);
2756 } else {
2757 head = word_range.end.to_point(&display_map);
2758 }
2759 } else {
2760 head = position.to_point(&display_map);
2761 }
2762
2763 if head <= original_buffer_range.start {
2764 tail = original_buffer_range.end;
2765 } else {
2766 tail = original_buffer_range.start;
2767 }
2768 }
2769 SelectMode::Line(original_range) => {
2770 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2771
2772 let position = display_map
2773 .clip_point(position, Bias::Left)
2774 .to_point(&display_map);
2775 let line_start = display_map.prev_line_boundary(position).0;
2776 let next_line_start = buffer.clip_point(
2777 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2778 Bias::Left,
2779 );
2780
2781 if line_start < original_range.start {
2782 head = line_start
2783 } else {
2784 head = next_line_start
2785 }
2786
2787 if head <= original_range.start {
2788 tail = original_range.end;
2789 } else {
2790 tail = original_range.start;
2791 }
2792 }
2793 SelectMode::All => {
2794 return;
2795 }
2796 };
2797
2798 if head < tail {
2799 pending.start = buffer.anchor_before(head);
2800 pending.end = buffer.anchor_before(tail);
2801 pending.reversed = true;
2802 } else {
2803 pending.start = buffer.anchor_before(tail);
2804 pending.end = buffer.anchor_before(head);
2805 pending.reversed = false;
2806 }
2807
2808 self.change_selections(None, cx, |s| {
2809 s.set_pending(pending, mode);
2810 });
2811 } else {
2812 log::error!("update_selection dispatched with no pending selection");
2813 return;
2814 }
2815
2816 self.apply_scroll_delta(scroll_delta, cx);
2817 cx.notify();
2818 }
2819
2820 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2821 self.columnar_selection_tail.take();
2822 if self.selections.pending_anchor().is_some() {
2823 let selections = self.selections.all::<usize>(cx);
2824 self.change_selections(None, cx, |s| {
2825 s.select(selections);
2826 s.clear_pending();
2827 });
2828 }
2829 }
2830
2831 fn select_columns(
2832 &mut self,
2833 tail: DisplayPoint,
2834 head: DisplayPoint,
2835 goal_column: u32,
2836 display_map: &DisplaySnapshot,
2837 cx: &mut ViewContext<Self>,
2838 ) {
2839 let start_row = cmp::min(tail.row(), head.row());
2840 let end_row = cmp::max(tail.row(), head.row());
2841 let start_column = cmp::min(tail.column(), goal_column);
2842 let end_column = cmp::max(tail.column(), goal_column);
2843 let reversed = start_column < tail.column();
2844
2845 let selection_ranges = (start_row.0..=end_row.0)
2846 .map(DisplayRow)
2847 .filter_map(|row| {
2848 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2849 let start = display_map
2850 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2851 .to_point(display_map);
2852 let end = display_map
2853 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2854 .to_point(display_map);
2855 if reversed {
2856 Some(end..start)
2857 } else {
2858 Some(start..end)
2859 }
2860 } else {
2861 None
2862 }
2863 })
2864 .collect::<Vec<_>>();
2865
2866 self.change_selections(None, cx, |s| {
2867 s.select_ranges(selection_ranges);
2868 });
2869 cx.notify();
2870 }
2871
2872 pub fn has_pending_nonempty_selection(&self) -> bool {
2873 let pending_nonempty_selection = match self.selections.pending_anchor() {
2874 Some(Selection { start, end, .. }) => start != end,
2875 None => false,
2876 };
2877
2878 pending_nonempty_selection
2879 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2880 }
2881
2882 pub fn has_pending_selection(&self) -> bool {
2883 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2884 }
2885
2886 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2887 if self.clear_clicked_diff_hunks(cx) {
2888 cx.notify();
2889 return;
2890 }
2891 if self.dismiss_menus_and_popups(true, cx) {
2892 return;
2893 }
2894
2895 if self.mode == EditorMode::Full {
2896 if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
2897 return;
2898 }
2899 }
2900
2901 cx.propagate();
2902 }
2903
2904 pub fn dismiss_menus_and_popups(
2905 &mut self,
2906 should_report_inline_completion_event: bool,
2907 cx: &mut ViewContext<Self>,
2908 ) -> bool {
2909 if self.take_rename(false, cx).is_some() {
2910 return true;
2911 }
2912
2913 if hide_hover(self, cx) {
2914 return true;
2915 }
2916
2917 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2918 return true;
2919 }
2920
2921 if self.hide_context_menu(cx).is_some() {
2922 return true;
2923 }
2924
2925 if self.mouse_context_menu.take().is_some() {
2926 return true;
2927 }
2928
2929 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2930 return true;
2931 }
2932
2933 if self.snippet_stack.pop().is_some() {
2934 return true;
2935 }
2936
2937 if self.mode == EditorMode::Full {
2938 if self.active_diagnostics.is_some() {
2939 self.dismiss_diagnostics(cx);
2940 return true;
2941 }
2942 }
2943
2944 false
2945 }
2946
2947 fn linked_editing_ranges_for(
2948 &self,
2949 selection: Range<text::Anchor>,
2950 cx: &AppContext,
2951 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2952 if self.linked_edit_ranges.is_empty() {
2953 return None;
2954 }
2955 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2956 selection.end.buffer_id.and_then(|end_buffer_id| {
2957 if selection.start.buffer_id != Some(end_buffer_id) {
2958 return None;
2959 }
2960 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2961 let snapshot = buffer.read(cx).snapshot();
2962 self.linked_edit_ranges
2963 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2964 .map(|ranges| (ranges, snapshot, buffer))
2965 })?;
2966 use text::ToOffset as TO;
2967 // find offset from the start of current range to current cursor position
2968 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2969
2970 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2971 let start_difference = start_offset - start_byte_offset;
2972 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2973 let end_difference = end_offset - start_byte_offset;
2974 // Current range has associated linked ranges.
2975 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2976 for range in linked_ranges.iter() {
2977 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2978 let end_offset = start_offset + end_difference;
2979 let start_offset = start_offset + start_difference;
2980 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2981 continue;
2982 }
2983 let start = buffer_snapshot.anchor_after(start_offset);
2984 let end = buffer_snapshot.anchor_after(end_offset);
2985 linked_edits
2986 .entry(buffer.clone())
2987 .or_default()
2988 .push(start..end);
2989 }
2990 Some(linked_edits)
2991 }
2992
2993 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2994 let text: Arc<str> = text.into();
2995
2996 if self.read_only(cx) {
2997 return;
2998 }
2999
3000 let selections = self.selections.all_adjusted(cx);
3001 let mut bracket_inserted = false;
3002 let mut edits = Vec::new();
3003 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3004 let mut new_selections = Vec::with_capacity(selections.len());
3005 let mut new_autoclose_regions = Vec::new();
3006 let snapshot = self.buffer.read(cx).read(cx);
3007
3008 for (selection, autoclose_region) in
3009 self.selections_with_autoclose_regions(selections, &snapshot)
3010 {
3011 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3012 // Determine if the inserted text matches the opening or closing
3013 // bracket of any of this language's bracket pairs.
3014 let mut bracket_pair = None;
3015 let mut is_bracket_pair_start = false;
3016 let mut is_bracket_pair_end = false;
3017 if !text.is_empty() {
3018 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3019 // and they are removing the character that triggered IME popup.
3020 for (pair, enabled) in scope.brackets() {
3021 if !pair.close && !pair.surround {
3022 continue;
3023 }
3024
3025 if enabled && pair.start.ends_with(text.as_ref()) {
3026 bracket_pair = Some(pair.clone());
3027 is_bracket_pair_start = true;
3028 break;
3029 }
3030 if pair.end.as_str() == text.as_ref() {
3031 bracket_pair = Some(pair.clone());
3032 is_bracket_pair_end = true;
3033 break;
3034 }
3035 }
3036 }
3037
3038 if let Some(bracket_pair) = bracket_pair {
3039 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3040 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3041 let auto_surround =
3042 self.use_auto_surround && snapshot_settings.use_auto_surround;
3043 if selection.is_empty() {
3044 if is_bracket_pair_start {
3045 let prefix_len = bracket_pair.start.len() - text.len();
3046
3047 // If the inserted text is a suffix of an opening bracket and the
3048 // selection is preceded by the rest of the opening bracket, then
3049 // insert the closing bracket.
3050 let following_text_allows_autoclose = snapshot
3051 .chars_at(selection.start)
3052 .next()
3053 .map_or(true, |c| scope.should_autoclose_before(c));
3054 let preceding_text_matches_prefix = prefix_len == 0
3055 || (selection.start.column >= (prefix_len as u32)
3056 && snapshot.contains_str_at(
3057 Point::new(
3058 selection.start.row,
3059 selection.start.column - (prefix_len as u32),
3060 ),
3061 &bracket_pair.start[..prefix_len],
3062 ));
3063
3064 if autoclose
3065 && bracket_pair.close
3066 && following_text_allows_autoclose
3067 && preceding_text_matches_prefix
3068 {
3069 let anchor = snapshot.anchor_before(selection.end);
3070 new_selections.push((selection.map(|_| anchor), text.len()));
3071 new_autoclose_regions.push((
3072 anchor,
3073 text.len(),
3074 selection.id,
3075 bracket_pair.clone(),
3076 ));
3077 edits.push((
3078 selection.range(),
3079 format!("{}{}", text, bracket_pair.end).into(),
3080 ));
3081 bracket_inserted = true;
3082 continue;
3083 }
3084 }
3085
3086 if let Some(region) = autoclose_region {
3087 // If the selection is followed by an auto-inserted closing bracket,
3088 // then don't insert that closing bracket again; just move the selection
3089 // past the closing bracket.
3090 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3091 && text.as_ref() == region.pair.end.as_str();
3092 if should_skip {
3093 let anchor = snapshot.anchor_after(selection.end);
3094 new_selections
3095 .push((selection.map(|_| anchor), region.pair.end.len()));
3096 continue;
3097 }
3098 }
3099
3100 let always_treat_brackets_as_autoclosed = snapshot
3101 .settings_at(selection.start, cx)
3102 .always_treat_brackets_as_autoclosed;
3103 if always_treat_brackets_as_autoclosed
3104 && is_bracket_pair_end
3105 && snapshot.contains_str_at(selection.end, text.as_ref())
3106 {
3107 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3108 // and the inserted text is a closing bracket and the selection is followed
3109 // by the closing bracket then move the selection past the closing bracket.
3110 let anchor = snapshot.anchor_after(selection.end);
3111 new_selections.push((selection.map(|_| anchor), text.len()));
3112 continue;
3113 }
3114 }
3115 // If an opening bracket is 1 character long and is typed while
3116 // text is selected, then surround that text with the bracket pair.
3117 else if auto_surround
3118 && bracket_pair.surround
3119 && is_bracket_pair_start
3120 && bracket_pair.start.chars().count() == 1
3121 {
3122 edits.push((selection.start..selection.start, text.clone()));
3123 edits.push((
3124 selection.end..selection.end,
3125 bracket_pair.end.as_str().into(),
3126 ));
3127 bracket_inserted = true;
3128 new_selections.push((
3129 Selection {
3130 id: selection.id,
3131 start: snapshot.anchor_after(selection.start),
3132 end: snapshot.anchor_before(selection.end),
3133 reversed: selection.reversed,
3134 goal: selection.goal,
3135 },
3136 0,
3137 ));
3138 continue;
3139 }
3140 }
3141 }
3142
3143 if self.auto_replace_emoji_shortcode
3144 && selection.is_empty()
3145 && text.as_ref().ends_with(':')
3146 {
3147 if let Some(possible_emoji_short_code) =
3148 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3149 {
3150 if !possible_emoji_short_code.is_empty() {
3151 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3152 let emoji_shortcode_start = Point::new(
3153 selection.start.row,
3154 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3155 );
3156
3157 // Remove shortcode from buffer
3158 edits.push((
3159 emoji_shortcode_start..selection.start,
3160 "".to_string().into(),
3161 ));
3162 new_selections.push((
3163 Selection {
3164 id: selection.id,
3165 start: snapshot.anchor_after(emoji_shortcode_start),
3166 end: snapshot.anchor_before(selection.start),
3167 reversed: selection.reversed,
3168 goal: selection.goal,
3169 },
3170 0,
3171 ));
3172
3173 // Insert emoji
3174 let selection_start_anchor = snapshot.anchor_after(selection.start);
3175 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3176 edits.push((selection.start..selection.end, emoji.to_string().into()));
3177
3178 continue;
3179 }
3180 }
3181 }
3182 }
3183
3184 // If not handling any auto-close operation, then just replace the selected
3185 // text with the given input and move the selection to the end of the
3186 // newly inserted text.
3187 let anchor = snapshot.anchor_after(selection.end);
3188 if !self.linked_edit_ranges.is_empty() {
3189 let start_anchor = snapshot.anchor_before(selection.start);
3190
3191 let is_word_char = text.chars().next().map_or(true, |char| {
3192 let scope = snapshot.language_scope_at(start_anchor.to_offset(&snapshot));
3193 let kind = char_kind(&scope, char);
3194
3195 kind == CharKind::Word
3196 });
3197
3198 if is_word_char {
3199 if let Some(ranges) = self
3200 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3201 {
3202 for (buffer, edits) in ranges {
3203 linked_edits
3204 .entry(buffer.clone())
3205 .or_default()
3206 .extend(edits.into_iter().map(|range| (range, text.clone())));
3207 }
3208 }
3209 }
3210 }
3211
3212 new_selections.push((selection.map(|_| anchor), 0));
3213 edits.push((selection.start..selection.end, text.clone()));
3214 }
3215
3216 drop(snapshot);
3217
3218 self.transact(cx, |this, cx| {
3219 this.buffer.update(cx, |buffer, cx| {
3220 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3221 });
3222 for (buffer, edits) in linked_edits {
3223 buffer.update(cx, |buffer, cx| {
3224 let snapshot = buffer.snapshot();
3225 let edits = edits
3226 .into_iter()
3227 .map(|(range, text)| {
3228 use text::ToPoint as TP;
3229 let end_point = TP::to_point(&range.end, &snapshot);
3230 let start_point = TP::to_point(&range.start, &snapshot);
3231 (start_point..end_point, text)
3232 })
3233 .sorted_by_key(|(range, _)| range.start)
3234 .collect::<Vec<_>>();
3235 buffer.edit(edits, None, cx);
3236 })
3237 }
3238 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3239 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3240 let snapshot = this.buffer.read(cx).read(cx);
3241 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3242 .zip(new_selection_deltas)
3243 .map(|(selection, delta)| Selection {
3244 id: selection.id,
3245 start: selection.start + delta,
3246 end: selection.end + delta,
3247 reversed: selection.reversed,
3248 goal: SelectionGoal::None,
3249 })
3250 .collect::<Vec<_>>();
3251
3252 let mut i = 0;
3253 for (position, delta, selection_id, pair) in new_autoclose_regions {
3254 let position = position.to_offset(&snapshot) + delta;
3255 let start = snapshot.anchor_before(position);
3256 let end = snapshot.anchor_after(position);
3257 while let Some(existing_state) = this.autoclose_regions.get(i) {
3258 match existing_state.range.start.cmp(&start, &snapshot) {
3259 Ordering::Less => i += 1,
3260 Ordering::Greater => break,
3261 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3262 Ordering::Less => i += 1,
3263 Ordering::Equal => break,
3264 Ordering::Greater => break,
3265 },
3266 }
3267 }
3268 this.autoclose_regions.insert(
3269 i,
3270 AutocloseRegion {
3271 selection_id,
3272 range: start..end,
3273 pair,
3274 },
3275 );
3276 }
3277
3278 drop(snapshot);
3279 let had_active_inline_completion = this.has_active_inline_completion(cx);
3280 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3281 s.select(new_selections)
3282 });
3283
3284 if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
3285 if let Some(on_type_format_task) =
3286 this.trigger_on_type_formatting(text.to_string(), cx)
3287 {
3288 on_type_format_task.detach_and_log_err(cx);
3289 }
3290 }
3291
3292 let editor_settings = EditorSettings::get_global(cx);
3293 if bracket_inserted
3294 && (editor_settings.auto_signature_help
3295 || editor_settings.show_signature_help_after_edits)
3296 {
3297 this.show_signature_help(&ShowSignatureHelp, cx);
3298 }
3299
3300 let trigger_in_words = !had_active_inline_completion;
3301 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3302 linked_editing_ranges::refresh_linked_ranges(this, cx);
3303 this.refresh_inline_completion(true, cx);
3304 });
3305 }
3306
3307 fn find_possible_emoji_shortcode_at_position(
3308 snapshot: &MultiBufferSnapshot,
3309 position: Point,
3310 ) -> Option<String> {
3311 let mut chars = Vec::new();
3312 let mut found_colon = false;
3313 for char in snapshot.reversed_chars_at(position).take(100) {
3314 // Found a possible emoji shortcode in the middle of the buffer
3315 if found_colon {
3316 if char.is_whitespace() {
3317 chars.reverse();
3318 return Some(chars.iter().collect());
3319 }
3320 // If the previous character is not a whitespace, we are in the middle of a word
3321 // and we only want to complete the shortcode if the word is made up of other emojis
3322 let mut containing_word = String::new();
3323 for ch in snapshot
3324 .reversed_chars_at(position)
3325 .skip(chars.len() + 1)
3326 .take(100)
3327 {
3328 if ch.is_whitespace() {
3329 break;
3330 }
3331 containing_word.push(ch);
3332 }
3333 let containing_word = containing_word.chars().rev().collect::<String>();
3334 if util::word_consists_of_emojis(containing_word.as_str()) {
3335 chars.reverse();
3336 return Some(chars.iter().collect());
3337 }
3338 }
3339
3340 if char.is_whitespace() || !char.is_ascii() {
3341 return None;
3342 }
3343 if char == ':' {
3344 found_colon = true;
3345 } else {
3346 chars.push(char);
3347 }
3348 }
3349 // Found a possible emoji shortcode at the beginning of the buffer
3350 chars.reverse();
3351 Some(chars.iter().collect())
3352 }
3353
3354 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3355 self.transact(cx, |this, cx| {
3356 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3357 let selections = this.selections.all::<usize>(cx);
3358 let multi_buffer = this.buffer.read(cx);
3359 let buffer = multi_buffer.snapshot(cx);
3360 selections
3361 .iter()
3362 .map(|selection| {
3363 let start_point = selection.start.to_point(&buffer);
3364 let mut indent =
3365 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3366 indent.len = cmp::min(indent.len, start_point.column);
3367 let start = selection.start;
3368 let end = selection.end;
3369 let selection_is_empty = start == end;
3370 let language_scope = buffer.language_scope_at(start);
3371 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3372 &language_scope
3373 {
3374 let leading_whitespace_len = buffer
3375 .reversed_chars_at(start)
3376 .take_while(|c| c.is_whitespace() && *c != '\n')
3377 .map(|c| c.len_utf8())
3378 .sum::<usize>();
3379
3380 let trailing_whitespace_len = buffer
3381 .chars_at(end)
3382 .take_while(|c| c.is_whitespace() && *c != '\n')
3383 .map(|c| c.len_utf8())
3384 .sum::<usize>();
3385
3386 let insert_extra_newline =
3387 language.brackets().any(|(pair, enabled)| {
3388 let pair_start = pair.start.trim_end();
3389 let pair_end = pair.end.trim_start();
3390
3391 enabled
3392 && pair.newline
3393 && buffer.contains_str_at(
3394 end + trailing_whitespace_len,
3395 pair_end,
3396 )
3397 && buffer.contains_str_at(
3398 (start - leading_whitespace_len)
3399 .saturating_sub(pair_start.len()),
3400 pair_start,
3401 )
3402 });
3403
3404 // Comment extension on newline is allowed only for cursor selections
3405 let comment_delimiter = maybe!({
3406 if !selection_is_empty {
3407 return None;
3408 }
3409
3410 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3411 return None;
3412 }
3413
3414 let delimiters = language.line_comment_prefixes();
3415 let max_len_of_delimiter =
3416 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3417 let (snapshot, range) =
3418 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3419
3420 let mut index_of_first_non_whitespace = 0;
3421 let comment_candidate = snapshot
3422 .chars_for_range(range)
3423 .skip_while(|c| {
3424 let should_skip = c.is_whitespace();
3425 if should_skip {
3426 index_of_first_non_whitespace += 1;
3427 }
3428 should_skip
3429 })
3430 .take(max_len_of_delimiter)
3431 .collect::<String>();
3432 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3433 comment_candidate.starts_with(comment_prefix.as_ref())
3434 })?;
3435 let cursor_is_placed_after_comment_marker =
3436 index_of_first_non_whitespace + comment_prefix.len()
3437 <= start_point.column as usize;
3438 if cursor_is_placed_after_comment_marker {
3439 Some(comment_prefix.clone())
3440 } else {
3441 None
3442 }
3443 });
3444 (comment_delimiter, insert_extra_newline)
3445 } else {
3446 (None, false)
3447 };
3448
3449 let capacity_for_delimiter = comment_delimiter
3450 .as_deref()
3451 .map(str::len)
3452 .unwrap_or_default();
3453 let mut new_text =
3454 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3455 new_text.push_str("\n");
3456 new_text.extend(indent.chars());
3457 if let Some(delimiter) = &comment_delimiter {
3458 new_text.push_str(&delimiter);
3459 }
3460 if insert_extra_newline {
3461 new_text = new_text.repeat(2);
3462 }
3463
3464 let anchor = buffer.anchor_after(end);
3465 let new_selection = selection.map(|_| anchor);
3466 (
3467 (start..end, new_text),
3468 (insert_extra_newline, new_selection),
3469 )
3470 })
3471 .unzip()
3472 };
3473
3474 this.edit_with_autoindent(edits, cx);
3475 let buffer = this.buffer.read(cx).snapshot(cx);
3476 let new_selections = selection_fixup_info
3477 .into_iter()
3478 .map(|(extra_newline_inserted, new_selection)| {
3479 let mut cursor = new_selection.end.to_point(&buffer);
3480 if extra_newline_inserted {
3481 cursor.row -= 1;
3482 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3483 }
3484 new_selection.map(|_| cursor)
3485 })
3486 .collect();
3487
3488 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3489 this.refresh_inline_completion(true, cx);
3490 });
3491 }
3492
3493 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3494 let buffer = self.buffer.read(cx);
3495 let snapshot = buffer.snapshot(cx);
3496
3497 let mut edits = Vec::new();
3498 let mut rows = Vec::new();
3499
3500 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3501 let cursor = selection.head();
3502 let row = cursor.row;
3503
3504 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3505
3506 let newline = "\n".to_string();
3507 edits.push((start_of_line..start_of_line, newline));
3508
3509 rows.push(row + rows_inserted as u32);
3510 }
3511
3512 self.transact(cx, |editor, cx| {
3513 editor.edit(edits, cx);
3514
3515 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3516 let mut index = 0;
3517 s.move_cursors_with(|map, _, _| {
3518 let row = rows[index];
3519 index += 1;
3520
3521 let point = Point::new(row, 0);
3522 let boundary = map.next_line_boundary(point).1;
3523 let clipped = map.clip_point(boundary, Bias::Left);
3524
3525 (clipped, SelectionGoal::None)
3526 });
3527 });
3528
3529 let mut indent_edits = Vec::new();
3530 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3531 for row in rows {
3532 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3533 for (row, indent) in indents {
3534 if indent.len == 0 {
3535 continue;
3536 }
3537
3538 let text = match indent.kind {
3539 IndentKind::Space => " ".repeat(indent.len as usize),
3540 IndentKind::Tab => "\t".repeat(indent.len as usize),
3541 };
3542 let point = Point::new(row.0, 0);
3543 indent_edits.push((point..point, text));
3544 }
3545 }
3546 editor.edit(indent_edits, cx);
3547 });
3548 }
3549
3550 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3551 let buffer = self.buffer.read(cx);
3552 let snapshot = buffer.snapshot(cx);
3553
3554 let mut edits = Vec::new();
3555 let mut rows = Vec::new();
3556 let mut rows_inserted = 0;
3557
3558 for selection in self.selections.all_adjusted(cx) {
3559 let cursor = selection.head();
3560 let row = cursor.row;
3561
3562 let point = Point::new(row + 1, 0);
3563 let start_of_line = snapshot.clip_point(point, Bias::Left);
3564
3565 let newline = "\n".to_string();
3566 edits.push((start_of_line..start_of_line, newline));
3567
3568 rows_inserted += 1;
3569 rows.push(row + rows_inserted);
3570 }
3571
3572 self.transact(cx, |editor, cx| {
3573 editor.edit(edits, cx);
3574
3575 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3576 let mut index = 0;
3577 s.move_cursors_with(|map, _, _| {
3578 let row = rows[index];
3579 index += 1;
3580
3581 let point = Point::new(row, 0);
3582 let boundary = map.next_line_boundary(point).1;
3583 let clipped = map.clip_point(boundary, Bias::Left);
3584
3585 (clipped, SelectionGoal::None)
3586 });
3587 });
3588
3589 let mut indent_edits = Vec::new();
3590 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3591 for row in rows {
3592 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3593 for (row, indent) in indents {
3594 if indent.len == 0 {
3595 continue;
3596 }
3597
3598 let text = match indent.kind {
3599 IndentKind::Space => " ".repeat(indent.len as usize),
3600 IndentKind::Tab => "\t".repeat(indent.len as usize),
3601 };
3602 let point = Point::new(row.0, 0);
3603 indent_edits.push((point..point, text));
3604 }
3605 }
3606 editor.edit(indent_edits, cx);
3607 });
3608 }
3609
3610 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3611 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3612 original_indent_columns: Vec::new(),
3613 });
3614 self.insert_with_autoindent_mode(text, autoindent, cx);
3615 }
3616
3617 fn insert_with_autoindent_mode(
3618 &mut self,
3619 text: &str,
3620 autoindent_mode: Option<AutoindentMode>,
3621 cx: &mut ViewContext<Self>,
3622 ) {
3623 if self.read_only(cx) {
3624 return;
3625 }
3626
3627 let text: Arc<str> = text.into();
3628 self.transact(cx, |this, cx| {
3629 let old_selections = this.selections.all_adjusted(cx);
3630 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3631 let anchors = {
3632 let snapshot = buffer.read(cx);
3633 old_selections
3634 .iter()
3635 .map(|s| {
3636 let anchor = snapshot.anchor_after(s.head());
3637 s.map(|_| anchor)
3638 })
3639 .collect::<Vec<_>>()
3640 };
3641 buffer.edit(
3642 old_selections
3643 .iter()
3644 .map(|s| (s.start..s.end, text.clone())),
3645 autoindent_mode,
3646 cx,
3647 );
3648 anchors
3649 });
3650
3651 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3652 s.select_anchors(selection_anchors);
3653 })
3654 });
3655 }
3656
3657 fn trigger_completion_on_input(
3658 &mut self,
3659 text: &str,
3660 trigger_in_words: bool,
3661 cx: &mut ViewContext<Self>,
3662 ) {
3663 if self.is_completion_trigger(text, trigger_in_words, cx) {
3664 self.show_completions(
3665 &ShowCompletions {
3666 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3667 },
3668 cx,
3669 );
3670 } else {
3671 self.hide_context_menu(cx);
3672 }
3673 }
3674
3675 fn is_completion_trigger(
3676 &self,
3677 text: &str,
3678 trigger_in_words: bool,
3679 cx: &mut ViewContext<Self>,
3680 ) -> bool {
3681 let position = self.selections.newest_anchor().head();
3682 let multibuffer = self.buffer.read(cx);
3683 let Some(buffer) = position
3684 .buffer_id
3685 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3686 else {
3687 return false;
3688 };
3689
3690 if let Some(completion_provider) = &self.completion_provider {
3691 completion_provider.is_completion_trigger(
3692 &buffer,
3693 position.text_anchor,
3694 text,
3695 trigger_in_words,
3696 cx,
3697 )
3698 } else {
3699 false
3700 }
3701 }
3702
3703 /// If any empty selections is touching the start of its innermost containing autoclose
3704 /// region, expand it to select the brackets.
3705 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3706 let selections = self.selections.all::<usize>(cx);
3707 let buffer = self.buffer.read(cx).read(cx);
3708 let new_selections = self
3709 .selections_with_autoclose_regions(selections, &buffer)
3710 .map(|(mut selection, region)| {
3711 if !selection.is_empty() {
3712 return selection;
3713 }
3714
3715 if let Some(region) = region {
3716 let mut range = region.range.to_offset(&buffer);
3717 if selection.start == range.start && range.start >= region.pair.start.len() {
3718 range.start -= region.pair.start.len();
3719 if buffer.contains_str_at(range.start, ®ion.pair.start)
3720 && buffer.contains_str_at(range.end, ®ion.pair.end)
3721 {
3722 range.end += region.pair.end.len();
3723 selection.start = range.start;
3724 selection.end = range.end;
3725
3726 return selection;
3727 }
3728 }
3729 }
3730
3731 let always_treat_brackets_as_autoclosed = buffer
3732 .settings_at(selection.start, cx)
3733 .always_treat_brackets_as_autoclosed;
3734
3735 if !always_treat_brackets_as_autoclosed {
3736 return selection;
3737 }
3738
3739 if let Some(scope) = buffer.language_scope_at(selection.start) {
3740 for (pair, enabled) in scope.brackets() {
3741 if !enabled || !pair.close {
3742 continue;
3743 }
3744
3745 if buffer.contains_str_at(selection.start, &pair.end) {
3746 let pair_start_len = pair.start.len();
3747 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3748 {
3749 selection.start -= pair_start_len;
3750 selection.end += pair.end.len();
3751
3752 return selection;
3753 }
3754 }
3755 }
3756 }
3757
3758 selection
3759 })
3760 .collect();
3761
3762 drop(buffer);
3763 self.change_selections(None, cx, |selections| selections.select(new_selections));
3764 }
3765
3766 /// Iterate the given selections, and for each one, find the smallest surrounding
3767 /// autoclose region. This uses the ordering of the selections and the autoclose
3768 /// regions to avoid repeated comparisons.
3769 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3770 &'a self,
3771 selections: impl IntoIterator<Item = Selection<D>>,
3772 buffer: &'a MultiBufferSnapshot,
3773 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3774 let mut i = 0;
3775 let mut regions = self.autoclose_regions.as_slice();
3776 selections.into_iter().map(move |selection| {
3777 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3778
3779 let mut enclosing = None;
3780 while let Some(pair_state) = regions.get(i) {
3781 if pair_state.range.end.to_offset(buffer) < range.start {
3782 regions = ®ions[i + 1..];
3783 i = 0;
3784 } else if pair_state.range.start.to_offset(buffer) > range.end {
3785 break;
3786 } else {
3787 if pair_state.selection_id == selection.id {
3788 enclosing = Some(pair_state);
3789 }
3790 i += 1;
3791 }
3792 }
3793
3794 (selection.clone(), enclosing)
3795 })
3796 }
3797
3798 /// Remove any autoclose regions that no longer contain their selection.
3799 fn invalidate_autoclose_regions(
3800 &mut self,
3801 mut selections: &[Selection<Anchor>],
3802 buffer: &MultiBufferSnapshot,
3803 ) {
3804 self.autoclose_regions.retain(|state| {
3805 let mut i = 0;
3806 while let Some(selection) = selections.get(i) {
3807 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3808 selections = &selections[1..];
3809 continue;
3810 }
3811 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3812 break;
3813 }
3814 if selection.id == state.selection_id {
3815 return true;
3816 } else {
3817 i += 1;
3818 }
3819 }
3820 false
3821 });
3822 }
3823
3824 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3825 let offset = position.to_offset(buffer);
3826 let (word_range, kind) = buffer.surrounding_word(offset);
3827 if offset > word_range.start && kind == Some(CharKind::Word) {
3828 Some(
3829 buffer
3830 .text_for_range(word_range.start..offset)
3831 .collect::<String>(),
3832 )
3833 } else {
3834 None
3835 }
3836 }
3837
3838 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3839 self.refresh_inlay_hints(
3840 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3841 cx,
3842 );
3843 }
3844
3845 pub fn inlay_hints_enabled(&self) -> bool {
3846 self.inlay_hint_cache.enabled
3847 }
3848
3849 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3850 if self.project.is_none() || self.mode != EditorMode::Full {
3851 return;
3852 }
3853
3854 let reason_description = reason.description();
3855 let ignore_debounce = matches!(
3856 reason,
3857 InlayHintRefreshReason::SettingsChange(_)
3858 | InlayHintRefreshReason::Toggle(_)
3859 | InlayHintRefreshReason::ExcerptsRemoved(_)
3860 );
3861 let (invalidate_cache, required_languages) = match reason {
3862 InlayHintRefreshReason::Toggle(enabled) => {
3863 self.inlay_hint_cache.enabled = enabled;
3864 if enabled {
3865 (InvalidationStrategy::RefreshRequested, None)
3866 } else {
3867 self.inlay_hint_cache.clear();
3868 self.splice_inlays(
3869 self.visible_inlay_hints(cx)
3870 .iter()
3871 .map(|inlay| inlay.id)
3872 .collect(),
3873 Vec::new(),
3874 cx,
3875 );
3876 return;
3877 }
3878 }
3879 InlayHintRefreshReason::SettingsChange(new_settings) => {
3880 match self.inlay_hint_cache.update_settings(
3881 &self.buffer,
3882 new_settings,
3883 self.visible_inlay_hints(cx),
3884 cx,
3885 ) {
3886 ControlFlow::Break(Some(InlaySplice {
3887 to_remove,
3888 to_insert,
3889 })) => {
3890 self.splice_inlays(to_remove, to_insert, cx);
3891 return;
3892 }
3893 ControlFlow::Break(None) => return,
3894 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3895 }
3896 }
3897 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3898 if let Some(InlaySplice {
3899 to_remove,
3900 to_insert,
3901 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3902 {
3903 self.splice_inlays(to_remove, to_insert, cx);
3904 }
3905 return;
3906 }
3907 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3908 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3909 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3910 }
3911 InlayHintRefreshReason::RefreshRequested => {
3912 (InvalidationStrategy::RefreshRequested, None)
3913 }
3914 };
3915
3916 if let Some(InlaySplice {
3917 to_remove,
3918 to_insert,
3919 }) = self.inlay_hint_cache.spawn_hint_refresh(
3920 reason_description,
3921 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3922 invalidate_cache,
3923 ignore_debounce,
3924 cx,
3925 ) {
3926 self.splice_inlays(to_remove, to_insert, cx);
3927 }
3928 }
3929
3930 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
3931 self.display_map
3932 .read(cx)
3933 .current_inlays()
3934 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3935 .cloned()
3936 .collect()
3937 }
3938
3939 pub fn excerpts_for_inlay_hints_query(
3940 &self,
3941 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3942 cx: &mut ViewContext<Editor>,
3943 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3944 let Some(project) = self.project.as_ref() else {
3945 return HashMap::default();
3946 };
3947 let project = project.read(cx);
3948 let multi_buffer = self.buffer().read(cx);
3949 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3950 let multi_buffer_visible_start = self
3951 .scroll_manager
3952 .anchor()
3953 .anchor
3954 .to_point(&multi_buffer_snapshot);
3955 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3956 multi_buffer_visible_start
3957 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3958 Bias::Left,
3959 );
3960 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3961 multi_buffer
3962 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
3963 .into_iter()
3964 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3965 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
3966 let buffer = buffer_handle.read(cx);
3967 let buffer_file = project::File::from_dyn(buffer.file())?;
3968 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3969 let worktree_entry = buffer_worktree
3970 .read(cx)
3971 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3972 if worktree_entry.is_ignored {
3973 return None;
3974 }
3975
3976 let language = buffer.language()?;
3977 if let Some(restrict_to_languages) = restrict_to_languages {
3978 if !restrict_to_languages.contains(language) {
3979 return None;
3980 }
3981 }
3982 Some((
3983 excerpt_id,
3984 (
3985 buffer_handle,
3986 buffer.version().clone(),
3987 excerpt_visible_range,
3988 ),
3989 ))
3990 })
3991 .collect()
3992 }
3993
3994 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3995 TextLayoutDetails {
3996 text_system: cx.text_system().clone(),
3997 editor_style: self.style.clone().unwrap(),
3998 rem_size: cx.rem_size(),
3999 scroll_anchor: self.scroll_manager.anchor(),
4000 visible_rows: self.visible_line_count(),
4001 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4002 }
4003 }
4004
4005 fn splice_inlays(
4006 &self,
4007 to_remove: Vec<InlayId>,
4008 to_insert: Vec<Inlay>,
4009 cx: &mut ViewContext<Self>,
4010 ) {
4011 self.display_map.update(cx, |display_map, cx| {
4012 display_map.splice_inlays(to_remove, to_insert, cx);
4013 });
4014 cx.notify();
4015 }
4016
4017 fn trigger_on_type_formatting(
4018 &self,
4019 input: String,
4020 cx: &mut ViewContext<Self>,
4021 ) -> Option<Task<Result<()>>> {
4022 if input.len() != 1 {
4023 return None;
4024 }
4025
4026 let project = self.project.as_ref()?;
4027 let position = self.selections.newest_anchor().head();
4028 let (buffer, buffer_position) = self
4029 .buffer
4030 .read(cx)
4031 .text_anchor_for_position(position, cx)?;
4032
4033 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4034 // hence we do LSP request & edit on host side only — add formats to host's history.
4035 let push_to_lsp_host_history = true;
4036 // If this is not the host, append its history with new edits.
4037 let push_to_client_history = project.read(cx).is_remote();
4038
4039 let on_type_formatting = project.update(cx, |project, cx| {
4040 project.on_type_format(
4041 buffer.clone(),
4042 buffer_position,
4043 input,
4044 push_to_lsp_host_history,
4045 cx,
4046 )
4047 });
4048 Some(cx.spawn(|editor, mut cx| async move {
4049 if let Some(transaction) = on_type_formatting.await? {
4050 if push_to_client_history {
4051 buffer
4052 .update(&mut cx, |buffer, _| {
4053 buffer.push_transaction(transaction, Instant::now());
4054 })
4055 .ok();
4056 }
4057 editor.update(&mut cx, |editor, cx| {
4058 editor.refresh_document_highlights(cx);
4059 })?;
4060 }
4061 Ok(())
4062 }))
4063 }
4064
4065 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4066 if self.pending_rename.is_some() {
4067 return;
4068 }
4069
4070 let Some(provider) = self.completion_provider.as_ref() else {
4071 return;
4072 };
4073
4074 let position = self.selections.newest_anchor().head();
4075 let (buffer, buffer_position) =
4076 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4077 output
4078 } else {
4079 return;
4080 };
4081
4082 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4083 let is_followup_invoke = {
4084 let context_menu_state = self.context_menu.read();
4085 matches!(
4086 context_menu_state.deref(),
4087 Some(ContextMenu::Completions(_))
4088 )
4089 };
4090 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4091 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4092 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(&trigger) => {
4093 CompletionTriggerKind::TRIGGER_CHARACTER
4094 }
4095
4096 _ => CompletionTriggerKind::INVOKED,
4097 };
4098 let completion_context = CompletionContext {
4099 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4100 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4101 Some(String::from(trigger))
4102 } else {
4103 None
4104 }
4105 }),
4106 trigger_kind,
4107 };
4108 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4109
4110 let id = post_inc(&mut self.next_completion_id);
4111 let task = cx.spawn(|this, mut cx| {
4112 async move {
4113 this.update(&mut cx, |this, _| {
4114 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4115 })?;
4116 let completions = completions.await.log_err();
4117 let menu = if let Some(completions) = completions {
4118 let mut menu = CompletionsMenu {
4119 id,
4120 initial_position: position,
4121 match_candidates: completions
4122 .iter()
4123 .enumerate()
4124 .map(|(id, completion)| {
4125 StringMatchCandidate::new(
4126 id,
4127 completion.label.text[completion.label.filter_range.clone()]
4128 .into(),
4129 )
4130 })
4131 .collect(),
4132 buffer: buffer.clone(),
4133 completions: Arc::new(RwLock::new(completions.into())),
4134 matches: Vec::new().into(),
4135 selected_item: 0,
4136 scroll_handle: UniformListScrollHandle::new(),
4137 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4138 DebouncedDelay::new(),
4139 )),
4140 };
4141 menu.filter(query.as_deref(), cx.background_executor().clone())
4142 .await;
4143
4144 if menu.matches.is_empty() {
4145 None
4146 } else {
4147 this.update(&mut cx, |editor, cx| {
4148 let completions = menu.completions.clone();
4149 let matches = menu.matches.clone();
4150
4151 let delay_ms = EditorSettings::get_global(cx)
4152 .completion_documentation_secondary_query_debounce;
4153 let delay = Duration::from_millis(delay_ms);
4154 editor
4155 .completion_documentation_pre_resolve_debounce
4156 .fire_new(delay, cx, |editor, cx| {
4157 CompletionsMenu::pre_resolve_completion_documentation(
4158 buffer,
4159 completions,
4160 matches,
4161 editor,
4162 cx,
4163 )
4164 });
4165 })
4166 .ok();
4167 Some(menu)
4168 }
4169 } else {
4170 None
4171 };
4172
4173 this.update(&mut cx, |this, cx| {
4174 let mut context_menu = this.context_menu.write();
4175 match context_menu.as_ref() {
4176 None => {}
4177
4178 Some(ContextMenu::Completions(prev_menu)) => {
4179 if prev_menu.id > id {
4180 return;
4181 }
4182 }
4183
4184 _ => return,
4185 }
4186
4187 if this.focus_handle.is_focused(cx) && menu.is_some() {
4188 let menu = menu.unwrap();
4189 *context_menu = Some(ContextMenu::Completions(menu));
4190 drop(context_menu);
4191 this.discard_inline_completion(false, cx);
4192 cx.notify();
4193 } else if this.completion_tasks.len() <= 1 {
4194 // If there are no more completion tasks and the last menu was
4195 // empty, we should hide it. If it was already hidden, we should
4196 // also show the copilot completion when available.
4197 drop(context_menu);
4198 if this.hide_context_menu(cx).is_none() {
4199 this.update_visible_inline_completion(cx);
4200 }
4201 }
4202 })?;
4203
4204 Ok::<_, anyhow::Error>(())
4205 }
4206 .log_err()
4207 });
4208
4209 self.completion_tasks.push((id, task));
4210 }
4211
4212 pub fn confirm_completion(
4213 &mut self,
4214 action: &ConfirmCompletion,
4215 cx: &mut ViewContext<Self>,
4216 ) -> Option<Task<Result<()>>> {
4217 use language::ToOffset as _;
4218
4219 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4220 menu
4221 } else {
4222 return None;
4223 };
4224
4225 let mat = completions_menu
4226 .matches
4227 .get(action.item_ix.unwrap_or(completions_menu.selected_item))?;
4228 let buffer_handle = completions_menu.buffer;
4229 let completions = completions_menu.completions.read();
4230 let completion = completions.get(mat.candidate_id)?;
4231 cx.stop_propagation();
4232
4233 let snippet;
4234 let text;
4235
4236 if completion.is_snippet() {
4237 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4238 text = snippet.as_ref().unwrap().text.clone();
4239 } else {
4240 snippet = None;
4241 text = completion.new_text.clone();
4242 };
4243 let selections = self.selections.all::<usize>(cx);
4244 let buffer = buffer_handle.read(cx);
4245 let old_range = completion.old_range.to_offset(buffer);
4246 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4247
4248 let newest_selection = self.selections.newest_anchor();
4249 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4250 return None;
4251 }
4252
4253 let lookbehind = newest_selection
4254 .start
4255 .text_anchor
4256 .to_offset(buffer)
4257 .saturating_sub(old_range.start);
4258 let lookahead = old_range
4259 .end
4260 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4261 let mut common_prefix_len = old_text
4262 .bytes()
4263 .zip(text.bytes())
4264 .take_while(|(a, b)| a == b)
4265 .count();
4266
4267 let snapshot = self.buffer.read(cx).snapshot(cx);
4268 let mut range_to_replace: Option<Range<isize>> = None;
4269 let mut ranges = Vec::new();
4270 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4271 for selection in &selections {
4272 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4273 let start = selection.start.saturating_sub(lookbehind);
4274 let end = selection.end + lookahead;
4275 if selection.id == newest_selection.id {
4276 range_to_replace = Some(
4277 ((start + common_prefix_len) as isize - selection.start as isize)
4278 ..(end as isize - selection.start as isize),
4279 );
4280 }
4281 ranges.push(start + common_prefix_len..end);
4282 } else {
4283 common_prefix_len = 0;
4284 ranges.clear();
4285 ranges.extend(selections.iter().map(|s| {
4286 if s.id == newest_selection.id {
4287 range_to_replace = Some(
4288 old_range.start.to_offset_utf16(&snapshot).0 as isize
4289 - selection.start as isize
4290 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4291 - selection.start as isize,
4292 );
4293 old_range.clone()
4294 } else {
4295 s.start..s.end
4296 }
4297 }));
4298 break;
4299 }
4300 if !self.linked_edit_ranges.is_empty() {
4301 let start_anchor = snapshot.anchor_before(selection.head());
4302 let end_anchor = snapshot.anchor_after(selection.tail());
4303 if let Some(ranges) = self
4304 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4305 {
4306 for (buffer, edits) in ranges {
4307 linked_edits.entry(buffer.clone()).or_default().extend(
4308 edits
4309 .into_iter()
4310 .map(|range| (range, text[common_prefix_len..].to_owned())),
4311 );
4312 }
4313 }
4314 }
4315 }
4316 let text = &text[common_prefix_len..];
4317
4318 cx.emit(EditorEvent::InputHandled {
4319 utf16_range_to_replace: range_to_replace,
4320 text: text.into(),
4321 });
4322
4323 self.transact(cx, |this, cx| {
4324 if let Some(mut snippet) = snippet {
4325 snippet.text = text.to_string();
4326 for tabstop in snippet.tabstops.iter_mut().flatten() {
4327 tabstop.start -= common_prefix_len as isize;
4328 tabstop.end -= common_prefix_len as isize;
4329 }
4330
4331 this.insert_snippet(&ranges, snippet, cx).log_err();
4332 } else {
4333 this.buffer.update(cx, |buffer, cx| {
4334 buffer.edit(
4335 ranges.iter().map(|range| (range.clone(), text)),
4336 this.autoindent_mode.clone(),
4337 cx,
4338 );
4339 });
4340 }
4341 for (buffer, edits) in linked_edits {
4342 buffer.update(cx, |buffer, cx| {
4343 let snapshot = buffer.snapshot();
4344 let edits = edits
4345 .into_iter()
4346 .map(|(range, text)| {
4347 use text::ToPoint as TP;
4348 let end_point = TP::to_point(&range.end, &snapshot);
4349 let start_point = TP::to_point(&range.start, &snapshot);
4350 (start_point..end_point, text)
4351 })
4352 .sorted_by_key(|(range, _)| range.start)
4353 .collect::<Vec<_>>();
4354 buffer.edit(edits, None, cx);
4355 })
4356 }
4357
4358 this.refresh_inline_completion(true, cx);
4359 });
4360
4361 if let Some(confirm) = completion.confirm.as_ref() {
4362 (confirm)(cx);
4363 }
4364
4365 if completion.show_new_completions_on_confirm {
4366 self.show_completions(&ShowCompletions { trigger: None }, cx);
4367 }
4368
4369 let provider = self.completion_provider.as_ref()?;
4370 let apply_edits = provider.apply_additional_edits_for_completion(
4371 buffer_handle,
4372 completion.clone(),
4373 true,
4374 cx,
4375 );
4376
4377 let editor_settings = EditorSettings::get_global(cx);
4378 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4379 // After the code completion is finished, users often want to know what signatures are needed.
4380 // so we should automatically call signature_help
4381 self.show_signature_help(&ShowSignatureHelp, cx);
4382 }
4383
4384 Some(cx.foreground_executor().spawn(async move {
4385 apply_edits.await?;
4386 Ok(())
4387 }))
4388 }
4389
4390 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4391 let mut context_menu = self.context_menu.write();
4392 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4393 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4394 // Toggle if we're selecting the same one
4395 *context_menu = None;
4396 cx.notify();
4397 return;
4398 } else {
4399 // Otherwise, clear it and start a new one
4400 *context_menu = None;
4401 cx.notify();
4402 }
4403 }
4404 drop(context_menu);
4405 let snapshot = self.snapshot(cx);
4406 let deployed_from_indicator = action.deployed_from_indicator;
4407 let mut task = self.code_actions_task.take();
4408 let action = action.clone();
4409 cx.spawn(|editor, mut cx| async move {
4410 while let Some(prev_task) = task {
4411 prev_task.await;
4412 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4413 }
4414
4415 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4416 if editor.focus_handle.is_focused(cx) {
4417 let multibuffer_point = action
4418 .deployed_from_indicator
4419 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4420 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4421 let (buffer, buffer_row) = snapshot
4422 .buffer_snapshot
4423 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4424 .and_then(|(buffer_snapshot, range)| {
4425 editor
4426 .buffer
4427 .read(cx)
4428 .buffer(buffer_snapshot.remote_id())
4429 .map(|buffer| (buffer, range.start.row))
4430 })?;
4431 let (_, code_actions) = editor
4432 .available_code_actions
4433 .clone()
4434 .and_then(|(location, code_actions)| {
4435 let snapshot = location.buffer.read(cx).snapshot();
4436 let point_range = location.range.to_point(&snapshot);
4437 let point_range = point_range.start.row..=point_range.end.row;
4438 if point_range.contains(&buffer_row) {
4439 Some((location, code_actions))
4440 } else {
4441 None
4442 }
4443 })
4444 .unzip();
4445 let buffer_id = buffer.read(cx).remote_id();
4446 let tasks = editor
4447 .tasks
4448 .get(&(buffer_id, buffer_row))
4449 .map(|t| Arc::new(t.to_owned()));
4450 if tasks.is_none() && code_actions.is_none() {
4451 return None;
4452 }
4453
4454 editor.completion_tasks.clear();
4455 editor.discard_inline_completion(false, cx);
4456 let task_context =
4457 tasks
4458 .as_ref()
4459 .zip(editor.project.clone())
4460 .map(|(tasks, project)| {
4461 let position = Point::new(buffer_row, tasks.column);
4462 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4463 let location = Location {
4464 buffer: buffer.clone(),
4465 range: range_start..range_start,
4466 };
4467 // Fill in the environmental variables from the tree-sitter captures
4468 let mut captured_task_variables = TaskVariables::default();
4469 for (capture_name, value) in tasks.extra_variables.clone() {
4470 captured_task_variables.insert(
4471 task::VariableName::Custom(capture_name.into()),
4472 value.clone(),
4473 );
4474 }
4475 project.update(cx, |project, cx| {
4476 project.task_context_for_location(
4477 captured_task_variables,
4478 location,
4479 cx,
4480 )
4481 })
4482 });
4483
4484 Some(cx.spawn(|editor, mut cx| async move {
4485 let task_context = match task_context {
4486 Some(task_context) => task_context.await,
4487 None => None,
4488 };
4489 let resolved_tasks =
4490 tasks.zip(task_context).map(|(tasks, task_context)| {
4491 Arc::new(ResolvedTasks {
4492 templates: tasks
4493 .templates
4494 .iter()
4495 .filter_map(|(kind, template)| {
4496 template
4497 .resolve_task(&kind.to_id_base(), &task_context)
4498 .map(|task| (kind.clone(), task))
4499 })
4500 .collect(),
4501 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4502 multibuffer_point.row,
4503 tasks.column,
4504 )),
4505 })
4506 });
4507 let spawn_straight_away = resolved_tasks
4508 .as_ref()
4509 .map_or(false, |tasks| tasks.templates.len() == 1)
4510 && code_actions
4511 .as_ref()
4512 .map_or(true, |actions| actions.is_empty());
4513 if let Some(task) = editor
4514 .update(&mut cx, |editor, cx| {
4515 *editor.context_menu.write() =
4516 Some(ContextMenu::CodeActions(CodeActionsMenu {
4517 buffer,
4518 actions: CodeActionContents {
4519 tasks: resolved_tasks,
4520 actions: code_actions,
4521 },
4522 selected_item: Default::default(),
4523 scroll_handle: UniformListScrollHandle::default(),
4524 deployed_from_indicator,
4525 }));
4526 if spawn_straight_away {
4527 if let Some(task) = editor.confirm_code_action(
4528 &ConfirmCodeAction { item_ix: Some(0) },
4529 cx,
4530 ) {
4531 cx.notify();
4532 return task;
4533 }
4534 }
4535 cx.notify();
4536 Task::ready(Ok(()))
4537 })
4538 .ok()
4539 {
4540 task.await
4541 } else {
4542 Ok(())
4543 }
4544 }))
4545 } else {
4546 Some(Task::ready(Ok(())))
4547 }
4548 })?;
4549 if let Some(task) = spawned_test_task {
4550 task.await?;
4551 }
4552
4553 Ok::<_, anyhow::Error>(())
4554 })
4555 .detach_and_log_err(cx);
4556 }
4557
4558 pub fn confirm_code_action(
4559 &mut self,
4560 action: &ConfirmCodeAction,
4561 cx: &mut ViewContext<Self>,
4562 ) -> Option<Task<Result<()>>> {
4563 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4564 menu
4565 } else {
4566 return None;
4567 };
4568 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4569 let action = actions_menu.actions.get(action_ix)?;
4570 let title = action.label();
4571 let buffer = actions_menu.buffer;
4572 let workspace = self.workspace()?;
4573
4574 match action {
4575 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4576 workspace.update(cx, |workspace, cx| {
4577 workspace::tasks::schedule_resolved_task(
4578 workspace,
4579 task_source_kind,
4580 resolved_task,
4581 false,
4582 cx,
4583 );
4584
4585 Some(Task::ready(Ok(())))
4586 })
4587 }
4588 CodeActionsItem::CodeAction(action) => {
4589 let apply_code_actions = workspace
4590 .read(cx)
4591 .project()
4592 .clone()
4593 .update(cx, |project, cx| {
4594 project.apply_code_action(buffer, action, true, cx)
4595 });
4596 let workspace = workspace.downgrade();
4597 Some(cx.spawn(|editor, cx| async move {
4598 let project_transaction = apply_code_actions.await?;
4599 Self::open_project_transaction(
4600 &editor,
4601 workspace,
4602 project_transaction,
4603 title,
4604 cx,
4605 )
4606 .await
4607 }))
4608 }
4609 }
4610 }
4611
4612 pub async fn open_project_transaction(
4613 this: &WeakView<Editor>,
4614 workspace: WeakView<Workspace>,
4615 transaction: ProjectTransaction,
4616 title: String,
4617 mut cx: AsyncWindowContext,
4618 ) -> Result<()> {
4619 let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
4620
4621 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4622 cx.update(|cx| {
4623 entries.sort_unstable_by_key(|(buffer, _)| {
4624 buffer.read(cx).file().map(|f| f.path().clone())
4625 });
4626 })?;
4627
4628 // If the project transaction's edits are all contained within this editor, then
4629 // avoid opening a new editor to display them.
4630
4631 if let Some((buffer, transaction)) = entries.first() {
4632 if entries.len() == 1 {
4633 let excerpt = this.update(&mut cx, |editor, cx| {
4634 editor
4635 .buffer()
4636 .read(cx)
4637 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4638 })?;
4639 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4640 if excerpted_buffer == *buffer {
4641 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4642 let excerpt_range = excerpt_range.to_offset(buffer);
4643 buffer
4644 .edited_ranges_for_transaction::<usize>(transaction)
4645 .all(|range| {
4646 excerpt_range.start <= range.start
4647 && excerpt_range.end >= range.end
4648 })
4649 })?;
4650
4651 if all_edits_within_excerpt {
4652 return Ok(());
4653 }
4654 }
4655 }
4656 }
4657 } else {
4658 return Ok(());
4659 }
4660
4661 let mut ranges_to_highlight = Vec::new();
4662 let excerpt_buffer = cx.new_model(|cx| {
4663 let mut multibuffer =
4664 MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
4665 for (buffer_handle, transaction) in &entries {
4666 let buffer = buffer_handle.read(cx);
4667 ranges_to_highlight.extend(
4668 multibuffer.push_excerpts_with_context_lines(
4669 buffer_handle.clone(),
4670 buffer
4671 .edited_ranges_for_transaction::<usize>(transaction)
4672 .collect(),
4673 DEFAULT_MULTIBUFFER_CONTEXT,
4674 cx,
4675 ),
4676 );
4677 }
4678 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4679 multibuffer
4680 })?;
4681
4682 workspace.update(&mut cx, |workspace, cx| {
4683 let project = workspace.project().clone();
4684 let editor =
4685 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4686 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4687 editor.update(cx, |editor, cx| {
4688 editor.highlight_background::<Self>(
4689 &ranges_to_highlight,
4690 |theme| theme.editor_highlighted_line_background,
4691 cx,
4692 );
4693 });
4694 })?;
4695
4696 Ok(())
4697 }
4698
4699 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4700 let project = self.project.clone()?;
4701 let buffer = self.buffer.read(cx);
4702 let newest_selection = self.selections.newest_anchor().clone();
4703 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4704 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4705 if start_buffer != end_buffer {
4706 return None;
4707 }
4708
4709 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4710 cx.background_executor()
4711 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4712 .await;
4713
4714 let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
4715 project.code_actions(&start_buffer, start..end, cx)
4716 }) {
4717 code_actions.await
4718 } else {
4719 Vec::new()
4720 };
4721
4722 this.update(&mut cx, |this, cx| {
4723 this.available_code_actions = if actions.is_empty() {
4724 None
4725 } else {
4726 Some((
4727 Location {
4728 buffer: start_buffer,
4729 range: start..end,
4730 },
4731 actions.into(),
4732 ))
4733 };
4734 cx.notify();
4735 })
4736 .log_err();
4737 }));
4738 None
4739 }
4740
4741 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4742 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4743 self.show_git_blame_inline = false;
4744
4745 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4746 cx.background_executor().timer(delay).await;
4747
4748 this.update(&mut cx, |this, cx| {
4749 this.show_git_blame_inline = true;
4750 cx.notify();
4751 })
4752 .log_err();
4753 }));
4754 }
4755 }
4756
4757 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4758 if self.pending_rename.is_some() {
4759 return None;
4760 }
4761
4762 let project = self.project.clone()?;
4763 let buffer = self.buffer.read(cx);
4764 let newest_selection = self.selections.newest_anchor().clone();
4765 let cursor_position = newest_selection.head();
4766 let (cursor_buffer, cursor_buffer_position) =
4767 buffer.text_anchor_for_position(cursor_position, cx)?;
4768 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4769 if cursor_buffer != tail_buffer {
4770 return None;
4771 }
4772
4773 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4774 cx.background_executor()
4775 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
4776 .await;
4777
4778 let highlights = if let Some(highlights) = project
4779 .update(&mut cx, |project, cx| {
4780 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4781 })
4782 .log_err()
4783 {
4784 highlights.await.log_err()
4785 } else {
4786 None
4787 };
4788
4789 if let Some(highlights) = highlights {
4790 this.update(&mut cx, |this, cx| {
4791 if this.pending_rename.is_some() {
4792 return;
4793 }
4794
4795 let buffer_id = cursor_position.buffer_id;
4796 let buffer = this.buffer.read(cx);
4797 if !buffer
4798 .text_anchor_for_position(cursor_position, cx)
4799 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4800 {
4801 return;
4802 }
4803
4804 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4805 let mut write_ranges = Vec::new();
4806 let mut read_ranges = Vec::new();
4807 for highlight in highlights {
4808 for (excerpt_id, excerpt_range) in
4809 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4810 {
4811 let start = highlight
4812 .range
4813 .start
4814 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4815 let end = highlight
4816 .range
4817 .end
4818 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4819 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4820 continue;
4821 }
4822
4823 let range = Anchor {
4824 buffer_id,
4825 excerpt_id: excerpt_id,
4826 text_anchor: start,
4827 }..Anchor {
4828 buffer_id,
4829 excerpt_id,
4830 text_anchor: end,
4831 };
4832 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4833 write_ranges.push(range);
4834 } else {
4835 read_ranges.push(range);
4836 }
4837 }
4838 }
4839
4840 this.highlight_background::<DocumentHighlightRead>(
4841 &read_ranges,
4842 |theme| theme.editor_document_highlight_read_background,
4843 cx,
4844 );
4845 this.highlight_background::<DocumentHighlightWrite>(
4846 &write_ranges,
4847 |theme| theme.editor_document_highlight_write_background,
4848 cx,
4849 );
4850 cx.notify();
4851 })
4852 .log_err();
4853 }
4854 }));
4855 None
4856 }
4857
4858 fn refresh_inline_completion(
4859 &mut self,
4860 debounce: bool,
4861 cx: &mut ViewContext<Self>,
4862 ) -> Option<()> {
4863 let provider = self.inline_completion_provider()?;
4864 let cursor = self.selections.newest_anchor().head();
4865 let (buffer, cursor_buffer_position) =
4866 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4867 if !self.show_inline_completions
4868 || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
4869 {
4870 self.discard_inline_completion(false, cx);
4871 return None;
4872 }
4873
4874 self.update_visible_inline_completion(cx);
4875 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4876 Some(())
4877 }
4878
4879 fn cycle_inline_completion(
4880 &mut self,
4881 direction: Direction,
4882 cx: &mut ViewContext<Self>,
4883 ) -> Option<()> {
4884 let provider = self.inline_completion_provider()?;
4885 let cursor = self.selections.newest_anchor().head();
4886 let (buffer, cursor_buffer_position) =
4887 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4888 if !self.show_inline_completions
4889 || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
4890 {
4891 return None;
4892 }
4893
4894 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4895 self.update_visible_inline_completion(cx);
4896
4897 Some(())
4898 }
4899
4900 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4901 if !self.has_active_inline_completion(cx) {
4902 self.refresh_inline_completion(false, cx);
4903 return;
4904 }
4905
4906 self.update_visible_inline_completion(cx);
4907 }
4908
4909 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4910 self.show_cursor_names(cx);
4911 }
4912
4913 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4914 self.show_cursor_names = true;
4915 cx.notify();
4916 cx.spawn(|this, mut cx| async move {
4917 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4918 this.update(&mut cx, |this, cx| {
4919 this.show_cursor_names = false;
4920 cx.notify()
4921 })
4922 .ok()
4923 })
4924 .detach();
4925 }
4926
4927 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4928 if self.has_active_inline_completion(cx) {
4929 self.cycle_inline_completion(Direction::Next, cx);
4930 } else {
4931 let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
4932 if is_copilot_disabled {
4933 cx.propagate();
4934 }
4935 }
4936 }
4937
4938 pub fn previous_inline_completion(
4939 &mut self,
4940 _: &PreviousInlineCompletion,
4941 cx: &mut ViewContext<Self>,
4942 ) {
4943 if self.has_active_inline_completion(cx) {
4944 self.cycle_inline_completion(Direction::Prev, cx);
4945 } else {
4946 let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
4947 if is_copilot_disabled {
4948 cx.propagate();
4949 }
4950 }
4951 }
4952
4953 pub fn accept_inline_completion(
4954 &mut self,
4955 _: &AcceptInlineCompletion,
4956 cx: &mut ViewContext<Self>,
4957 ) {
4958 let Some((completion, delete_range)) = self.take_active_inline_completion(cx) else {
4959 return;
4960 };
4961 if let Some(provider) = self.inline_completion_provider() {
4962 provider.accept(cx);
4963 }
4964
4965 cx.emit(EditorEvent::InputHandled {
4966 utf16_range_to_replace: None,
4967 text: completion.text.to_string().into(),
4968 });
4969
4970 if let Some(range) = delete_range {
4971 self.change_selections(None, cx, |s| s.select_ranges([range]))
4972 }
4973 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
4974 self.refresh_inline_completion(true, cx);
4975 cx.notify();
4976 }
4977
4978 pub fn accept_partial_inline_completion(
4979 &mut self,
4980 _: &AcceptPartialInlineCompletion,
4981 cx: &mut ViewContext<Self>,
4982 ) {
4983 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
4984 if let Some((completion, delete_range)) = self.take_active_inline_completion(cx) {
4985 let mut partial_completion = completion
4986 .text
4987 .chars()
4988 .by_ref()
4989 .take_while(|c| c.is_alphabetic())
4990 .collect::<String>();
4991 if partial_completion.is_empty() {
4992 partial_completion = completion
4993 .text
4994 .chars()
4995 .by_ref()
4996 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4997 .collect::<String>();
4998 }
4999
5000 cx.emit(EditorEvent::InputHandled {
5001 utf16_range_to_replace: None,
5002 text: partial_completion.clone().into(),
5003 });
5004
5005 if let Some(range) = delete_range {
5006 self.change_selections(None, cx, |s| s.select_ranges([range]))
5007 }
5008 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5009
5010 self.refresh_inline_completion(true, cx);
5011 cx.notify();
5012 }
5013 }
5014 }
5015
5016 fn discard_inline_completion(
5017 &mut self,
5018 should_report_inline_completion_event: bool,
5019 cx: &mut ViewContext<Self>,
5020 ) -> bool {
5021 if let Some(provider) = self.inline_completion_provider() {
5022 provider.discard(should_report_inline_completion_event, cx);
5023 }
5024
5025 self.take_active_inline_completion(cx).is_some()
5026 }
5027
5028 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5029 if let Some(completion) = self.active_inline_completion.as_ref() {
5030 let buffer = self.buffer.read(cx).read(cx);
5031 completion.0.position.is_valid(&buffer)
5032 } else {
5033 false
5034 }
5035 }
5036
5037 fn take_active_inline_completion(
5038 &mut self,
5039 cx: &mut ViewContext<Self>,
5040 ) -> Option<(Inlay, Option<Range<Anchor>>)> {
5041 let completion = self.active_inline_completion.take()?;
5042 self.display_map.update(cx, |map, cx| {
5043 map.splice_inlays(vec![completion.0.id], Default::default(), cx);
5044 });
5045 let buffer = self.buffer.read(cx).read(cx);
5046
5047 if completion.0.position.is_valid(&buffer) {
5048 Some(completion)
5049 } else {
5050 None
5051 }
5052 }
5053
5054 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5055 let selection = self.selections.newest_anchor();
5056 let cursor = selection.head();
5057
5058 let excerpt_id = cursor.excerpt_id;
5059
5060 if self.context_menu.read().is_none()
5061 && self.completion_tasks.is_empty()
5062 && selection.start == selection.end
5063 {
5064 if let Some(provider) = self.inline_completion_provider() {
5065 if let Some((buffer, cursor_buffer_position)) =
5066 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5067 {
5068 if let Some((text, text_anchor_range)) =
5069 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5070 {
5071 let text = Rope::from(text);
5072 let mut to_remove = Vec::new();
5073 if let Some(completion) = self.active_inline_completion.take() {
5074 to_remove.push(completion.0.id);
5075 }
5076
5077 let completion_inlay =
5078 Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
5079
5080 let multibuffer_anchor_range = text_anchor_range.and_then(|range| {
5081 let snapshot = self.buffer.read(cx).snapshot(cx);
5082 Some(
5083 snapshot.anchor_in_excerpt(excerpt_id, range.start)?
5084 ..snapshot.anchor_in_excerpt(excerpt_id, range.end)?,
5085 )
5086 });
5087 self.active_inline_completion =
5088 Some((completion_inlay.clone(), multibuffer_anchor_range));
5089
5090 self.display_map.update(cx, move |map, cx| {
5091 map.splice_inlays(to_remove, vec![completion_inlay], cx)
5092 });
5093 cx.notify();
5094 return;
5095 }
5096 }
5097 }
5098 }
5099
5100 self.discard_inline_completion(false, cx);
5101 }
5102
5103 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5104 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5105 }
5106
5107 fn render_code_actions_indicator(
5108 &self,
5109 _style: &EditorStyle,
5110 row: DisplayRow,
5111 is_active: bool,
5112 cx: &mut ViewContext<Self>,
5113 ) -> Option<IconButton> {
5114 if self.available_code_actions.is_some() {
5115 Some(
5116 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5117 .shape(ui::IconButtonShape::Square)
5118 .icon_size(IconSize::XSmall)
5119 .icon_color(Color::Muted)
5120 .selected(is_active)
5121 .on_click(cx.listener(move |editor, _e, cx| {
5122 editor.focus(cx);
5123 editor.toggle_code_actions(
5124 &ToggleCodeActions {
5125 deployed_from_indicator: Some(row),
5126 },
5127 cx,
5128 );
5129 })),
5130 )
5131 } else {
5132 None
5133 }
5134 }
5135
5136 fn clear_tasks(&mut self) {
5137 self.tasks.clear()
5138 }
5139
5140 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5141 if let Some(_) = self.tasks.insert(key, value) {
5142 // This case should hopefully be rare, but just in case...
5143 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5144 }
5145 }
5146
5147 fn render_run_indicator(
5148 &self,
5149 _style: &EditorStyle,
5150 is_active: bool,
5151 row: DisplayRow,
5152 cx: &mut ViewContext<Self>,
5153 ) -> IconButton {
5154 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5155 .shape(ui::IconButtonShape::Square)
5156 .icon_size(IconSize::XSmall)
5157 .icon_color(Color::Muted)
5158 .selected(is_active)
5159 .on_click(cx.listener(move |editor, _e, cx| {
5160 editor.focus(cx);
5161 editor.toggle_code_actions(
5162 &ToggleCodeActions {
5163 deployed_from_indicator: Some(row),
5164 },
5165 cx,
5166 );
5167 }))
5168 }
5169
5170 fn render_close_hunk_diff_button(
5171 &self,
5172 hunk: HoveredHunk,
5173 row: DisplayRow,
5174 cx: &mut ViewContext<Self>,
5175 ) -> IconButton {
5176 IconButton::new(
5177 ("close_hunk_diff_indicator", row.0 as usize),
5178 ui::IconName::Close,
5179 )
5180 .shape(ui::IconButtonShape::Square)
5181 .icon_size(IconSize::XSmall)
5182 .icon_color(Color::Muted)
5183 .tooltip(|cx| Tooltip::for_action("Close hunk diff", &ToggleHunkDiff, cx))
5184 .on_click(cx.listener(move |editor, _e, cx| editor.toggle_hovered_hunk(&hunk, cx)))
5185 }
5186
5187 pub fn context_menu_visible(&self) -> bool {
5188 self.context_menu
5189 .read()
5190 .as_ref()
5191 .map_or(false, |menu| menu.visible())
5192 }
5193
5194 fn render_context_menu(
5195 &self,
5196 cursor_position: DisplayPoint,
5197 style: &EditorStyle,
5198 max_height: Pixels,
5199 cx: &mut ViewContext<Editor>,
5200 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5201 self.context_menu.read().as_ref().map(|menu| {
5202 menu.render(
5203 cursor_position,
5204 style,
5205 max_height,
5206 self.workspace.as_ref().map(|(w, _)| w.clone()),
5207 cx,
5208 )
5209 })
5210 }
5211
5212 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5213 cx.notify();
5214 self.completion_tasks.clear();
5215 let context_menu = self.context_menu.write().take();
5216 if context_menu.is_some() {
5217 self.update_visible_inline_completion(cx);
5218 }
5219 context_menu
5220 }
5221
5222 pub fn insert_snippet(
5223 &mut self,
5224 insertion_ranges: &[Range<usize>],
5225 snippet: Snippet,
5226 cx: &mut ViewContext<Self>,
5227 ) -> Result<()> {
5228 struct Tabstop<T> {
5229 is_end_tabstop: bool,
5230 ranges: Vec<Range<T>>,
5231 }
5232
5233 let tabstops = self.buffer.update(cx, |buffer, cx| {
5234 let snippet_text: Arc<str> = snippet.text.clone().into();
5235 buffer.edit(
5236 insertion_ranges
5237 .iter()
5238 .cloned()
5239 .map(|range| (range, snippet_text.clone())),
5240 Some(AutoindentMode::EachLine),
5241 cx,
5242 );
5243
5244 let snapshot = &*buffer.read(cx);
5245 let snippet = &snippet;
5246 snippet
5247 .tabstops
5248 .iter()
5249 .map(|tabstop| {
5250 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5251 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5252 });
5253 let mut tabstop_ranges = tabstop
5254 .iter()
5255 .flat_map(|tabstop_range| {
5256 let mut delta = 0_isize;
5257 insertion_ranges.iter().map(move |insertion_range| {
5258 let insertion_start = insertion_range.start as isize + delta;
5259 delta +=
5260 snippet.text.len() as isize - insertion_range.len() as isize;
5261
5262 let start = ((insertion_start + tabstop_range.start) as usize)
5263 .min(snapshot.len());
5264 let end = ((insertion_start + tabstop_range.end) as usize)
5265 .min(snapshot.len());
5266 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5267 })
5268 })
5269 .collect::<Vec<_>>();
5270 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5271
5272 Tabstop {
5273 is_end_tabstop,
5274 ranges: tabstop_ranges,
5275 }
5276 })
5277 .collect::<Vec<_>>()
5278 });
5279 if let Some(tabstop) = tabstops.first() {
5280 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5281 s.select_ranges(tabstop.ranges.iter().cloned());
5282 });
5283
5284 // If we're already at the last tabstop and it's at the end of the snippet,
5285 // we're done, we don't need to keep the state around.
5286 if !tabstop.is_end_tabstop {
5287 let ranges = tabstops
5288 .into_iter()
5289 .map(|tabstop| tabstop.ranges)
5290 .collect::<Vec<_>>();
5291 self.snippet_stack.push(SnippetState {
5292 active_index: 0,
5293 ranges,
5294 });
5295 }
5296
5297 // Check whether the just-entered snippet ends with an auto-closable bracket.
5298 if self.autoclose_regions.is_empty() {
5299 let snapshot = self.buffer.read(cx).snapshot(cx);
5300 for selection in &mut self.selections.all::<Point>(cx) {
5301 let selection_head = selection.head();
5302 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5303 continue;
5304 };
5305
5306 let mut bracket_pair = None;
5307 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5308 let prev_chars = snapshot
5309 .reversed_chars_at(selection_head)
5310 .collect::<String>();
5311 for (pair, enabled) in scope.brackets() {
5312 if enabled
5313 && pair.close
5314 && prev_chars.starts_with(pair.start.as_str())
5315 && next_chars.starts_with(pair.end.as_str())
5316 {
5317 bracket_pair = Some(pair.clone());
5318 break;
5319 }
5320 }
5321 if let Some(pair) = bracket_pair {
5322 let start = snapshot.anchor_after(selection_head);
5323 let end = snapshot.anchor_after(selection_head);
5324 self.autoclose_regions.push(AutocloseRegion {
5325 selection_id: selection.id,
5326 range: start..end,
5327 pair,
5328 });
5329 }
5330 }
5331 }
5332 }
5333 Ok(())
5334 }
5335
5336 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5337 self.move_to_snippet_tabstop(Bias::Right, cx)
5338 }
5339
5340 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5341 self.move_to_snippet_tabstop(Bias::Left, cx)
5342 }
5343
5344 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5345 if let Some(mut snippet) = self.snippet_stack.pop() {
5346 match bias {
5347 Bias::Left => {
5348 if snippet.active_index > 0 {
5349 snippet.active_index -= 1;
5350 } else {
5351 self.snippet_stack.push(snippet);
5352 return false;
5353 }
5354 }
5355 Bias::Right => {
5356 if snippet.active_index + 1 < snippet.ranges.len() {
5357 snippet.active_index += 1;
5358 } else {
5359 self.snippet_stack.push(snippet);
5360 return false;
5361 }
5362 }
5363 }
5364 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5365 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5366 s.select_anchor_ranges(current_ranges.iter().cloned())
5367 });
5368 // If snippet state is not at the last tabstop, push it back on the stack
5369 if snippet.active_index + 1 < snippet.ranges.len() {
5370 self.snippet_stack.push(snippet);
5371 }
5372 return true;
5373 }
5374 }
5375
5376 false
5377 }
5378
5379 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5380 self.transact(cx, |this, cx| {
5381 this.select_all(&SelectAll, cx);
5382 this.insert("", cx);
5383 });
5384 }
5385
5386 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5387 self.transact(cx, |this, cx| {
5388 this.select_autoclose_pair(cx);
5389 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5390 if !this.linked_edit_ranges.is_empty() {
5391 let selections = this.selections.all::<MultiBufferPoint>(cx);
5392 let snapshot = this.buffer.read(cx).snapshot(cx);
5393
5394 for selection in selections.iter() {
5395 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5396 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5397 if selection_start.buffer_id != selection_end.buffer_id {
5398 continue;
5399 }
5400 if let Some(ranges) =
5401 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5402 {
5403 for (buffer, entries) in ranges {
5404 linked_ranges.entry(buffer).or_default().extend(entries);
5405 }
5406 }
5407 }
5408 }
5409
5410 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5411 if !this.selections.line_mode {
5412 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5413 for selection in &mut selections {
5414 if selection.is_empty() {
5415 let old_head = selection.head();
5416 let mut new_head =
5417 movement::left(&display_map, old_head.to_display_point(&display_map))
5418 .to_point(&display_map);
5419 if let Some((buffer, line_buffer_range)) = display_map
5420 .buffer_snapshot
5421 .buffer_line_for_row(MultiBufferRow(old_head.row))
5422 {
5423 let indent_size =
5424 buffer.indent_size_for_line(line_buffer_range.start.row);
5425 let indent_len = match indent_size.kind {
5426 IndentKind::Space => {
5427 buffer.settings_at(line_buffer_range.start, cx).tab_size
5428 }
5429 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5430 };
5431 if old_head.column <= indent_size.len && old_head.column > 0 {
5432 let indent_len = indent_len.get();
5433 new_head = cmp::min(
5434 new_head,
5435 MultiBufferPoint::new(
5436 old_head.row,
5437 ((old_head.column - 1) / indent_len) * indent_len,
5438 ),
5439 );
5440 }
5441 }
5442
5443 selection.set_head(new_head, SelectionGoal::None);
5444 }
5445 }
5446 }
5447
5448 this.signature_help_state.set_backspace_pressed(true);
5449 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5450 this.insert("", cx);
5451 let empty_str: Arc<str> = Arc::from("");
5452 for (buffer, edits) in linked_ranges {
5453 let snapshot = buffer.read(cx).snapshot();
5454 use text::ToPoint as TP;
5455
5456 let edits = edits
5457 .into_iter()
5458 .map(|range| {
5459 let end_point = TP::to_point(&range.end, &snapshot);
5460 let mut start_point = TP::to_point(&range.start, &snapshot);
5461
5462 if end_point == start_point {
5463 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5464 .saturating_sub(1);
5465 start_point = TP::to_point(&offset, &snapshot);
5466 };
5467
5468 (start_point..end_point, empty_str.clone())
5469 })
5470 .sorted_by_key(|(range, _)| range.start)
5471 .collect::<Vec<_>>();
5472 buffer.update(cx, |this, cx| {
5473 this.edit(edits, None, cx);
5474 })
5475 }
5476 this.refresh_inline_completion(true, cx);
5477 linked_editing_ranges::refresh_linked_ranges(this, cx);
5478 });
5479 }
5480
5481 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5482 self.transact(cx, |this, cx| {
5483 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5484 let line_mode = s.line_mode;
5485 s.move_with(|map, selection| {
5486 if selection.is_empty() && !line_mode {
5487 let cursor = movement::right(map, selection.head());
5488 selection.end = cursor;
5489 selection.reversed = true;
5490 selection.goal = SelectionGoal::None;
5491 }
5492 })
5493 });
5494 this.insert("", cx);
5495 this.refresh_inline_completion(true, cx);
5496 });
5497 }
5498
5499 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5500 if self.move_to_prev_snippet_tabstop(cx) {
5501 return;
5502 }
5503
5504 self.outdent(&Outdent, cx);
5505 }
5506
5507 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5508 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5509 return;
5510 }
5511
5512 let mut selections = self.selections.all_adjusted(cx);
5513 let buffer = self.buffer.read(cx);
5514 let snapshot = buffer.snapshot(cx);
5515 let rows_iter = selections.iter().map(|s| s.head().row);
5516 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5517
5518 let mut edits = Vec::new();
5519 let mut prev_edited_row = 0;
5520 let mut row_delta = 0;
5521 for selection in &mut selections {
5522 if selection.start.row != prev_edited_row {
5523 row_delta = 0;
5524 }
5525 prev_edited_row = selection.end.row;
5526
5527 // If the selection is non-empty, then increase the indentation of the selected lines.
5528 if !selection.is_empty() {
5529 row_delta =
5530 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5531 continue;
5532 }
5533
5534 // If the selection is empty and the cursor is in the leading whitespace before the
5535 // suggested indentation, then auto-indent the line.
5536 let cursor = selection.head();
5537 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5538 if let Some(suggested_indent) =
5539 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5540 {
5541 if cursor.column < suggested_indent.len
5542 && cursor.column <= current_indent.len
5543 && current_indent.len <= suggested_indent.len
5544 {
5545 selection.start = Point::new(cursor.row, suggested_indent.len);
5546 selection.end = selection.start;
5547 if row_delta == 0 {
5548 edits.extend(Buffer::edit_for_indent_size_adjustment(
5549 cursor.row,
5550 current_indent,
5551 suggested_indent,
5552 ));
5553 row_delta = suggested_indent.len - current_indent.len;
5554 }
5555 continue;
5556 }
5557 }
5558
5559 // Otherwise, insert a hard or soft tab.
5560 let settings = buffer.settings_at(cursor, cx);
5561 let tab_size = if settings.hard_tabs {
5562 IndentSize::tab()
5563 } else {
5564 let tab_size = settings.tab_size.get();
5565 let char_column = snapshot
5566 .text_for_range(Point::new(cursor.row, 0)..cursor)
5567 .flat_map(str::chars)
5568 .count()
5569 + row_delta as usize;
5570 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5571 IndentSize::spaces(chars_to_next_tab_stop)
5572 };
5573 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5574 selection.end = selection.start;
5575 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5576 row_delta += tab_size.len;
5577 }
5578
5579 self.transact(cx, |this, cx| {
5580 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5581 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5582 this.refresh_inline_completion(true, cx);
5583 });
5584 }
5585
5586 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5587 if self.read_only(cx) {
5588 return;
5589 }
5590 let mut selections = self.selections.all::<Point>(cx);
5591 let mut prev_edited_row = 0;
5592 let mut row_delta = 0;
5593 let mut edits = Vec::new();
5594 let buffer = self.buffer.read(cx);
5595 let snapshot = buffer.snapshot(cx);
5596 for selection in &mut selections {
5597 if selection.start.row != prev_edited_row {
5598 row_delta = 0;
5599 }
5600 prev_edited_row = selection.end.row;
5601
5602 row_delta =
5603 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5604 }
5605
5606 self.transact(cx, |this, cx| {
5607 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5608 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5609 });
5610 }
5611
5612 fn indent_selection(
5613 buffer: &MultiBuffer,
5614 snapshot: &MultiBufferSnapshot,
5615 selection: &mut Selection<Point>,
5616 edits: &mut Vec<(Range<Point>, String)>,
5617 delta_for_start_row: u32,
5618 cx: &AppContext,
5619 ) -> u32 {
5620 let settings = buffer.settings_at(selection.start, cx);
5621 let tab_size = settings.tab_size.get();
5622 let indent_kind = if settings.hard_tabs {
5623 IndentKind::Tab
5624 } else {
5625 IndentKind::Space
5626 };
5627 let mut start_row = selection.start.row;
5628 let mut end_row = selection.end.row + 1;
5629
5630 // If a selection ends at the beginning of a line, don't indent
5631 // that last line.
5632 if selection.end.column == 0 && selection.end.row > selection.start.row {
5633 end_row -= 1;
5634 }
5635
5636 // Avoid re-indenting a row that has already been indented by a
5637 // previous selection, but still update this selection's column
5638 // to reflect that indentation.
5639 if delta_for_start_row > 0 {
5640 start_row += 1;
5641 selection.start.column += delta_for_start_row;
5642 if selection.end.row == selection.start.row {
5643 selection.end.column += delta_for_start_row;
5644 }
5645 }
5646
5647 let mut delta_for_end_row = 0;
5648 let has_multiple_rows = start_row + 1 != end_row;
5649 for row in start_row..end_row {
5650 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5651 let indent_delta = match (current_indent.kind, indent_kind) {
5652 (IndentKind::Space, IndentKind::Space) => {
5653 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5654 IndentSize::spaces(columns_to_next_tab_stop)
5655 }
5656 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5657 (_, IndentKind::Tab) => IndentSize::tab(),
5658 };
5659
5660 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5661 0
5662 } else {
5663 selection.start.column
5664 };
5665 let row_start = Point::new(row, start);
5666 edits.push((
5667 row_start..row_start,
5668 indent_delta.chars().collect::<String>(),
5669 ));
5670
5671 // Update this selection's endpoints to reflect the indentation.
5672 if row == selection.start.row {
5673 selection.start.column += indent_delta.len;
5674 }
5675 if row == selection.end.row {
5676 selection.end.column += indent_delta.len;
5677 delta_for_end_row = indent_delta.len;
5678 }
5679 }
5680
5681 if selection.start.row == selection.end.row {
5682 delta_for_start_row + delta_for_end_row
5683 } else {
5684 delta_for_end_row
5685 }
5686 }
5687
5688 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5689 if self.read_only(cx) {
5690 return;
5691 }
5692 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5693 let selections = self.selections.all::<Point>(cx);
5694 let mut deletion_ranges = Vec::new();
5695 let mut last_outdent = None;
5696 {
5697 let buffer = self.buffer.read(cx);
5698 let snapshot = buffer.snapshot(cx);
5699 for selection in &selections {
5700 let settings = buffer.settings_at(selection.start, cx);
5701 let tab_size = settings.tab_size.get();
5702 let mut rows = selection.spanned_rows(false, &display_map);
5703
5704 // Avoid re-outdenting a row that has already been outdented by a
5705 // previous selection.
5706 if let Some(last_row) = last_outdent {
5707 if last_row == rows.start {
5708 rows.start = rows.start.next_row();
5709 }
5710 }
5711 let has_multiple_rows = rows.len() > 1;
5712 for row in rows.iter_rows() {
5713 let indent_size = snapshot.indent_size_for_line(row);
5714 if indent_size.len > 0 {
5715 let deletion_len = match indent_size.kind {
5716 IndentKind::Space => {
5717 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5718 if columns_to_prev_tab_stop == 0 {
5719 tab_size
5720 } else {
5721 columns_to_prev_tab_stop
5722 }
5723 }
5724 IndentKind::Tab => 1,
5725 };
5726 let start = if has_multiple_rows
5727 || deletion_len > selection.start.column
5728 || indent_size.len < selection.start.column
5729 {
5730 0
5731 } else {
5732 selection.start.column - deletion_len
5733 };
5734 deletion_ranges.push(
5735 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5736 );
5737 last_outdent = Some(row);
5738 }
5739 }
5740 }
5741 }
5742
5743 self.transact(cx, |this, cx| {
5744 this.buffer.update(cx, |buffer, cx| {
5745 let empty_str: Arc<str> = "".into();
5746 buffer.edit(
5747 deletion_ranges
5748 .into_iter()
5749 .map(|range| (range, empty_str.clone())),
5750 None,
5751 cx,
5752 );
5753 });
5754 let selections = this.selections.all::<usize>(cx);
5755 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5756 });
5757 }
5758
5759 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5760 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5761 let selections = self.selections.all::<Point>(cx);
5762
5763 let mut new_cursors = Vec::new();
5764 let mut edit_ranges = Vec::new();
5765 let mut selections = selections.iter().peekable();
5766 while let Some(selection) = selections.next() {
5767 let mut rows = selection.spanned_rows(false, &display_map);
5768 let goal_display_column = selection.head().to_display_point(&display_map).column();
5769
5770 // Accumulate contiguous regions of rows that we want to delete.
5771 while let Some(next_selection) = selections.peek() {
5772 let next_rows = next_selection.spanned_rows(false, &display_map);
5773 if next_rows.start <= rows.end {
5774 rows.end = next_rows.end;
5775 selections.next().unwrap();
5776 } else {
5777 break;
5778 }
5779 }
5780
5781 let buffer = &display_map.buffer_snapshot;
5782 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5783 let edit_end;
5784 let cursor_buffer_row;
5785 if buffer.max_point().row >= rows.end.0 {
5786 // If there's a line after the range, delete the \n from the end of the row range
5787 // and position the cursor on the next line.
5788 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5789 cursor_buffer_row = rows.end;
5790 } else {
5791 // If there isn't a line after the range, delete the \n from the line before the
5792 // start of the row range and position the cursor there.
5793 edit_start = edit_start.saturating_sub(1);
5794 edit_end = buffer.len();
5795 cursor_buffer_row = rows.start.previous_row();
5796 }
5797
5798 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5799 *cursor.column_mut() =
5800 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5801
5802 new_cursors.push((
5803 selection.id,
5804 buffer.anchor_after(cursor.to_point(&display_map)),
5805 ));
5806 edit_ranges.push(edit_start..edit_end);
5807 }
5808
5809 self.transact(cx, |this, cx| {
5810 let buffer = this.buffer.update(cx, |buffer, cx| {
5811 let empty_str: Arc<str> = "".into();
5812 buffer.edit(
5813 edit_ranges
5814 .into_iter()
5815 .map(|range| (range, empty_str.clone())),
5816 None,
5817 cx,
5818 );
5819 buffer.snapshot(cx)
5820 });
5821 let new_selections = new_cursors
5822 .into_iter()
5823 .map(|(id, cursor)| {
5824 let cursor = cursor.to_point(&buffer);
5825 Selection {
5826 id,
5827 start: cursor,
5828 end: cursor,
5829 reversed: false,
5830 goal: SelectionGoal::None,
5831 }
5832 })
5833 .collect();
5834
5835 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5836 s.select(new_selections);
5837 });
5838 });
5839 }
5840
5841 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5842 if self.read_only(cx) {
5843 return;
5844 }
5845 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5846 for selection in self.selections.all::<Point>(cx) {
5847 let start = MultiBufferRow(selection.start.row);
5848 let end = if selection.start.row == selection.end.row {
5849 MultiBufferRow(selection.start.row + 1)
5850 } else {
5851 MultiBufferRow(selection.end.row)
5852 };
5853
5854 if let Some(last_row_range) = row_ranges.last_mut() {
5855 if start <= last_row_range.end {
5856 last_row_range.end = end;
5857 continue;
5858 }
5859 }
5860 row_ranges.push(start..end);
5861 }
5862
5863 let snapshot = self.buffer.read(cx).snapshot(cx);
5864 let mut cursor_positions = Vec::new();
5865 for row_range in &row_ranges {
5866 let anchor = snapshot.anchor_before(Point::new(
5867 row_range.end.previous_row().0,
5868 snapshot.line_len(row_range.end.previous_row()),
5869 ));
5870 cursor_positions.push(anchor..anchor);
5871 }
5872
5873 self.transact(cx, |this, cx| {
5874 for row_range in row_ranges.into_iter().rev() {
5875 for row in row_range.iter_rows().rev() {
5876 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5877 let next_line_row = row.next_row();
5878 let indent = snapshot.indent_size_for_line(next_line_row);
5879 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5880
5881 let replace = if snapshot.line_len(next_line_row) > indent.len {
5882 " "
5883 } else {
5884 ""
5885 };
5886
5887 this.buffer.update(cx, |buffer, cx| {
5888 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5889 });
5890 }
5891 }
5892
5893 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5894 s.select_anchor_ranges(cursor_positions)
5895 });
5896 });
5897 }
5898
5899 pub fn sort_lines_case_sensitive(
5900 &mut self,
5901 _: &SortLinesCaseSensitive,
5902 cx: &mut ViewContext<Self>,
5903 ) {
5904 self.manipulate_lines(cx, |lines| lines.sort())
5905 }
5906
5907 pub fn sort_lines_case_insensitive(
5908 &mut self,
5909 _: &SortLinesCaseInsensitive,
5910 cx: &mut ViewContext<Self>,
5911 ) {
5912 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5913 }
5914
5915 pub fn unique_lines_case_insensitive(
5916 &mut self,
5917 _: &UniqueLinesCaseInsensitive,
5918 cx: &mut ViewContext<Self>,
5919 ) {
5920 self.manipulate_lines(cx, |lines| {
5921 let mut seen = HashSet::default();
5922 lines.retain(|line| seen.insert(line.to_lowercase()));
5923 })
5924 }
5925
5926 pub fn unique_lines_case_sensitive(
5927 &mut self,
5928 _: &UniqueLinesCaseSensitive,
5929 cx: &mut ViewContext<Self>,
5930 ) {
5931 self.manipulate_lines(cx, |lines| {
5932 let mut seen = HashSet::default();
5933 lines.retain(|line| seen.insert(*line));
5934 })
5935 }
5936
5937 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
5938 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
5939 if !revert_changes.is_empty() {
5940 self.transact(cx, |editor, cx| {
5941 editor.revert(revert_changes, cx);
5942 });
5943 }
5944 }
5945
5946 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
5947 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
5948 let project_path = buffer.read(cx).project_path(cx)?;
5949 let project = self.project.as_ref()?.read(cx);
5950 let entry = project.entry_for_path(&project_path, cx)?;
5951 let abs_path = project.absolute_path(&project_path, cx)?;
5952 let parent = if entry.is_symlink {
5953 abs_path.canonicalize().ok()?
5954 } else {
5955 abs_path
5956 }
5957 .parent()?
5958 .to_path_buf();
5959 Some(parent)
5960 }) {
5961 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
5962 }
5963 }
5964
5965 fn gather_revert_changes(
5966 &mut self,
5967 selections: &[Selection<Anchor>],
5968 cx: &mut ViewContext<'_, Editor>,
5969 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
5970 let mut revert_changes = HashMap::default();
5971 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
5972 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
5973 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
5974 }
5975 revert_changes
5976 }
5977
5978 pub fn prepare_revert_change(
5979 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
5980 multi_buffer: &Model<MultiBuffer>,
5981 hunk: &DiffHunk<MultiBufferRow>,
5982 cx: &AppContext,
5983 ) -> Option<()> {
5984 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
5985 let buffer = buffer.read(cx);
5986 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
5987 let buffer_snapshot = buffer.snapshot();
5988 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
5989 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
5990 probe
5991 .0
5992 .start
5993 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
5994 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
5995 }) {
5996 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
5997 Some(())
5998 } else {
5999 None
6000 }
6001 }
6002
6003 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6004 self.manipulate_lines(cx, |lines| lines.reverse())
6005 }
6006
6007 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6008 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6009 }
6010
6011 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6012 where
6013 Fn: FnMut(&mut Vec<&str>),
6014 {
6015 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6016 let buffer = self.buffer.read(cx).snapshot(cx);
6017
6018 let mut edits = Vec::new();
6019
6020 let selections = self.selections.all::<Point>(cx);
6021 let mut selections = selections.iter().peekable();
6022 let mut contiguous_row_selections = Vec::new();
6023 let mut new_selections = Vec::new();
6024 let mut added_lines = 0;
6025 let mut removed_lines = 0;
6026
6027 while let Some(selection) = selections.next() {
6028 let (start_row, end_row) = consume_contiguous_rows(
6029 &mut contiguous_row_selections,
6030 selection,
6031 &display_map,
6032 &mut selections,
6033 );
6034
6035 let start_point = Point::new(start_row.0, 0);
6036 let end_point = Point::new(
6037 end_row.previous_row().0,
6038 buffer.line_len(end_row.previous_row()),
6039 );
6040 let text = buffer
6041 .text_for_range(start_point..end_point)
6042 .collect::<String>();
6043
6044 let mut lines = text.split('\n').collect_vec();
6045
6046 let lines_before = lines.len();
6047 callback(&mut lines);
6048 let lines_after = lines.len();
6049
6050 edits.push((start_point..end_point, lines.join("\n")));
6051
6052 // Selections must change based on added and removed line count
6053 let start_row =
6054 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6055 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6056 new_selections.push(Selection {
6057 id: selection.id,
6058 start: start_row,
6059 end: end_row,
6060 goal: SelectionGoal::None,
6061 reversed: selection.reversed,
6062 });
6063
6064 if lines_after > lines_before {
6065 added_lines += lines_after - lines_before;
6066 } else if lines_before > lines_after {
6067 removed_lines += lines_before - lines_after;
6068 }
6069 }
6070
6071 self.transact(cx, |this, cx| {
6072 let buffer = this.buffer.update(cx, |buffer, cx| {
6073 buffer.edit(edits, None, cx);
6074 buffer.snapshot(cx)
6075 });
6076
6077 // Recalculate offsets on newly edited buffer
6078 let new_selections = new_selections
6079 .iter()
6080 .map(|s| {
6081 let start_point = Point::new(s.start.0, 0);
6082 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6083 Selection {
6084 id: s.id,
6085 start: buffer.point_to_offset(start_point),
6086 end: buffer.point_to_offset(end_point),
6087 goal: s.goal,
6088 reversed: s.reversed,
6089 }
6090 })
6091 .collect();
6092
6093 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6094 s.select(new_selections);
6095 });
6096
6097 this.request_autoscroll(Autoscroll::fit(), cx);
6098 });
6099 }
6100
6101 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6102 self.manipulate_text(cx, |text| text.to_uppercase())
6103 }
6104
6105 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6106 self.manipulate_text(cx, |text| text.to_lowercase())
6107 }
6108
6109 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6110 self.manipulate_text(cx, |text| {
6111 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6112 // https://github.com/rutrum/convert-case/issues/16
6113 text.split('\n')
6114 .map(|line| line.to_case(Case::Title))
6115 .join("\n")
6116 })
6117 }
6118
6119 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6120 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6121 }
6122
6123 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6124 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6125 }
6126
6127 pub fn convert_to_upper_camel_case(
6128 &mut self,
6129 _: &ConvertToUpperCamelCase,
6130 cx: &mut ViewContext<Self>,
6131 ) {
6132 self.manipulate_text(cx, |text| {
6133 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6134 // https://github.com/rutrum/convert-case/issues/16
6135 text.split('\n')
6136 .map(|line| line.to_case(Case::UpperCamel))
6137 .join("\n")
6138 })
6139 }
6140
6141 pub fn convert_to_lower_camel_case(
6142 &mut self,
6143 _: &ConvertToLowerCamelCase,
6144 cx: &mut ViewContext<Self>,
6145 ) {
6146 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6147 }
6148
6149 pub fn convert_to_opposite_case(
6150 &mut self,
6151 _: &ConvertToOppositeCase,
6152 cx: &mut ViewContext<Self>,
6153 ) {
6154 self.manipulate_text(cx, |text| {
6155 text.chars()
6156 .fold(String::with_capacity(text.len()), |mut t, c| {
6157 if c.is_uppercase() {
6158 t.extend(c.to_lowercase());
6159 } else {
6160 t.extend(c.to_uppercase());
6161 }
6162 t
6163 })
6164 })
6165 }
6166
6167 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6168 where
6169 Fn: FnMut(&str) -> String,
6170 {
6171 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6172 let buffer = self.buffer.read(cx).snapshot(cx);
6173
6174 let mut new_selections = Vec::new();
6175 let mut edits = Vec::new();
6176 let mut selection_adjustment = 0i32;
6177
6178 for selection in self.selections.all::<usize>(cx) {
6179 let selection_is_empty = selection.is_empty();
6180
6181 let (start, end) = if selection_is_empty {
6182 let word_range = movement::surrounding_word(
6183 &display_map,
6184 selection.start.to_display_point(&display_map),
6185 );
6186 let start = word_range.start.to_offset(&display_map, Bias::Left);
6187 let end = word_range.end.to_offset(&display_map, Bias::Left);
6188 (start, end)
6189 } else {
6190 (selection.start, selection.end)
6191 };
6192
6193 let text = buffer.text_for_range(start..end).collect::<String>();
6194 let old_length = text.len() as i32;
6195 let text = callback(&text);
6196
6197 new_selections.push(Selection {
6198 start: (start as i32 - selection_adjustment) as usize,
6199 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6200 goal: SelectionGoal::None,
6201 ..selection
6202 });
6203
6204 selection_adjustment += old_length - text.len() as i32;
6205
6206 edits.push((start..end, text));
6207 }
6208
6209 self.transact(cx, |this, cx| {
6210 this.buffer.update(cx, |buffer, cx| {
6211 buffer.edit(edits, None, cx);
6212 });
6213
6214 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6215 s.select(new_selections);
6216 });
6217
6218 this.request_autoscroll(Autoscroll::fit(), cx);
6219 });
6220 }
6221
6222 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6223 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6224 let buffer = &display_map.buffer_snapshot;
6225 let selections = self.selections.all::<Point>(cx);
6226
6227 let mut edits = Vec::new();
6228 let mut selections_iter = selections.iter().peekable();
6229 while let Some(selection) = selections_iter.next() {
6230 // Avoid duplicating the same lines twice.
6231 let mut rows = selection.spanned_rows(false, &display_map);
6232
6233 while let Some(next_selection) = selections_iter.peek() {
6234 let next_rows = next_selection.spanned_rows(false, &display_map);
6235 if next_rows.start < rows.end {
6236 rows.end = next_rows.end;
6237 selections_iter.next().unwrap();
6238 } else {
6239 break;
6240 }
6241 }
6242
6243 // Copy the text from the selected row region and splice it either at the start
6244 // or end of the region.
6245 let start = Point::new(rows.start.0, 0);
6246 let end = Point::new(
6247 rows.end.previous_row().0,
6248 buffer.line_len(rows.end.previous_row()),
6249 );
6250 let text = buffer
6251 .text_for_range(start..end)
6252 .chain(Some("\n"))
6253 .collect::<String>();
6254 let insert_location = if upwards {
6255 Point::new(rows.end.0, 0)
6256 } else {
6257 start
6258 };
6259 edits.push((insert_location..insert_location, text));
6260 }
6261
6262 self.transact(cx, |this, cx| {
6263 this.buffer.update(cx, |buffer, cx| {
6264 buffer.edit(edits, None, cx);
6265 });
6266
6267 this.request_autoscroll(Autoscroll::fit(), cx);
6268 });
6269 }
6270
6271 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6272 self.duplicate_line(true, cx);
6273 }
6274
6275 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6276 self.duplicate_line(false, cx);
6277 }
6278
6279 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6280 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6281 let buffer = self.buffer.read(cx).snapshot(cx);
6282
6283 let mut edits = Vec::new();
6284 let mut unfold_ranges = Vec::new();
6285 let mut refold_ranges = Vec::new();
6286
6287 let selections = self.selections.all::<Point>(cx);
6288 let mut selections = selections.iter().peekable();
6289 let mut contiguous_row_selections = Vec::new();
6290 let mut new_selections = Vec::new();
6291
6292 while let Some(selection) = selections.next() {
6293 // Find all the selections that span a contiguous row range
6294 let (start_row, end_row) = consume_contiguous_rows(
6295 &mut contiguous_row_selections,
6296 selection,
6297 &display_map,
6298 &mut selections,
6299 );
6300
6301 // Move the text spanned by the row range to be before the line preceding the row range
6302 if start_row.0 > 0 {
6303 let range_to_move = Point::new(
6304 start_row.previous_row().0,
6305 buffer.line_len(start_row.previous_row()),
6306 )
6307 ..Point::new(
6308 end_row.previous_row().0,
6309 buffer.line_len(end_row.previous_row()),
6310 );
6311 let insertion_point = display_map
6312 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6313 .0;
6314
6315 // Don't move lines across excerpts
6316 if buffer
6317 .excerpt_boundaries_in_range((
6318 Bound::Excluded(insertion_point),
6319 Bound::Included(range_to_move.end),
6320 ))
6321 .next()
6322 .is_none()
6323 {
6324 let text = buffer
6325 .text_for_range(range_to_move.clone())
6326 .flat_map(|s| s.chars())
6327 .skip(1)
6328 .chain(['\n'])
6329 .collect::<String>();
6330
6331 edits.push((
6332 buffer.anchor_after(range_to_move.start)
6333 ..buffer.anchor_before(range_to_move.end),
6334 String::new(),
6335 ));
6336 let insertion_anchor = buffer.anchor_after(insertion_point);
6337 edits.push((insertion_anchor..insertion_anchor, text));
6338
6339 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6340
6341 // Move selections up
6342 new_selections.extend(contiguous_row_selections.drain(..).map(
6343 |mut selection| {
6344 selection.start.row -= row_delta;
6345 selection.end.row -= row_delta;
6346 selection
6347 },
6348 ));
6349
6350 // Move folds up
6351 unfold_ranges.push(range_to_move.clone());
6352 for fold in display_map.folds_in_range(
6353 buffer.anchor_before(range_to_move.start)
6354 ..buffer.anchor_after(range_to_move.end),
6355 ) {
6356 let mut start = fold.range.start.to_point(&buffer);
6357 let mut end = fold.range.end.to_point(&buffer);
6358 start.row -= row_delta;
6359 end.row -= row_delta;
6360 refold_ranges.push((start..end, fold.placeholder.clone()));
6361 }
6362 }
6363 }
6364
6365 // If we didn't move line(s), preserve the existing selections
6366 new_selections.append(&mut contiguous_row_selections);
6367 }
6368
6369 self.transact(cx, |this, cx| {
6370 this.unfold_ranges(unfold_ranges, true, true, cx);
6371 this.buffer.update(cx, |buffer, cx| {
6372 for (range, text) in edits {
6373 buffer.edit([(range, text)], None, cx);
6374 }
6375 });
6376 this.fold_ranges(refold_ranges, true, cx);
6377 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6378 s.select(new_selections);
6379 })
6380 });
6381 }
6382
6383 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6384 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6385 let buffer = self.buffer.read(cx).snapshot(cx);
6386
6387 let mut edits = Vec::new();
6388 let mut unfold_ranges = Vec::new();
6389 let mut refold_ranges = Vec::new();
6390
6391 let selections = self.selections.all::<Point>(cx);
6392 let mut selections = selections.iter().peekable();
6393 let mut contiguous_row_selections = Vec::new();
6394 let mut new_selections = Vec::new();
6395
6396 while let Some(selection) = selections.next() {
6397 // Find all the selections that span a contiguous row range
6398 let (start_row, end_row) = consume_contiguous_rows(
6399 &mut contiguous_row_selections,
6400 selection,
6401 &display_map,
6402 &mut selections,
6403 );
6404
6405 // Move the text spanned by the row range to be after the last line of the row range
6406 if end_row.0 <= buffer.max_point().row {
6407 let range_to_move =
6408 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6409 let insertion_point = display_map
6410 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6411 .0;
6412
6413 // Don't move lines across excerpt boundaries
6414 if buffer
6415 .excerpt_boundaries_in_range((
6416 Bound::Excluded(range_to_move.start),
6417 Bound::Included(insertion_point),
6418 ))
6419 .next()
6420 .is_none()
6421 {
6422 let mut text = String::from("\n");
6423 text.extend(buffer.text_for_range(range_to_move.clone()));
6424 text.pop(); // Drop trailing newline
6425 edits.push((
6426 buffer.anchor_after(range_to_move.start)
6427 ..buffer.anchor_before(range_to_move.end),
6428 String::new(),
6429 ));
6430 let insertion_anchor = buffer.anchor_after(insertion_point);
6431 edits.push((insertion_anchor..insertion_anchor, text));
6432
6433 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6434
6435 // Move selections down
6436 new_selections.extend(contiguous_row_selections.drain(..).map(
6437 |mut selection| {
6438 selection.start.row += row_delta;
6439 selection.end.row += row_delta;
6440 selection
6441 },
6442 ));
6443
6444 // Move folds down
6445 unfold_ranges.push(range_to_move.clone());
6446 for fold in display_map.folds_in_range(
6447 buffer.anchor_before(range_to_move.start)
6448 ..buffer.anchor_after(range_to_move.end),
6449 ) {
6450 let mut start = fold.range.start.to_point(&buffer);
6451 let mut end = fold.range.end.to_point(&buffer);
6452 start.row += row_delta;
6453 end.row += row_delta;
6454 refold_ranges.push((start..end, fold.placeholder.clone()));
6455 }
6456 }
6457 }
6458
6459 // If we didn't move line(s), preserve the existing selections
6460 new_selections.append(&mut contiguous_row_selections);
6461 }
6462
6463 self.transact(cx, |this, cx| {
6464 this.unfold_ranges(unfold_ranges, true, true, cx);
6465 this.buffer.update(cx, |buffer, cx| {
6466 for (range, text) in edits {
6467 buffer.edit([(range, text)], None, cx);
6468 }
6469 });
6470 this.fold_ranges(refold_ranges, true, cx);
6471 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6472 });
6473 }
6474
6475 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6476 let text_layout_details = &self.text_layout_details(cx);
6477 self.transact(cx, |this, cx| {
6478 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6479 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6480 let line_mode = s.line_mode;
6481 s.move_with(|display_map, selection| {
6482 if !selection.is_empty() || line_mode {
6483 return;
6484 }
6485
6486 let mut head = selection.head();
6487 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6488 if head.column() == display_map.line_len(head.row()) {
6489 transpose_offset = display_map
6490 .buffer_snapshot
6491 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6492 }
6493
6494 if transpose_offset == 0 {
6495 return;
6496 }
6497
6498 *head.column_mut() += 1;
6499 head = display_map.clip_point(head, Bias::Right);
6500 let goal = SelectionGoal::HorizontalPosition(
6501 display_map
6502 .x_for_display_point(head, &text_layout_details)
6503 .into(),
6504 );
6505 selection.collapse_to(head, goal);
6506
6507 let transpose_start = display_map
6508 .buffer_snapshot
6509 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6510 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6511 let transpose_end = display_map
6512 .buffer_snapshot
6513 .clip_offset(transpose_offset + 1, Bias::Right);
6514 if let Some(ch) =
6515 display_map.buffer_snapshot.chars_at(transpose_start).next()
6516 {
6517 edits.push((transpose_start..transpose_offset, String::new()));
6518 edits.push((transpose_end..transpose_end, ch.to_string()));
6519 }
6520 }
6521 });
6522 edits
6523 });
6524 this.buffer
6525 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6526 let selections = this.selections.all::<usize>(cx);
6527 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6528 s.select(selections);
6529 });
6530 });
6531 }
6532
6533 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6534 let mut text = String::new();
6535 let buffer = self.buffer.read(cx).snapshot(cx);
6536 let mut selections = self.selections.all::<Point>(cx);
6537 let mut clipboard_selections = Vec::with_capacity(selections.len());
6538 {
6539 let max_point = buffer.max_point();
6540 let mut is_first = true;
6541 for selection in &mut selections {
6542 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6543 if is_entire_line {
6544 selection.start = Point::new(selection.start.row, 0);
6545 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6546 selection.goal = SelectionGoal::None;
6547 }
6548 if is_first {
6549 is_first = false;
6550 } else {
6551 text += "\n";
6552 }
6553 let mut len = 0;
6554 for chunk in buffer.text_for_range(selection.start..selection.end) {
6555 text.push_str(chunk);
6556 len += chunk.len();
6557 }
6558 clipboard_selections.push(ClipboardSelection {
6559 len,
6560 is_entire_line,
6561 first_line_indent: buffer
6562 .indent_size_for_line(MultiBufferRow(selection.start.row))
6563 .len,
6564 });
6565 }
6566 }
6567
6568 self.transact(cx, |this, cx| {
6569 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6570 s.select(selections);
6571 });
6572 this.insert("", cx);
6573 cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
6574 });
6575 }
6576
6577 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6578 let selections = self.selections.all::<Point>(cx);
6579 let buffer = self.buffer.read(cx).read(cx);
6580 let mut text = String::new();
6581
6582 let mut clipboard_selections = Vec::with_capacity(selections.len());
6583 {
6584 let max_point = buffer.max_point();
6585 let mut is_first = true;
6586 for selection in selections.iter() {
6587 let mut start = selection.start;
6588 let mut end = selection.end;
6589 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6590 if is_entire_line {
6591 start = Point::new(start.row, 0);
6592 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6593 }
6594 if is_first {
6595 is_first = false;
6596 } else {
6597 text += "\n";
6598 }
6599 let mut len = 0;
6600 for chunk in buffer.text_for_range(start..end) {
6601 text.push_str(chunk);
6602 len += chunk.len();
6603 }
6604 clipboard_selections.push(ClipboardSelection {
6605 len,
6606 is_entire_line,
6607 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6608 });
6609 }
6610 }
6611
6612 cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
6613 }
6614
6615 pub fn do_paste(
6616 &mut self,
6617 text: &String,
6618 clipboard_selections: Option<Vec<ClipboardSelection>>,
6619 handle_entire_lines: bool,
6620 cx: &mut ViewContext<Self>,
6621 ) {
6622 if self.read_only(cx) {
6623 return;
6624 }
6625
6626 let clipboard_text = Cow::Borrowed(text);
6627
6628 self.transact(cx, |this, cx| {
6629 if let Some(mut clipboard_selections) = clipboard_selections {
6630 let old_selections = this.selections.all::<usize>(cx);
6631 let all_selections_were_entire_line =
6632 clipboard_selections.iter().all(|s| s.is_entire_line);
6633 let first_selection_indent_column =
6634 clipboard_selections.first().map(|s| s.first_line_indent);
6635 if clipboard_selections.len() != old_selections.len() {
6636 clipboard_selections.drain(..);
6637 }
6638
6639 this.buffer.update(cx, |buffer, cx| {
6640 let snapshot = buffer.read(cx);
6641 let mut start_offset = 0;
6642 let mut edits = Vec::new();
6643 let mut original_indent_columns = Vec::new();
6644 for (ix, selection) in old_selections.iter().enumerate() {
6645 let to_insert;
6646 let entire_line;
6647 let original_indent_column;
6648 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6649 let end_offset = start_offset + clipboard_selection.len;
6650 to_insert = &clipboard_text[start_offset..end_offset];
6651 entire_line = clipboard_selection.is_entire_line;
6652 start_offset = end_offset + 1;
6653 original_indent_column = Some(clipboard_selection.first_line_indent);
6654 } else {
6655 to_insert = clipboard_text.as_str();
6656 entire_line = all_selections_were_entire_line;
6657 original_indent_column = first_selection_indent_column
6658 }
6659
6660 // If the corresponding selection was empty when this slice of the
6661 // clipboard text was written, then the entire line containing the
6662 // selection was copied. If this selection is also currently empty,
6663 // then paste the line before the current line of the buffer.
6664 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6665 let column = selection.start.to_point(&snapshot).column as usize;
6666 let line_start = selection.start - column;
6667 line_start..line_start
6668 } else {
6669 selection.range()
6670 };
6671
6672 edits.push((range, to_insert));
6673 original_indent_columns.extend(original_indent_column);
6674 }
6675 drop(snapshot);
6676
6677 buffer.edit(
6678 edits,
6679 Some(AutoindentMode::Block {
6680 original_indent_columns,
6681 }),
6682 cx,
6683 );
6684 });
6685
6686 let selections = this.selections.all::<usize>(cx);
6687 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6688 } else {
6689 this.insert(&clipboard_text, cx);
6690 }
6691 });
6692 }
6693
6694 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
6695 if let Some(item) = cx.read_from_clipboard() {
6696 self.do_paste(
6697 item.text(),
6698 item.metadata::<Vec<ClipboardSelection>>(),
6699 true,
6700 cx,
6701 )
6702 };
6703 }
6704
6705 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
6706 if self.read_only(cx) {
6707 return;
6708 }
6709
6710 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
6711 if let Some((selections, _)) =
6712 self.selection_history.transaction(transaction_id).cloned()
6713 {
6714 self.change_selections(None, cx, |s| {
6715 s.select_anchors(selections.to_vec());
6716 });
6717 }
6718 self.request_autoscroll(Autoscroll::fit(), cx);
6719 self.unmark_text(cx);
6720 self.refresh_inline_completion(true, cx);
6721 cx.emit(EditorEvent::Edited { transaction_id });
6722 cx.emit(EditorEvent::TransactionUndone { transaction_id });
6723 }
6724 }
6725
6726 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
6727 if self.read_only(cx) {
6728 return;
6729 }
6730
6731 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
6732 if let Some((_, Some(selections))) =
6733 self.selection_history.transaction(transaction_id).cloned()
6734 {
6735 self.change_selections(None, cx, |s| {
6736 s.select_anchors(selections.to_vec());
6737 });
6738 }
6739 self.request_autoscroll(Autoscroll::fit(), cx);
6740 self.unmark_text(cx);
6741 self.refresh_inline_completion(true, cx);
6742 cx.emit(EditorEvent::Edited { transaction_id });
6743 }
6744 }
6745
6746 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
6747 self.buffer
6748 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
6749 }
6750
6751 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
6752 self.buffer
6753 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
6754 }
6755
6756 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
6757 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6758 let line_mode = s.line_mode;
6759 s.move_with(|map, selection| {
6760 let cursor = if selection.is_empty() && !line_mode {
6761 movement::left(map, selection.start)
6762 } else {
6763 selection.start
6764 };
6765 selection.collapse_to(cursor, SelectionGoal::None);
6766 });
6767 })
6768 }
6769
6770 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
6771 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6772 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
6773 })
6774 }
6775
6776 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
6777 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6778 let line_mode = s.line_mode;
6779 s.move_with(|map, selection| {
6780 let cursor = if selection.is_empty() && !line_mode {
6781 movement::right(map, selection.end)
6782 } else {
6783 selection.end
6784 };
6785 selection.collapse_to(cursor, SelectionGoal::None)
6786 });
6787 })
6788 }
6789
6790 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
6791 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6792 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
6793 })
6794 }
6795
6796 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
6797 if self.take_rename(true, cx).is_some() {
6798 return;
6799 }
6800
6801 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6802 cx.propagate();
6803 return;
6804 }
6805
6806 let text_layout_details = &self.text_layout_details(cx);
6807 let selection_count = self.selections.count();
6808 let first_selection = self.selections.first_anchor();
6809
6810 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6811 let line_mode = s.line_mode;
6812 s.move_with(|map, selection| {
6813 if !selection.is_empty() && !line_mode {
6814 selection.goal = SelectionGoal::None;
6815 }
6816 let (cursor, goal) = movement::up(
6817 map,
6818 selection.start,
6819 selection.goal,
6820 false,
6821 &text_layout_details,
6822 );
6823 selection.collapse_to(cursor, goal);
6824 });
6825 });
6826
6827 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
6828 {
6829 cx.propagate();
6830 }
6831 }
6832
6833 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
6834 if self.take_rename(true, cx).is_some() {
6835 return;
6836 }
6837
6838 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6839 cx.propagate();
6840 return;
6841 }
6842
6843 let text_layout_details = &self.text_layout_details(cx);
6844
6845 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6846 let line_mode = s.line_mode;
6847 s.move_with(|map, selection| {
6848 if !selection.is_empty() && !line_mode {
6849 selection.goal = SelectionGoal::None;
6850 }
6851 let (cursor, goal) = movement::up_by_rows(
6852 map,
6853 selection.start,
6854 action.lines,
6855 selection.goal,
6856 false,
6857 &text_layout_details,
6858 );
6859 selection.collapse_to(cursor, goal);
6860 });
6861 })
6862 }
6863
6864 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
6865 if self.take_rename(true, cx).is_some() {
6866 return;
6867 }
6868
6869 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6870 cx.propagate();
6871 return;
6872 }
6873
6874 let text_layout_details = &self.text_layout_details(cx);
6875
6876 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6877 let line_mode = s.line_mode;
6878 s.move_with(|map, selection| {
6879 if !selection.is_empty() && !line_mode {
6880 selection.goal = SelectionGoal::None;
6881 }
6882 let (cursor, goal) = movement::down_by_rows(
6883 map,
6884 selection.start,
6885 action.lines,
6886 selection.goal,
6887 false,
6888 &text_layout_details,
6889 );
6890 selection.collapse_to(cursor, goal);
6891 });
6892 })
6893 }
6894
6895 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
6896 let text_layout_details = &self.text_layout_details(cx);
6897 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6898 s.move_heads_with(|map, head, goal| {
6899 movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
6900 })
6901 })
6902 }
6903
6904 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
6905 let text_layout_details = &self.text_layout_details(cx);
6906 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6907 s.move_heads_with(|map, head, goal| {
6908 movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
6909 })
6910 })
6911 }
6912
6913 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
6914 let Some(row_count) = self.visible_row_count() else {
6915 return;
6916 };
6917
6918 let text_layout_details = &self.text_layout_details(cx);
6919
6920 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6921 s.move_heads_with(|map, head, goal| {
6922 movement::up_by_rows(map, head, row_count, goal, false, &text_layout_details)
6923 })
6924 })
6925 }
6926
6927 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
6928 if self.take_rename(true, cx).is_some() {
6929 return;
6930 }
6931
6932 if self
6933 .context_menu
6934 .write()
6935 .as_mut()
6936 .map(|menu| menu.select_first(self.project.as_ref(), cx))
6937 .unwrap_or(false)
6938 {
6939 return;
6940 }
6941
6942 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6943 cx.propagate();
6944 return;
6945 }
6946
6947 let Some(row_count) = self.visible_row_count() else {
6948 return;
6949 };
6950
6951 let autoscroll = if action.center_cursor {
6952 Autoscroll::center()
6953 } else {
6954 Autoscroll::fit()
6955 };
6956
6957 let text_layout_details = &self.text_layout_details(cx);
6958
6959 self.change_selections(Some(autoscroll), cx, |s| {
6960 let line_mode = s.line_mode;
6961 s.move_with(|map, selection| {
6962 if !selection.is_empty() && !line_mode {
6963 selection.goal = SelectionGoal::None;
6964 }
6965 let (cursor, goal) = movement::up_by_rows(
6966 map,
6967 selection.end,
6968 row_count,
6969 selection.goal,
6970 false,
6971 &text_layout_details,
6972 );
6973 selection.collapse_to(cursor, goal);
6974 });
6975 });
6976 }
6977
6978 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
6979 let text_layout_details = &self.text_layout_details(cx);
6980 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6981 s.move_heads_with(|map, head, goal| {
6982 movement::up(map, head, goal, false, &text_layout_details)
6983 })
6984 })
6985 }
6986
6987 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
6988 self.take_rename(true, cx);
6989
6990 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6991 cx.propagate();
6992 return;
6993 }
6994
6995 let text_layout_details = &self.text_layout_details(cx);
6996 let selection_count = self.selections.count();
6997 let first_selection = self.selections.first_anchor();
6998
6999 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7000 let line_mode = s.line_mode;
7001 s.move_with(|map, selection| {
7002 if !selection.is_empty() && !line_mode {
7003 selection.goal = SelectionGoal::None;
7004 }
7005 let (cursor, goal) = movement::down(
7006 map,
7007 selection.end,
7008 selection.goal,
7009 false,
7010 &text_layout_details,
7011 );
7012 selection.collapse_to(cursor, goal);
7013 });
7014 });
7015
7016 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7017 {
7018 cx.propagate();
7019 }
7020 }
7021
7022 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7023 let Some(row_count) = self.visible_row_count() else {
7024 return;
7025 };
7026
7027 let text_layout_details = &self.text_layout_details(cx);
7028
7029 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7030 s.move_heads_with(|map, head, goal| {
7031 movement::down_by_rows(map, head, row_count, goal, false, &text_layout_details)
7032 })
7033 })
7034 }
7035
7036 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7037 if self.take_rename(true, cx).is_some() {
7038 return;
7039 }
7040
7041 if self
7042 .context_menu
7043 .write()
7044 .as_mut()
7045 .map(|menu| menu.select_last(self.project.as_ref(), cx))
7046 .unwrap_or(false)
7047 {
7048 return;
7049 }
7050
7051 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7052 cx.propagate();
7053 return;
7054 }
7055
7056 let Some(row_count) = self.visible_row_count() else {
7057 return;
7058 };
7059
7060 let autoscroll = if action.center_cursor {
7061 Autoscroll::center()
7062 } else {
7063 Autoscroll::fit()
7064 };
7065
7066 let text_layout_details = &self.text_layout_details(cx);
7067 self.change_selections(Some(autoscroll), cx, |s| {
7068 let line_mode = s.line_mode;
7069 s.move_with(|map, selection| {
7070 if !selection.is_empty() && !line_mode {
7071 selection.goal = SelectionGoal::None;
7072 }
7073 let (cursor, goal) = movement::down_by_rows(
7074 map,
7075 selection.end,
7076 row_count,
7077 selection.goal,
7078 false,
7079 &text_layout_details,
7080 );
7081 selection.collapse_to(cursor, goal);
7082 });
7083 });
7084 }
7085
7086 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7087 let text_layout_details = &self.text_layout_details(cx);
7088 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7089 s.move_heads_with(|map, head, goal| {
7090 movement::down(map, head, goal, false, &text_layout_details)
7091 })
7092 });
7093 }
7094
7095 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7096 if let Some(context_menu) = self.context_menu.write().as_mut() {
7097 context_menu.select_first(self.project.as_ref(), cx);
7098 }
7099 }
7100
7101 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7102 if let Some(context_menu) = self.context_menu.write().as_mut() {
7103 context_menu.select_prev(self.project.as_ref(), cx);
7104 }
7105 }
7106
7107 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7108 if let Some(context_menu) = self.context_menu.write().as_mut() {
7109 context_menu.select_next(self.project.as_ref(), cx);
7110 }
7111 }
7112
7113 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7114 if let Some(context_menu) = self.context_menu.write().as_mut() {
7115 context_menu.select_last(self.project.as_ref(), cx);
7116 }
7117 }
7118
7119 pub fn move_to_previous_word_start(
7120 &mut self,
7121 _: &MoveToPreviousWordStart,
7122 cx: &mut ViewContext<Self>,
7123 ) {
7124 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7125 s.move_cursors_with(|map, head, _| {
7126 (
7127 movement::previous_word_start(map, head),
7128 SelectionGoal::None,
7129 )
7130 });
7131 })
7132 }
7133
7134 pub fn move_to_previous_subword_start(
7135 &mut self,
7136 _: &MoveToPreviousSubwordStart,
7137 cx: &mut ViewContext<Self>,
7138 ) {
7139 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7140 s.move_cursors_with(|map, head, _| {
7141 (
7142 movement::previous_subword_start(map, head),
7143 SelectionGoal::None,
7144 )
7145 });
7146 })
7147 }
7148
7149 pub fn select_to_previous_word_start(
7150 &mut self,
7151 _: &SelectToPreviousWordStart,
7152 cx: &mut ViewContext<Self>,
7153 ) {
7154 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7155 s.move_heads_with(|map, head, _| {
7156 (
7157 movement::previous_word_start(map, head),
7158 SelectionGoal::None,
7159 )
7160 });
7161 })
7162 }
7163
7164 pub fn select_to_previous_subword_start(
7165 &mut self,
7166 _: &SelectToPreviousSubwordStart,
7167 cx: &mut ViewContext<Self>,
7168 ) {
7169 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7170 s.move_heads_with(|map, head, _| {
7171 (
7172 movement::previous_subword_start(map, head),
7173 SelectionGoal::None,
7174 )
7175 });
7176 })
7177 }
7178
7179 pub fn delete_to_previous_word_start(
7180 &mut self,
7181 _: &DeleteToPreviousWordStart,
7182 cx: &mut ViewContext<Self>,
7183 ) {
7184 self.transact(cx, |this, cx| {
7185 this.select_autoclose_pair(cx);
7186 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7187 let line_mode = s.line_mode;
7188 s.move_with(|map, selection| {
7189 if selection.is_empty() && !line_mode {
7190 let cursor = movement::previous_word_start(map, selection.head());
7191 selection.set_head(cursor, SelectionGoal::None);
7192 }
7193 });
7194 });
7195 this.insert("", cx);
7196 });
7197 }
7198
7199 pub fn delete_to_previous_subword_start(
7200 &mut self,
7201 _: &DeleteToPreviousSubwordStart,
7202 cx: &mut ViewContext<Self>,
7203 ) {
7204 self.transact(cx, |this, cx| {
7205 this.select_autoclose_pair(cx);
7206 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7207 let line_mode = s.line_mode;
7208 s.move_with(|map, selection| {
7209 if selection.is_empty() && !line_mode {
7210 let cursor = movement::previous_subword_start(map, selection.head());
7211 selection.set_head(cursor, SelectionGoal::None);
7212 }
7213 });
7214 });
7215 this.insert("", cx);
7216 });
7217 }
7218
7219 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7220 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7221 s.move_cursors_with(|map, head, _| {
7222 (movement::next_word_end(map, head), SelectionGoal::None)
7223 });
7224 })
7225 }
7226
7227 pub fn move_to_next_subword_end(
7228 &mut self,
7229 _: &MoveToNextSubwordEnd,
7230 cx: &mut ViewContext<Self>,
7231 ) {
7232 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7233 s.move_cursors_with(|map, head, _| {
7234 (movement::next_subword_end(map, head), SelectionGoal::None)
7235 });
7236 })
7237 }
7238
7239 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7240 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7241 s.move_heads_with(|map, head, _| {
7242 (movement::next_word_end(map, head), SelectionGoal::None)
7243 });
7244 })
7245 }
7246
7247 pub fn select_to_next_subword_end(
7248 &mut self,
7249 _: &SelectToNextSubwordEnd,
7250 cx: &mut ViewContext<Self>,
7251 ) {
7252 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7253 s.move_heads_with(|map, head, _| {
7254 (movement::next_subword_end(map, head), SelectionGoal::None)
7255 });
7256 })
7257 }
7258
7259 pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
7260 self.transact(cx, |this, cx| {
7261 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7262 let line_mode = s.line_mode;
7263 s.move_with(|map, selection| {
7264 if selection.is_empty() && !line_mode {
7265 let cursor = movement::next_word_end(map, selection.head());
7266 selection.set_head(cursor, SelectionGoal::None);
7267 }
7268 });
7269 });
7270 this.insert("", cx);
7271 });
7272 }
7273
7274 pub fn delete_to_next_subword_end(
7275 &mut self,
7276 _: &DeleteToNextSubwordEnd,
7277 cx: &mut ViewContext<Self>,
7278 ) {
7279 self.transact(cx, |this, cx| {
7280 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7281 s.move_with(|map, selection| {
7282 if selection.is_empty() {
7283 let cursor = movement::next_subword_end(map, selection.head());
7284 selection.set_head(cursor, SelectionGoal::None);
7285 }
7286 });
7287 });
7288 this.insert("", cx);
7289 });
7290 }
7291
7292 pub fn move_to_beginning_of_line(
7293 &mut self,
7294 action: &MoveToBeginningOfLine,
7295 cx: &mut ViewContext<Self>,
7296 ) {
7297 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7298 s.move_cursors_with(|map, head, _| {
7299 (
7300 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7301 SelectionGoal::None,
7302 )
7303 });
7304 })
7305 }
7306
7307 pub fn select_to_beginning_of_line(
7308 &mut self,
7309 action: &SelectToBeginningOfLine,
7310 cx: &mut ViewContext<Self>,
7311 ) {
7312 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7313 s.move_heads_with(|map, head, _| {
7314 (
7315 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7316 SelectionGoal::None,
7317 )
7318 });
7319 });
7320 }
7321
7322 pub fn delete_to_beginning_of_line(
7323 &mut self,
7324 _: &DeleteToBeginningOfLine,
7325 cx: &mut ViewContext<Self>,
7326 ) {
7327 self.transact(cx, |this, cx| {
7328 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7329 s.move_with(|_, selection| {
7330 selection.reversed = true;
7331 });
7332 });
7333
7334 this.select_to_beginning_of_line(
7335 &SelectToBeginningOfLine {
7336 stop_at_soft_wraps: false,
7337 },
7338 cx,
7339 );
7340 this.backspace(&Backspace, cx);
7341 });
7342 }
7343
7344 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7345 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7346 s.move_cursors_with(|map, head, _| {
7347 (
7348 movement::line_end(map, head, action.stop_at_soft_wraps),
7349 SelectionGoal::None,
7350 )
7351 });
7352 })
7353 }
7354
7355 pub fn select_to_end_of_line(
7356 &mut self,
7357 action: &SelectToEndOfLine,
7358 cx: &mut ViewContext<Self>,
7359 ) {
7360 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7361 s.move_heads_with(|map, head, _| {
7362 (
7363 movement::line_end(map, head, action.stop_at_soft_wraps),
7364 SelectionGoal::None,
7365 )
7366 });
7367 })
7368 }
7369
7370 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7371 self.transact(cx, |this, cx| {
7372 this.select_to_end_of_line(
7373 &SelectToEndOfLine {
7374 stop_at_soft_wraps: false,
7375 },
7376 cx,
7377 );
7378 this.delete(&Delete, cx);
7379 });
7380 }
7381
7382 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7383 self.transact(cx, |this, cx| {
7384 this.select_to_end_of_line(
7385 &SelectToEndOfLine {
7386 stop_at_soft_wraps: false,
7387 },
7388 cx,
7389 );
7390 this.cut(&Cut, cx);
7391 });
7392 }
7393
7394 pub fn move_to_start_of_paragraph(
7395 &mut self,
7396 _: &MoveToStartOfParagraph,
7397 cx: &mut ViewContext<Self>,
7398 ) {
7399 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7400 cx.propagate();
7401 return;
7402 }
7403
7404 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7405 s.move_with(|map, selection| {
7406 selection.collapse_to(
7407 movement::start_of_paragraph(map, selection.head(), 1),
7408 SelectionGoal::None,
7409 )
7410 });
7411 })
7412 }
7413
7414 pub fn move_to_end_of_paragraph(
7415 &mut self,
7416 _: &MoveToEndOfParagraph,
7417 cx: &mut ViewContext<Self>,
7418 ) {
7419 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7420 cx.propagate();
7421 return;
7422 }
7423
7424 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7425 s.move_with(|map, selection| {
7426 selection.collapse_to(
7427 movement::end_of_paragraph(map, selection.head(), 1),
7428 SelectionGoal::None,
7429 )
7430 });
7431 })
7432 }
7433
7434 pub fn select_to_start_of_paragraph(
7435 &mut self,
7436 _: &SelectToStartOfParagraph,
7437 cx: &mut ViewContext<Self>,
7438 ) {
7439 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7440 cx.propagate();
7441 return;
7442 }
7443
7444 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7445 s.move_heads_with(|map, head, _| {
7446 (
7447 movement::start_of_paragraph(map, head, 1),
7448 SelectionGoal::None,
7449 )
7450 });
7451 })
7452 }
7453
7454 pub fn select_to_end_of_paragraph(
7455 &mut self,
7456 _: &SelectToEndOfParagraph,
7457 cx: &mut ViewContext<Self>,
7458 ) {
7459 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7460 cx.propagate();
7461 return;
7462 }
7463
7464 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7465 s.move_heads_with(|map, head, _| {
7466 (
7467 movement::end_of_paragraph(map, head, 1),
7468 SelectionGoal::None,
7469 )
7470 });
7471 })
7472 }
7473
7474 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7475 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7476 cx.propagate();
7477 return;
7478 }
7479
7480 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7481 s.select_ranges(vec![0..0]);
7482 });
7483 }
7484
7485 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7486 let mut selection = self.selections.last::<Point>(cx);
7487 selection.set_head(Point::zero(), SelectionGoal::None);
7488
7489 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7490 s.select(vec![selection]);
7491 });
7492 }
7493
7494 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7495 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7496 cx.propagate();
7497 return;
7498 }
7499
7500 let cursor = self.buffer.read(cx).read(cx).len();
7501 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7502 s.select_ranges(vec![cursor..cursor])
7503 });
7504 }
7505
7506 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7507 self.nav_history = nav_history;
7508 }
7509
7510 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7511 self.nav_history.as_ref()
7512 }
7513
7514 fn push_to_nav_history(
7515 &mut self,
7516 cursor_anchor: Anchor,
7517 new_position: Option<Point>,
7518 cx: &mut ViewContext<Self>,
7519 ) {
7520 if let Some(nav_history) = self.nav_history.as_mut() {
7521 let buffer = self.buffer.read(cx).read(cx);
7522 let cursor_position = cursor_anchor.to_point(&buffer);
7523 let scroll_state = self.scroll_manager.anchor();
7524 let scroll_top_row = scroll_state.top_row(&buffer);
7525 drop(buffer);
7526
7527 if let Some(new_position) = new_position {
7528 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7529 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7530 return;
7531 }
7532 }
7533
7534 nav_history.push(
7535 Some(NavigationData {
7536 cursor_anchor,
7537 cursor_position,
7538 scroll_anchor: scroll_state,
7539 scroll_top_row,
7540 }),
7541 cx,
7542 );
7543 }
7544 }
7545
7546 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7547 let buffer = self.buffer.read(cx).snapshot(cx);
7548 let mut selection = self.selections.first::<usize>(cx);
7549 selection.set_head(buffer.len(), SelectionGoal::None);
7550 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7551 s.select(vec![selection]);
7552 });
7553 }
7554
7555 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7556 let end = self.buffer.read(cx).read(cx).len();
7557 self.change_selections(None, cx, |s| {
7558 s.select_ranges(vec![0..end]);
7559 });
7560 }
7561
7562 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7563 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7564 let mut selections = self.selections.all::<Point>(cx);
7565 let max_point = display_map.buffer_snapshot.max_point();
7566 for selection in &mut selections {
7567 let rows = selection.spanned_rows(true, &display_map);
7568 selection.start = Point::new(rows.start.0, 0);
7569 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7570 selection.reversed = false;
7571 }
7572 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7573 s.select(selections);
7574 });
7575 }
7576
7577 pub fn split_selection_into_lines(
7578 &mut self,
7579 _: &SplitSelectionIntoLines,
7580 cx: &mut ViewContext<Self>,
7581 ) {
7582 let mut to_unfold = Vec::new();
7583 let mut new_selection_ranges = Vec::new();
7584 {
7585 let selections = self.selections.all::<Point>(cx);
7586 let buffer = self.buffer.read(cx).read(cx);
7587 for selection in selections {
7588 for row in selection.start.row..selection.end.row {
7589 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7590 new_selection_ranges.push(cursor..cursor);
7591 }
7592 new_selection_ranges.push(selection.end..selection.end);
7593 to_unfold.push(selection.start..selection.end);
7594 }
7595 }
7596 self.unfold_ranges(to_unfold, true, true, cx);
7597 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7598 s.select_ranges(new_selection_ranges);
7599 });
7600 }
7601
7602 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7603 self.add_selection(true, cx);
7604 }
7605
7606 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7607 self.add_selection(false, cx);
7608 }
7609
7610 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7611 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7612 let mut selections = self.selections.all::<Point>(cx);
7613 let text_layout_details = self.text_layout_details(cx);
7614 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7615 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7616 let range = oldest_selection.display_range(&display_map).sorted();
7617
7618 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7619 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7620 let positions = start_x.min(end_x)..start_x.max(end_x);
7621
7622 selections.clear();
7623 let mut stack = Vec::new();
7624 for row in range.start.row().0..=range.end.row().0 {
7625 if let Some(selection) = self.selections.build_columnar_selection(
7626 &display_map,
7627 DisplayRow(row),
7628 &positions,
7629 oldest_selection.reversed,
7630 &text_layout_details,
7631 ) {
7632 stack.push(selection.id);
7633 selections.push(selection);
7634 }
7635 }
7636
7637 if above {
7638 stack.reverse();
7639 }
7640
7641 AddSelectionsState { above, stack }
7642 });
7643
7644 let last_added_selection = *state.stack.last().unwrap();
7645 let mut new_selections = Vec::new();
7646 if above == state.above {
7647 let end_row = if above {
7648 DisplayRow(0)
7649 } else {
7650 display_map.max_point().row()
7651 };
7652
7653 'outer: for selection in selections {
7654 if selection.id == last_added_selection {
7655 let range = selection.display_range(&display_map).sorted();
7656 debug_assert_eq!(range.start.row(), range.end.row());
7657 let mut row = range.start.row();
7658 let positions =
7659 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7660 px(start)..px(end)
7661 } else {
7662 let start_x =
7663 display_map.x_for_display_point(range.start, &text_layout_details);
7664 let end_x =
7665 display_map.x_for_display_point(range.end, &text_layout_details);
7666 start_x.min(end_x)..start_x.max(end_x)
7667 };
7668
7669 while row != end_row {
7670 if above {
7671 row.0 -= 1;
7672 } else {
7673 row.0 += 1;
7674 }
7675
7676 if let Some(new_selection) = self.selections.build_columnar_selection(
7677 &display_map,
7678 row,
7679 &positions,
7680 selection.reversed,
7681 &text_layout_details,
7682 ) {
7683 state.stack.push(new_selection.id);
7684 if above {
7685 new_selections.push(new_selection);
7686 new_selections.push(selection);
7687 } else {
7688 new_selections.push(selection);
7689 new_selections.push(new_selection);
7690 }
7691
7692 continue 'outer;
7693 }
7694 }
7695 }
7696
7697 new_selections.push(selection);
7698 }
7699 } else {
7700 new_selections = selections;
7701 new_selections.retain(|s| s.id != last_added_selection);
7702 state.stack.pop();
7703 }
7704
7705 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7706 s.select(new_selections);
7707 });
7708 if state.stack.len() > 1 {
7709 self.add_selections_state = Some(state);
7710 }
7711 }
7712
7713 pub fn select_next_match_internal(
7714 &mut self,
7715 display_map: &DisplaySnapshot,
7716 replace_newest: bool,
7717 autoscroll: Option<Autoscroll>,
7718 cx: &mut ViewContext<Self>,
7719 ) -> Result<()> {
7720 fn select_next_match_ranges(
7721 this: &mut Editor,
7722 range: Range<usize>,
7723 replace_newest: bool,
7724 auto_scroll: Option<Autoscroll>,
7725 cx: &mut ViewContext<Editor>,
7726 ) {
7727 this.unfold_ranges([range.clone()], false, true, cx);
7728 this.change_selections(auto_scroll, cx, |s| {
7729 if replace_newest {
7730 s.delete(s.newest_anchor().id);
7731 }
7732 s.insert_range(range.clone());
7733 });
7734 }
7735
7736 let buffer = &display_map.buffer_snapshot;
7737 let mut selections = self.selections.all::<usize>(cx);
7738 if let Some(mut select_next_state) = self.select_next_state.take() {
7739 let query = &select_next_state.query;
7740 if !select_next_state.done {
7741 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7742 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7743 let mut next_selected_range = None;
7744
7745 let bytes_after_last_selection =
7746 buffer.bytes_in_range(last_selection.end..buffer.len());
7747 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
7748 let query_matches = query
7749 .stream_find_iter(bytes_after_last_selection)
7750 .map(|result| (last_selection.end, result))
7751 .chain(
7752 query
7753 .stream_find_iter(bytes_before_first_selection)
7754 .map(|result| (0, result)),
7755 );
7756
7757 for (start_offset, query_match) in query_matches {
7758 let query_match = query_match.unwrap(); // can only fail due to I/O
7759 let offset_range =
7760 start_offset + query_match.start()..start_offset + query_match.end();
7761 let display_range = offset_range.start.to_display_point(&display_map)
7762 ..offset_range.end.to_display_point(&display_map);
7763
7764 if !select_next_state.wordwise
7765 || (!movement::is_inside_word(&display_map, display_range.start)
7766 && !movement::is_inside_word(&display_map, display_range.end))
7767 {
7768 // TODO: This is n^2, because we might check all the selections
7769 if !selections
7770 .iter()
7771 .any(|selection| selection.range().overlaps(&offset_range))
7772 {
7773 next_selected_range = Some(offset_range);
7774 break;
7775 }
7776 }
7777 }
7778
7779 if let Some(next_selected_range) = next_selected_range {
7780 select_next_match_ranges(
7781 self,
7782 next_selected_range,
7783 replace_newest,
7784 autoscroll,
7785 cx,
7786 );
7787 } else {
7788 select_next_state.done = true;
7789 }
7790 }
7791
7792 self.select_next_state = Some(select_next_state);
7793 } else {
7794 let mut only_carets = true;
7795 let mut same_text_selected = true;
7796 let mut selected_text = None;
7797
7798 let mut selections_iter = selections.iter().peekable();
7799 while let Some(selection) = selections_iter.next() {
7800 if selection.start != selection.end {
7801 only_carets = false;
7802 }
7803
7804 if same_text_selected {
7805 if selected_text.is_none() {
7806 selected_text =
7807 Some(buffer.text_for_range(selection.range()).collect::<String>());
7808 }
7809
7810 if let Some(next_selection) = selections_iter.peek() {
7811 if next_selection.range().len() == selection.range().len() {
7812 let next_selected_text = buffer
7813 .text_for_range(next_selection.range())
7814 .collect::<String>();
7815 if Some(next_selected_text) != selected_text {
7816 same_text_selected = false;
7817 selected_text = None;
7818 }
7819 } else {
7820 same_text_selected = false;
7821 selected_text = None;
7822 }
7823 }
7824 }
7825 }
7826
7827 if only_carets {
7828 for selection in &mut selections {
7829 let word_range = movement::surrounding_word(
7830 &display_map,
7831 selection.start.to_display_point(&display_map),
7832 );
7833 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
7834 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
7835 selection.goal = SelectionGoal::None;
7836 selection.reversed = false;
7837 select_next_match_ranges(
7838 self,
7839 selection.start..selection.end,
7840 replace_newest,
7841 autoscroll,
7842 cx,
7843 );
7844 }
7845
7846 if selections.len() == 1 {
7847 let selection = selections
7848 .last()
7849 .expect("ensured that there's only one selection");
7850 let query = buffer
7851 .text_for_range(selection.start..selection.end)
7852 .collect::<String>();
7853 let is_empty = query.is_empty();
7854 let select_state = SelectNextState {
7855 query: AhoCorasick::new(&[query])?,
7856 wordwise: true,
7857 done: is_empty,
7858 };
7859 self.select_next_state = Some(select_state);
7860 } else {
7861 self.select_next_state = None;
7862 }
7863 } else if let Some(selected_text) = selected_text {
7864 self.select_next_state = Some(SelectNextState {
7865 query: AhoCorasick::new(&[selected_text])?,
7866 wordwise: false,
7867 done: false,
7868 });
7869 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
7870 }
7871 }
7872 Ok(())
7873 }
7874
7875 pub fn select_all_matches(
7876 &mut self,
7877 _action: &SelectAllMatches,
7878 cx: &mut ViewContext<Self>,
7879 ) -> Result<()> {
7880 self.push_to_selection_history();
7881 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7882
7883 self.select_next_match_internal(&display_map, false, None, cx)?;
7884 let Some(select_next_state) = self.select_next_state.as_mut() else {
7885 return Ok(());
7886 };
7887 if select_next_state.done {
7888 return Ok(());
7889 }
7890
7891 let mut new_selections = self.selections.all::<usize>(cx);
7892
7893 let buffer = &display_map.buffer_snapshot;
7894 let query_matches = select_next_state
7895 .query
7896 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
7897
7898 for query_match in query_matches {
7899 let query_match = query_match.unwrap(); // can only fail due to I/O
7900 let offset_range = query_match.start()..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 self.selections.change_with(cx, |selections| {
7909 new_selections.push(Selection {
7910 id: selections.new_selection_id(),
7911 start: offset_range.start,
7912 end: offset_range.end,
7913 reversed: false,
7914 goal: SelectionGoal::None,
7915 });
7916 });
7917 }
7918 }
7919
7920 new_selections.sort_by_key(|selection| selection.start);
7921 let mut ix = 0;
7922 while ix + 1 < new_selections.len() {
7923 let current_selection = &new_selections[ix];
7924 let next_selection = &new_selections[ix + 1];
7925 if current_selection.range().overlaps(&next_selection.range()) {
7926 if current_selection.id < next_selection.id {
7927 new_selections.remove(ix + 1);
7928 } else {
7929 new_selections.remove(ix);
7930 }
7931 } else {
7932 ix += 1;
7933 }
7934 }
7935
7936 select_next_state.done = true;
7937 self.unfold_ranges(
7938 new_selections.iter().map(|selection| selection.range()),
7939 false,
7940 false,
7941 cx,
7942 );
7943 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
7944 selections.select(new_selections)
7945 });
7946
7947 Ok(())
7948 }
7949
7950 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
7951 self.push_to_selection_history();
7952 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7953 self.select_next_match_internal(
7954 &display_map,
7955 action.replace_newest,
7956 Some(Autoscroll::newest()),
7957 cx,
7958 )?;
7959 Ok(())
7960 }
7961
7962 pub fn select_previous(
7963 &mut self,
7964 action: &SelectPrevious,
7965 cx: &mut ViewContext<Self>,
7966 ) -> Result<()> {
7967 self.push_to_selection_history();
7968 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7969 let buffer = &display_map.buffer_snapshot;
7970 let mut selections = self.selections.all::<usize>(cx);
7971 if let Some(mut select_prev_state) = self.select_prev_state.take() {
7972 let query = &select_prev_state.query;
7973 if !select_prev_state.done {
7974 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7975 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7976 let mut next_selected_range = None;
7977 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
7978 let bytes_before_last_selection =
7979 buffer.reversed_bytes_in_range(0..last_selection.start);
7980 let bytes_after_first_selection =
7981 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
7982 let query_matches = query
7983 .stream_find_iter(bytes_before_last_selection)
7984 .map(|result| (last_selection.start, result))
7985 .chain(
7986 query
7987 .stream_find_iter(bytes_after_first_selection)
7988 .map(|result| (buffer.len(), result)),
7989 );
7990 for (end_offset, query_match) in query_matches {
7991 let query_match = query_match.unwrap(); // can only fail due to I/O
7992 let offset_range =
7993 end_offset - query_match.end()..end_offset - query_match.start();
7994 let display_range = offset_range.start.to_display_point(&display_map)
7995 ..offset_range.end.to_display_point(&display_map);
7996
7997 if !select_prev_state.wordwise
7998 || (!movement::is_inside_word(&display_map, display_range.start)
7999 && !movement::is_inside_word(&display_map, display_range.end))
8000 {
8001 next_selected_range = Some(offset_range);
8002 break;
8003 }
8004 }
8005
8006 if let Some(next_selected_range) = next_selected_range {
8007 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8008 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8009 if action.replace_newest {
8010 s.delete(s.newest_anchor().id);
8011 }
8012 s.insert_range(next_selected_range);
8013 });
8014 } else {
8015 select_prev_state.done = true;
8016 }
8017 }
8018
8019 self.select_prev_state = Some(select_prev_state);
8020 } else {
8021 let mut only_carets = true;
8022 let mut same_text_selected = true;
8023 let mut selected_text = None;
8024
8025 let mut selections_iter = selections.iter().peekable();
8026 while let Some(selection) = selections_iter.next() {
8027 if selection.start != selection.end {
8028 only_carets = false;
8029 }
8030
8031 if same_text_selected {
8032 if selected_text.is_none() {
8033 selected_text =
8034 Some(buffer.text_for_range(selection.range()).collect::<String>());
8035 }
8036
8037 if let Some(next_selection) = selections_iter.peek() {
8038 if next_selection.range().len() == selection.range().len() {
8039 let next_selected_text = buffer
8040 .text_for_range(next_selection.range())
8041 .collect::<String>();
8042 if Some(next_selected_text) != selected_text {
8043 same_text_selected = false;
8044 selected_text = None;
8045 }
8046 } else {
8047 same_text_selected = false;
8048 selected_text = None;
8049 }
8050 }
8051 }
8052 }
8053
8054 if only_carets {
8055 for selection in &mut selections {
8056 let word_range = movement::surrounding_word(
8057 &display_map,
8058 selection.start.to_display_point(&display_map),
8059 );
8060 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8061 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8062 selection.goal = SelectionGoal::None;
8063 selection.reversed = false;
8064 }
8065 if selections.len() == 1 {
8066 let selection = selections
8067 .last()
8068 .expect("ensured that there's only one selection");
8069 let query = buffer
8070 .text_for_range(selection.start..selection.end)
8071 .collect::<String>();
8072 let is_empty = query.is_empty();
8073 let select_state = SelectNextState {
8074 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8075 wordwise: true,
8076 done: is_empty,
8077 };
8078 self.select_prev_state = Some(select_state);
8079 } else {
8080 self.select_prev_state = None;
8081 }
8082
8083 self.unfold_ranges(
8084 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8085 false,
8086 true,
8087 cx,
8088 );
8089 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8090 s.select(selections);
8091 });
8092 } else if let Some(selected_text) = selected_text {
8093 self.select_prev_state = Some(SelectNextState {
8094 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8095 wordwise: false,
8096 done: false,
8097 });
8098 self.select_previous(action, cx)?;
8099 }
8100 }
8101 Ok(())
8102 }
8103
8104 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8105 let text_layout_details = &self.text_layout_details(cx);
8106 self.transact(cx, |this, cx| {
8107 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8108 let mut edits = Vec::new();
8109 let mut selection_edit_ranges = Vec::new();
8110 let mut last_toggled_row = None;
8111 let snapshot = this.buffer.read(cx).read(cx);
8112 let empty_str: Arc<str> = "".into();
8113 let mut suffixes_inserted = Vec::new();
8114
8115 fn comment_prefix_range(
8116 snapshot: &MultiBufferSnapshot,
8117 row: MultiBufferRow,
8118 comment_prefix: &str,
8119 comment_prefix_whitespace: &str,
8120 ) -> Range<Point> {
8121 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8122
8123 let mut line_bytes = snapshot
8124 .bytes_in_range(start..snapshot.max_point())
8125 .flatten()
8126 .copied();
8127
8128 // If this line currently begins with the line comment prefix, then record
8129 // the range containing the prefix.
8130 if line_bytes
8131 .by_ref()
8132 .take(comment_prefix.len())
8133 .eq(comment_prefix.bytes())
8134 {
8135 // Include any whitespace that matches the comment prefix.
8136 let matching_whitespace_len = line_bytes
8137 .zip(comment_prefix_whitespace.bytes())
8138 .take_while(|(a, b)| a == b)
8139 .count() as u32;
8140 let end = Point::new(
8141 start.row,
8142 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8143 );
8144 start..end
8145 } else {
8146 start..start
8147 }
8148 }
8149
8150 fn comment_suffix_range(
8151 snapshot: &MultiBufferSnapshot,
8152 row: MultiBufferRow,
8153 comment_suffix: &str,
8154 comment_suffix_has_leading_space: bool,
8155 ) -> Range<Point> {
8156 let end = Point::new(row.0, snapshot.line_len(row));
8157 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8158
8159 let mut line_end_bytes = snapshot
8160 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8161 .flatten()
8162 .copied();
8163
8164 let leading_space_len = if suffix_start_column > 0
8165 && line_end_bytes.next() == Some(b' ')
8166 && comment_suffix_has_leading_space
8167 {
8168 1
8169 } else {
8170 0
8171 };
8172
8173 // If this line currently begins with the line comment prefix, then record
8174 // the range containing the prefix.
8175 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8176 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8177 start..end
8178 } else {
8179 end..end
8180 }
8181 }
8182
8183 // TODO: Handle selections that cross excerpts
8184 for selection in &mut selections {
8185 let start_column = snapshot
8186 .indent_size_for_line(MultiBufferRow(selection.start.row))
8187 .len;
8188 let language = if let Some(language) =
8189 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8190 {
8191 language
8192 } else {
8193 continue;
8194 };
8195
8196 selection_edit_ranges.clear();
8197
8198 // If multiple selections contain a given row, avoid processing that
8199 // row more than once.
8200 let mut start_row = MultiBufferRow(selection.start.row);
8201 if last_toggled_row == Some(start_row) {
8202 start_row = start_row.next_row();
8203 }
8204 let end_row =
8205 if selection.end.row > selection.start.row && selection.end.column == 0 {
8206 MultiBufferRow(selection.end.row - 1)
8207 } else {
8208 MultiBufferRow(selection.end.row)
8209 };
8210 last_toggled_row = Some(end_row);
8211
8212 if start_row > end_row {
8213 continue;
8214 }
8215
8216 // If the language has line comments, toggle those.
8217 let full_comment_prefixes = language.line_comment_prefixes();
8218 if !full_comment_prefixes.is_empty() {
8219 let first_prefix = full_comment_prefixes
8220 .first()
8221 .expect("prefixes is non-empty");
8222 let prefix_trimmed_lengths = full_comment_prefixes
8223 .iter()
8224 .map(|p| p.trim_end_matches(' ').len())
8225 .collect::<SmallVec<[usize; 4]>>();
8226
8227 let mut all_selection_lines_are_comments = true;
8228
8229 for row in start_row.0..=end_row.0 {
8230 let row = MultiBufferRow(row);
8231 if start_row < end_row && snapshot.is_line_blank(row) {
8232 continue;
8233 }
8234
8235 let prefix_range = full_comment_prefixes
8236 .iter()
8237 .zip(prefix_trimmed_lengths.iter().copied())
8238 .map(|(prefix, trimmed_prefix_len)| {
8239 comment_prefix_range(
8240 snapshot.deref(),
8241 row,
8242 &prefix[..trimmed_prefix_len],
8243 &prefix[trimmed_prefix_len..],
8244 )
8245 })
8246 .max_by_key(|range| range.end.column - range.start.column)
8247 .expect("prefixes is non-empty");
8248
8249 if prefix_range.is_empty() {
8250 all_selection_lines_are_comments = false;
8251 }
8252
8253 selection_edit_ranges.push(prefix_range);
8254 }
8255
8256 if all_selection_lines_are_comments {
8257 edits.extend(
8258 selection_edit_ranges
8259 .iter()
8260 .cloned()
8261 .map(|range| (range, empty_str.clone())),
8262 );
8263 } else {
8264 let min_column = selection_edit_ranges
8265 .iter()
8266 .map(|range| range.start.column)
8267 .min()
8268 .unwrap_or(0);
8269 edits.extend(selection_edit_ranges.iter().map(|range| {
8270 let position = Point::new(range.start.row, min_column);
8271 (position..position, first_prefix.clone())
8272 }));
8273 }
8274 } else if let Some((full_comment_prefix, comment_suffix)) =
8275 language.block_comment_delimiters()
8276 {
8277 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8278 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8279 let prefix_range = comment_prefix_range(
8280 snapshot.deref(),
8281 start_row,
8282 comment_prefix,
8283 comment_prefix_whitespace,
8284 );
8285 let suffix_range = comment_suffix_range(
8286 snapshot.deref(),
8287 end_row,
8288 comment_suffix.trim_start_matches(' '),
8289 comment_suffix.starts_with(' '),
8290 );
8291
8292 if prefix_range.is_empty() || suffix_range.is_empty() {
8293 edits.push((
8294 prefix_range.start..prefix_range.start,
8295 full_comment_prefix.clone(),
8296 ));
8297 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8298 suffixes_inserted.push((end_row, comment_suffix.len()));
8299 } else {
8300 edits.push((prefix_range, empty_str.clone()));
8301 edits.push((suffix_range, empty_str.clone()));
8302 }
8303 } else {
8304 continue;
8305 }
8306 }
8307
8308 drop(snapshot);
8309 this.buffer.update(cx, |buffer, cx| {
8310 buffer.edit(edits, None, cx);
8311 });
8312
8313 // Adjust selections so that they end before any comment suffixes that
8314 // were inserted.
8315 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8316 let mut selections = this.selections.all::<Point>(cx);
8317 let snapshot = this.buffer.read(cx).read(cx);
8318 for selection in &mut selections {
8319 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8320 match row.cmp(&MultiBufferRow(selection.end.row)) {
8321 Ordering::Less => {
8322 suffixes_inserted.next();
8323 continue;
8324 }
8325 Ordering::Greater => break,
8326 Ordering::Equal => {
8327 if selection.end.column == snapshot.line_len(row) {
8328 if selection.is_empty() {
8329 selection.start.column -= suffix_len as u32;
8330 }
8331 selection.end.column -= suffix_len as u32;
8332 }
8333 break;
8334 }
8335 }
8336 }
8337 }
8338
8339 drop(snapshot);
8340 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8341
8342 let selections = this.selections.all::<Point>(cx);
8343 let selections_on_single_row = selections.windows(2).all(|selections| {
8344 selections[0].start.row == selections[1].start.row
8345 && selections[0].end.row == selections[1].end.row
8346 && selections[0].start.row == selections[0].end.row
8347 });
8348 let selections_selecting = selections
8349 .iter()
8350 .any(|selection| selection.start != selection.end);
8351 let advance_downwards = action.advance_downwards
8352 && selections_on_single_row
8353 && !selections_selecting
8354 && !matches!(this.mode, EditorMode::SingleLine { .. });
8355
8356 if advance_downwards {
8357 let snapshot = this.buffer.read(cx).snapshot(cx);
8358
8359 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8360 s.move_cursors_with(|display_snapshot, display_point, _| {
8361 let mut point = display_point.to_point(display_snapshot);
8362 point.row += 1;
8363 point = snapshot.clip_point(point, Bias::Left);
8364 let display_point = point.to_display_point(display_snapshot);
8365 let goal = SelectionGoal::HorizontalPosition(
8366 display_snapshot
8367 .x_for_display_point(display_point, &text_layout_details)
8368 .into(),
8369 );
8370 (display_point, goal)
8371 })
8372 });
8373 }
8374 });
8375 }
8376
8377 pub fn select_enclosing_symbol(
8378 &mut self,
8379 _: &SelectEnclosingSymbol,
8380 cx: &mut ViewContext<Self>,
8381 ) {
8382 let buffer = self.buffer.read(cx).snapshot(cx);
8383 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8384
8385 fn update_selection(
8386 selection: &Selection<usize>,
8387 buffer_snap: &MultiBufferSnapshot,
8388 ) -> Option<Selection<usize>> {
8389 let cursor = selection.head();
8390 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8391 for symbol in symbols.iter().rev() {
8392 let start = symbol.range.start.to_offset(&buffer_snap);
8393 let end = symbol.range.end.to_offset(&buffer_snap);
8394 let new_range = start..end;
8395 if start < selection.start || end > selection.end {
8396 return Some(Selection {
8397 id: selection.id,
8398 start: new_range.start,
8399 end: new_range.end,
8400 goal: SelectionGoal::None,
8401 reversed: selection.reversed,
8402 });
8403 }
8404 }
8405 None
8406 }
8407
8408 let mut selected_larger_symbol = false;
8409 let new_selections = old_selections
8410 .iter()
8411 .map(|selection| match update_selection(selection, &buffer) {
8412 Some(new_selection) => {
8413 if new_selection.range() != selection.range() {
8414 selected_larger_symbol = true;
8415 }
8416 new_selection
8417 }
8418 None => selection.clone(),
8419 })
8420 .collect::<Vec<_>>();
8421
8422 if selected_larger_symbol {
8423 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8424 s.select(new_selections);
8425 });
8426 }
8427 }
8428
8429 pub fn select_larger_syntax_node(
8430 &mut self,
8431 _: &SelectLargerSyntaxNode,
8432 cx: &mut ViewContext<Self>,
8433 ) {
8434 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8435 let buffer = self.buffer.read(cx).snapshot(cx);
8436 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8437
8438 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8439 let mut selected_larger_node = false;
8440 let new_selections = old_selections
8441 .iter()
8442 .map(|selection| {
8443 let old_range = selection.start..selection.end;
8444 let mut new_range = old_range.clone();
8445 while let Some(containing_range) =
8446 buffer.range_for_syntax_ancestor(new_range.clone())
8447 {
8448 new_range = containing_range;
8449 if !display_map.intersects_fold(new_range.start)
8450 && !display_map.intersects_fold(new_range.end)
8451 {
8452 break;
8453 }
8454 }
8455
8456 selected_larger_node |= new_range != old_range;
8457 Selection {
8458 id: selection.id,
8459 start: new_range.start,
8460 end: new_range.end,
8461 goal: SelectionGoal::None,
8462 reversed: selection.reversed,
8463 }
8464 })
8465 .collect::<Vec<_>>();
8466
8467 if selected_larger_node {
8468 stack.push(old_selections);
8469 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8470 s.select(new_selections);
8471 });
8472 }
8473 self.select_larger_syntax_node_stack = stack;
8474 }
8475
8476 pub fn select_smaller_syntax_node(
8477 &mut self,
8478 _: &SelectSmallerSyntaxNode,
8479 cx: &mut ViewContext<Self>,
8480 ) {
8481 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8482 if let Some(selections) = stack.pop() {
8483 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8484 s.select(selections.to_vec());
8485 });
8486 }
8487 self.select_larger_syntax_node_stack = stack;
8488 }
8489
8490 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8491 if !EditorSettings::get_global(cx).gutter.runnables {
8492 self.clear_tasks();
8493 return Task::ready(());
8494 }
8495 let project = self.project.clone();
8496 cx.spawn(|this, mut cx| async move {
8497 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8498 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8499 }) else {
8500 return;
8501 };
8502
8503 let Some(project) = project else {
8504 return;
8505 };
8506
8507 let hide_runnables = project
8508 .update(&mut cx, |project, cx| {
8509 // Do not display any test indicators in non-dev server remote projects.
8510 project.is_remote() && project.ssh_connection_string(cx).is_none()
8511 })
8512 .unwrap_or(true);
8513 if hide_runnables {
8514 return;
8515 }
8516 let new_rows =
8517 cx.background_executor()
8518 .spawn({
8519 let snapshot = display_snapshot.clone();
8520 async move {
8521 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8522 }
8523 })
8524 .await;
8525 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8526
8527 this.update(&mut cx, |this, _| {
8528 this.clear_tasks();
8529 for (key, value) in rows {
8530 this.insert_tasks(key, value);
8531 }
8532 })
8533 .ok();
8534 })
8535 }
8536 fn fetch_runnable_ranges(
8537 snapshot: &DisplaySnapshot,
8538 range: Range<Anchor>,
8539 ) -> Vec<language::RunnableRange> {
8540 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8541 }
8542
8543 fn runnable_rows(
8544 project: Model<Project>,
8545 snapshot: DisplaySnapshot,
8546 runnable_ranges: Vec<RunnableRange>,
8547 mut cx: AsyncWindowContext,
8548 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8549 runnable_ranges
8550 .into_iter()
8551 .filter_map(|mut runnable| {
8552 let tasks = cx
8553 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8554 .ok()?;
8555 if tasks.is_empty() {
8556 return None;
8557 }
8558
8559 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8560
8561 let row = snapshot
8562 .buffer_snapshot
8563 .buffer_line_for_row(MultiBufferRow(point.row))?
8564 .1
8565 .start
8566 .row;
8567
8568 let context_range =
8569 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8570 Some((
8571 (runnable.buffer_id, row),
8572 RunnableTasks {
8573 templates: tasks,
8574 offset: MultiBufferOffset(runnable.run_range.start),
8575 context_range,
8576 column: point.column,
8577 extra_variables: runnable.extra_captures,
8578 },
8579 ))
8580 })
8581 .collect()
8582 }
8583
8584 fn templates_with_tags(
8585 project: &Model<Project>,
8586 runnable: &mut Runnable,
8587 cx: &WindowContext<'_>,
8588 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8589 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8590 let (worktree_id, file) = project
8591 .buffer_for_id(runnable.buffer, cx)
8592 .and_then(|buffer| buffer.read(cx).file())
8593 .map(|file| (WorktreeId::from_usize(file.worktree_id()), file.clone()))
8594 .unzip();
8595
8596 (project.task_inventory().clone(), worktree_id, file)
8597 });
8598
8599 let inventory = inventory.read(cx);
8600 let tags = mem::take(&mut runnable.tags);
8601 let mut tags: Vec<_> = tags
8602 .into_iter()
8603 .flat_map(|tag| {
8604 let tag = tag.0.clone();
8605 inventory
8606 .list_tasks(
8607 file.clone(),
8608 Some(runnable.language.clone()),
8609 worktree_id,
8610 cx,
8611 )
8612 .into_iter()
8613 .filter(move |(_, template)| {
8614 template.tags.iter().any(|source_tag| source_tag == &tag)
8615 })
8616 })
8617 .sorted_by_key(|(kind, _)| kind.to_owned())
8618 .collect();
8619 if let Some((leading_tag_source, _)) = tags.first() {
8620 // Strongest source wins; if we have worktree tag binding, prefer that to
8621 // global and language bindings;
8622 // if we have a global binding, prefer that to language binding.
8623 let first_mismatch = tags
8624 .iter()
8625 .position(|(tag_source, _)| tag_source != leading_tag_source);
8626 if let Some(index) = first_mismatch {
8627 tags.truncate(index);
8628 }
8629 }
8630
8631 tags
8632 }
8633
8634 pub fn move_to_enclosing_bracket(
8635 &mut self,
8636 _: &MoveToEnclosingBracket,
8637 cx: &mut ViewContext<Self>,
8638 ) {
8639 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8640 s.move_offsets_with(|snapshot, selection| {
8641 let Some(enclosing_bracket_ranges) =
8642 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
8643 else {
8644 return;
8645 };
8646
8647 let mut best_length = usize::MAX;
8648 let mut best_inside = false;
8649 let mut best_in_bracket_range = false;
8650 let mut best_destination = None;
8651 for (open, close) in enclosing_bracket_ranges {
8652 let close = close.to_inclusive();
8653 let length = close.end() - open.start;
8654 let inside = selection.start >= open.end && selection.end <= *close.start();
8655 let in_bracket_range = open.to_inclusive().contains(&selection.head())
8656 || close.contains(&selection.head());
8657
8658 // If best is next to a bracket and current isn't, skip
8659 if !in_bracket_range && best_in_bracket_range {
8660 continue;
8661 }
8662
8663 // Prefer smaller lengths unless best is inside and current isn't
8664 if length > best_length && (best_inside || !inside) {
8665 continue;
8666 }
8667
8668 best_length = length;
8669 best_inside = inside;
8670 best_in_bracket_range = in_bracket_range;
8671 best_destination = Some(
8672 if close.contains(&selection.start) && close.contains(&selection.end) {
8673 if inside {
8674 open.end
8675 } else {
8676 open.start
8677 }
8678 } else {
8679 if inside {
8680 *close.start()
8681 } else {
8682 *close.end()
8683 }
8684 },
8685 );
8686 }
8687
8688 if let Some(destination) = best_destination {
8689 selection.collapse_to(destination, SelectionGoal::None);
8690 }
8691 })
8692 });
8693 }
8694
8695 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
8696 self.end_selection(cx);
8697 self.selection_history.mode = SelectionHistoryMode::Undoing;
8698 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
8699 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8700 self.select_next_state = entry.select_next_state;
8701 self.select_prev_state = entry.select_prev_state;
8702 self.add_selections_state = entry.add_selections_state;
8703 self.request_autoscroll(Autoscroll::newest(), cx);
8704 }
8705 self.selection_history.mode = SelectionHistoryMode::Normal;
8706 }
8707
8708 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
8709 self.end_selection(cx);
8710 self.selection_history.mode = SelectionHistoryMode::Redoing;
8711 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
8712 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8713 self.select_next_state = entry.select_next_state;
8714 self.select_prev_state = entry.select_prev_state;
8715 self.add_selections_state = entry.add_selections_state;
8716 self.request_autoscroll(Autoscroll::newest(), cx);
8717 }
8718 self.selection_history.mode = SelectionHistoryMode::Normal;
8719 }
8720
8721 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
8722 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
8723 }
8724
8725 pub fn expand_excerpts_down(
8726 &mut self,
8727 action: &ExpandExcerptsDown,
8728 cx: &mut ViewContext<Self>,
8729 ) {
8730 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
8731 }
8732
8733 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
8734 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
8735 }
8736
8737 pub fn expand_excerpts_for_direction(
8738 &mut self,
8739 lines: u32,
8740 direction: ExpandExcerptDirection,
8741 cx: &mut ViewContext<Self>,
8742 ) {
8743 let selections = self.selections.disjoint_anchors();
8744
8745 let lines = if lines == 0 {
8746 EditorSettings::get_global(cx).expand_excerpt_lines
8747 } else {
8748 lines
8749 };
8750
8751 self.buffer.update(cx, |buffer, cx| {
8752 buffer.expand_excerpts(
8753 selections
8754 .into_iter()
8755 .map(|selection| selection.head().excerpt_id)
8756 .dedup(),
8757 lines,
8758 direction,
8759 cx,
8760 )
8761 })
8762 }
8763
8764 pub fn expand_excerpt(
8765 &mut self,
8766 excerpt: ExcerptId,
8767 direction: ExpandExcerptDirection,
8768 cx: &mut ViewContext<Self>,
8769 ) {
8770 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
8771 self.buffer.update(cx, |buffer, cx| {
8772 buffer.expand_excerpts([excerpt], lines, direction, cx)
8773 })
8774 }
8775
8776 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
8777 self.go_to_diagnostic_impl(Direction::Next, cx)
8778 }
8779
8780 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
8781 self.go_to_diagnostic_impl(Direction::Prev, cx)
8782 }
8783
8784 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
8785 let buffer = self.buffer.read(cx).snapshot(cx);
8786 let selection = self.selections.newest::<usize>(cx);
8787
8788 // If there is an active Diagnostic Popover jump to its diagnostic instead.
8789 if direction == Direction::Next {
8790 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
8791 let (group_id, jump_to) = popover.activation_info();
8792 if self.activate_diagnostics(group_id, cx) {
8793 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8794 let mut new_selection = s.newest_anchor().clone();
8795 new_selection.collapse_to(jump_to, SelectionGoal::None);
8796 s.select_anchors(vec![new_selection.clone()]);
8797 });
8798 }
8799 return;
8800 }
8801 }
8802
8803 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
8804 active_diagnostics
8805 .primary_range
8806 .to_offset(&buffer)
8807 .to_inclusive()
8808 });
8809 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
8810 if active_primary_range.contains(&selection.head()) {
8811 *active_primary_range.start()
8812 } else {
8813 selection.head()
8814 }
8815 } else {
8816 selection.head()
8817 };
8818 let snapshot = self.snapshot(cx);
8819 loop {
8820 let diagnostics = if direction == Direction::Prev {
8821 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
8822 } else {
8823 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
8824 }
8825 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
8826 let group = diagnostics
8827 // relies on diagnostics_in_range to return diagnostics with the same starting range to
8828 // be sorted in a stable way
8829 // skip until we are at current active diagnostic, if it exists
8830 .skip_while(|entry| {
8831 (match direction {
8832 Direction::Prev => entry.range.start >= search_start,
8833 Direction::Next => entry.range.start <= search_start,
8834 }) && self
8835 .active_diagnostics
8836 .as_ref()
8837 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
8838 })
8839 .find_map(|entry| {
8840 if entry.diagnostic.is_primary
8841 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
8842 && !entry.range.is_empty()
8843 // if we match with the active diagnostic, skip it
8844 && Some(entry.diagnostic.group_id)
8845 != self.active_diagnostics.as_ref().map(|d| d.group_id)
8846 {
8847 Some((entry.range, entry.diagnostic.group_id))
8848 } else {
8849 None
8850 }
8851 });
8852
8853 if let Some((primary_range, group_id)) = group {
8854 if self.activate_diagnostics(group_id, cx) {
8855 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8856 s.select(vec![Selection {
8857 id: selection.id,
8858 start: primary_range.start,
8859 end: primary_range.start,
8860 reversed: false,
8861 goal: SelectionGoal::None,
8862 }]);
8863 });
8864 }
8865 break;
8866 } else {
8867 // Cycle around to the start of the buffer, potentially moving back to the start of
8868 // the currently active diagnostic.
8869 active_primary_range.take();
8870 if direction == Direction::Prev {
8871 if search_start == buffer.len() {
8872 break;
8873 } else {
8874 search_start = buffer.len();
8875 }
8876 } else if search_start == 0 {
8877 break;
8878 } else {
8879 search_start = 0;
8880 }
8881 }
8882 }
8883 }
8884
8885 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
8886 let snapshot = self
8887 .display_map
8888 .update(cx, |display_map, cx| display_map.snapshot(cx));
8889 let selection = self.selections.newest::<Point>(cx);
8890
8891 if !self.seek_in_direction(
8892 &snapshot,
8893 selection.head(),
8894 false,
8895 snapshot.buffer_snapshot.git_diff_hunks_in_range(
8896 MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
8897 ),
8898 cx,
8899 ) {
8900 let wrapped_point = Point::zero();
8901 self.seek_in_direction(
8902 &snapshot,
8903 wrapped_point,
8904 true,
8905 snapshot.buffer_snapshot.git_diff_hunks_in_range(
8906 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
8907 ),
8908 cx,
8909 );
8910 }
8911 }
8912
8913 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
8914 let snapshot = self
8915 .display_map
8916 .update(cx, |display_map, cx| display_map.snapshot(cx));
8917 let selection = self.selections.newest::<Point>(cx);
8918
8919 if !self.seek_in_direction(
8920 &snapshot,
8921 selection.head(),
8922 false,
8923 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
8924 MultiBufferRow(0)..MultiBufferRow(selection.head().row),
8925 ),
8926 cx,
8927 ) {
8928 let wrapped_point = snapshot.buffer_snapshot.max_point();
8929 self.seek_in_direction(
8930 &snapshot,
8931 wrapped_point,
8932 true,
8933 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
8934 MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
8935 ),
8936 cx,
8937 );
8938 }
8939 }
8940
8941 fn seek_in_direction(
8942 &mut self,
8943 snapshot: &DisplaySnapshot,
8944 initial_point: Point,
8945 is_wrapped: bool,
8946 hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
8947 cx: &mut ViewContext<Editor>,
8948 ) -> bool {
8949 let display_point = initial_point.to_display_point(snapshot);
8950 let mut hunks = hunks
8951 .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
8952 .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
8953 .dedup();
8954
8955 if let Some(hunk) = hunks.next() {
8956 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8957 let row = hunk.start_display_row();
8958 let point = DisplayPoint::new(row, 0);
8959 s.select_display_ranges([point..point]);
8960 });
8961
8962 true
8963 } else {
8964 false
8965 }
8966 }
8967
8968 pub fn go_to_definition(
8969 &mut self,
8970 _: &GoToDefinition,
8971 cx: &mut ViewContext<Self>,
8972 ) -> Task<Result<bool>> {
8973 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx)
8974 }
8975
8976 pub fn go_to_implementation(
8977 &mut self,
8978 _: &GoToImplementation,
8979 cx: &mut ViewContext<Self>,
8980 ) -> Task<Result<bool>> {
8981 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
8982 }
8983
8984 pub fn go_to_implementation_split(
8985 &mut self,
8986 _: &GoToImplementationSplit,
8987 cx: &mut ViewContext<Self>,
8988 ) -> Task<Result<bool>> {
8989 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
8990 }
8991
8992 pub fn go_to_type_definition(
8993 &mut self,
8994 _: &GoToTypeDefinition,
8995 cx: &mut ViewContext<Self>,
8996 ) -> Task<Result<bool>> {
8997 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
8998 }
8999
9000 pub fn go_to_definition_split(
9001 &mut self,
9002 _: &GoToDefinitionSplit,
9003 cx: &mut ViewContext<Self>,
9004 ) -> Task<Result<bool>> {
9005 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9006 }
9007
9008 pub fn go_to_type_definition_split(
9009 &mut self,
9010 _: &GoToTypeDefinitionSplit,
9011 cx: &mut ViewContext<Self>,
9012 ) -> Task<Result<bool>> {
9013 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9014 }
9015
9016 fn go_to_definition_of_kind(
9017 &mut self,
9018 kind: GotoDefinitionKind,
9019 split: bool,
9020 cx: &mut ViewContext<Self>,
9021 ) -> Task<Result<bool>> {
9022 let Some(workspace) = self.workspace() else {
9023 return Task::ready(Ok(false));
9024 };
9025 let buffer = self.buffer.read(cx);
9026 let head = self.selections.newest::<usize>(cx).head();
9027 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9028 text_anchor
9029 } else {
9030 return Task::ready(Ok(false));
9031 };
9032
9033 let project = workspace.read(cx).project().clone();
9034 let definitions = project.update(cx, |project, cx| match kind {
9035 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
9036 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
9037 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
9038 });
9039
9040 cx.spawn(|editor, mut cx| async move {
9041 let definitions = definitions.await?;
9042 let navigated = editor
9043 .update(&mut cx, |editor, cx| {
9044 editor.navigate_to_hover_links(
9045 Some(kind),
9046 definitions
9047 .into_iter()
9048 .filter(|location| {
9049 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9050 })
9051 .map(HoverLink::Text)
9052 .collect::<Vec<_>>(),
9053 split,
9054 cx,
9055 )
9056 })?
9057 .await?;
9058 anyhow::Ok(navigated)
9059 })
9060 }
9061
9062 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9063 let position = self.selections.newest_anchor().head();
9064 let Some((buffer, buffer_position)) =
9065 self.buffer.read(cx).text_anchor_for_position(position, cx)
9066 else {
9067 return;
9068 };
9069
9070 cx.spawn(|editor, mut cx| async move {
9071 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9072 editor.update(&mut cx, |_, cx| {
9073 cx.open_url(&url);
9074 })
9075 } else {
9076 Ok(())
9077 }
9078 })
9079 .detach();
9080 }
9081
9082 pub(crate) fn navigate_to_hover_links(
9083 &mut self,
9084 kind: Option<GotoDefinitionKind>,
9085 mut definitions: Vec<HoverLink>,
9086 split: bool,
9087 cx: &mut ViewContext<Editor>,
9088 ) -> Task<Result<bool>> {
9089 // If there is one definition, just open it directly
9090 if definitions.len() == 1 {
9091 let definition = definitions.pop().unwrap();
9092 let target_task = match definition {
9093 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9094 HoverLink::InlayHint(lsp_location, server_id) => {
9095 self.compute_target_location(lsp_location, server_id, cx)
9096 }
9097 HoverLink::Url(url) => {
9098 cx.open_url(&url);
9099 Task::ready(Ok(None))
9100 }
9101 };
9102 cx.spawn(|editor, mut cx| async move {
9103 let target = target_task.await.context("target resolution task")?;
9104 if let Some(target) = target {
9105 editor.update(&mut cx, |editor, cx| {
9106 let Some(workspace) = editor.workspace() else {
9107 return false;
9108 };
9109 let pane = workspace.read(cx).active_pane().clone();
9110
9111 let range = target.range.to_offset(target.buffer.read(cx));
9112 let range = editor.range_for_match(&range);
9113
9114 /// If select range has more than one line, we
9115 /// just point the cursor to range.start.
9116 fn check_multiline_range(
9117 buffer: &Buffer,
9118 range: Range<usize>,
9119 ) -> Range<usize> {
9120 if buffer.offset_to_point(range.start).row
9121 == buffer.offset_to_point(range.end).row
9122 {
9123 range
9124 } else {
9125 range.start..range.start
9126 }
9127 }
9128
9129 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9130 let buffer = target.buffer.read(cx);
9131 let range = check_multiline_range(buffer, range);
9132 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
9133 s.select_ranges([range]);
9134 });
9135 } else {
9136 cx.window_context().defer(move |cx| {
9137 let target_editor: View<Self> =
9138 workspace.update(cx, |workspace, cx| {
9139 let pane = if split {
9140 workspace.adjacent_pane(cx)
9141 } else {
9142 workspace.active_pane().clone()
9143 };
9144
9145 workspace.open_project_item(
9146 pane,
9147 target.buffer.clone(),
9148 true,
9149 true,
9150 cx,
9151 )
9152 });
9153 target_editor.update(cx, |target_editor, cx| {
9154 // When selecting a definition in a different buffer, disable the nav history
9155 // to avoid creating a history entry at the previous cursor location.
9156 pane.update(cx, |pane, _| pane.disable_history());
9157 let buffer = target.buffer.read(cx);
9158 let range = check_multiline_range(buffer, range);
9159 target_editor.change_selections(
9160 Some(Autoscroll::focused()),
9161 cx,
9162 |s| {
9163 s.select_ranges([range]);
9164 },
9165 );
9166 pane.update(cx, |pane, _| pane.enable_history());
9167 });
9168 });
9169 }
9170 true
9171 })
9172 } else {
9173 Ok(false)
9174 }
9175 })
9176 } else if !definitions.is_empty() {
9177 let replica_id = self.replica_id(cx);
9178 cx.spawn(|editor, mut cx| async move {
9179 let (title, location_tasks, workspace) = editor
9180 .update(&mut cx, |editor, cx| {
9181 let tab_kind = match kind {
9182 Some(GotoDefinitionKind::Implementation) => "Implementations",
9183 _ => "Definitions",
9184 };
9185 let title = definitions
9186 .iter()
9187 .find_map(|definition| match definition {
9188 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9189 let buffer = origin.buffer.read(cx);
9190 format!(
9191 "{} for {}",
9192 tab_kind,
9193 buffer
9194 .text_for_range(origin.range.clone())
9195 .collect::<String>()
9196 )
9197 }),
9198 HoverLink::InlayHint(_, _) => None,
9199 HoverLink::Url(_) => None,
9200 })
9201 .unwrap_or(tab_kind.to_string());
9202 let location_tasks = definitions
9203 .into_iter()
9204 .map(|definition| match definition {
9205 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9206 HoverLink::InlayHint(lsp_location, server_id) => {
9207 editor.compute_target_location(lsp_location, server_id, cx)
9208 }
9209 HoverLink::Url(_) => Task::ready(Ok(None)),
9210 })
9211 .collect::<Vec<_>>();
9212 (title, location_tasks, editor.workspace().clone())
9213 })
9214 .context("location tasks preparation")?;
9215
9216 let locations = futures::future::join_all(location_tasks)
9217 .await
9218 .into_iter()
9219 .filter_map(|location| location.transpose())
9220 .collect::<Result<_>>()
9221 .context("location tasks")?;
9222
9223 let Some(workspace) = workspace else {
9224 return Ok(false);
9225 };
9226 let opened = workspace
9227 .update(&mut cx, |workspace, cx| {
9228 Self::open_locations_in_multibuffer(
9229 workspace, locations, replica_id, title, split, cx,
9230 )
9231 })
9232 .ok();
9233
9234 anyhow::Ok(opened.is_some())
9235 })
9236 } else {
9237 Task::ready(Ok(false))
9238 }
9239 }
9240
9241 fn compute_target_location(
9242 &self,
9243 lsp_location: lsp::Location,
9244 server_id: LanguageServerId,
9245 cx: &mut ViewContext<Editor>,
9246 ) -> Task<anyhow::Result<Option<Location>>> {
9247 let Some(project) = self.project.clone() else {
9248 return Task::Ready(Some(Ok(None)));
9249 };
9250
9251 cx.spawn(move |editor, mut cx| async move {
9252 let location_task = editor.update(&mut cx, |editor, cx| {
9253 project.update(cx, |project, cx| {
9254 let language_server_name =
9255 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9256 project
9257 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9258 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9259 });
9260 language_server_name.map(|language_server_name| {
9261 project.open_local_buffer_via_lsp(
9262 lsp_location.uri.clone(),
9263 server_id,
9264 language_server_name,
9265 cx,
9266 )
9267 })
9268 })
9269 })?;
9270 let location = match location_task {
9271 Some(task) => Some({
9272 let target_buffer_handle = task.await.context("open local buffer")?;
9273 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9274 let target_start = target_buffer
9275 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9276 let target_end = target_buffer
9277 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9278 target_buffer.anchor_after(target_start)
9279 ..target_buffer.anchor_before(target_end)
9280 })?;
9281 Location {
9282 buffer: target_buffer_handle,
9283 range,
9284 }
9285 }),
9286 None => None,
9287 };
9288 Ok(location)
9289 })
9290 }
9291
9292 pub fn find_all_references(
9293 &mut self,
9294 _: &FindAllReferences,
9295 cx: &mut ViewContext<Self>,
9296 ) -> Option<Task<Result<()>>> {
9297 let multi_buffer = self.buffer.read(cx);
9298 let selection = self.selections.newest::<usize>(cx);
9299 let head = selection.head();
9300
9301 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9302 let head_anchor = multi_buffer_snapshot.anchor_at(
9303 head,
9304 if head < selection.tail() {
9305 Bias::Right
9306 } else {
9307 Bias::Left
9308 },
9309 );
9310
9311 match self
9312 .find_all_references_task_sources
9313 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9314 {
9315 Ok(_) => {
9316 log::info!(
9317 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9318 );
9319 return None;
9320 }
9321 Err(i) => {
9322 self.find_all_references_task_sources.insert(i, head_anchor);
9323 }
9324 }
9325
9326 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9327 let replica_id = self.replica_id(cx);
9328 let workspace = self.workspace()?;
9329 let project = workspace.read(cx).project().clone();
9330 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9331 Some(cx.spawn(|editor, mut cx| async move {
9332 let _cleanup = defer({
9333 let mut cx = cx.clone();
9334 move || {
9335 let _ = editor.update(&mut cx, |editor, _| {
9336 if let Ok(i) =
9337 editor
9338 .find_all_references_task_sources
9339 .binary_search_by(|anchor| {
9340 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9341 })
9342 {
9343 editor.find_all_references_task_sources.remove(i);
9344 }
9345 });
9346 }
9347 });
9348
9349 let locations = references.await?;
9350 if locations.is_empty() {
9351 return anyhow::Ok(());
9352 }
9353
9354 workspace.update(&mut cx, |workspace, cx| {
9355 let title = locations
9356 .first()
9357 .as_ref()
9358 .map(|location| {
9359 let buffer = location.buffer.read(cx);
9360 format!(
9361 "References to `{}`",
9362 buffer
9363 .text_for_range(location.range.clone())
9364 .collect::<String>()
9365 )
9366 })
9367 .unwrap();
9368 Self::open_locations_in_multibuffer(
9369 workspace, locations, replica_id, title, false, cx,
9370 );
9371 })
9372 }))
9373 }
9374
9375 /// Opens a multibuffer with the given project locations in it
9376 pub fn open_locations_in_multibuffer(
9377 workspace: &mut Workspace,
9378 mut locations: Vec<Location>,
9379 replica_id: ReplicaId,
9380 title: String,
9381 split: bool,
9382 cx: &mut ViewContext<Workspace>,
9383 ) {
9384 // If there are multiple definitions, open them in a multibuffer
9385 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9386 let mut locations = locations.into_iter().peekable();
9387 let mut ranges_to_highlight = Vec::new();
9388 let capability = workspace.project().read(cx).capability();
9389
9390 let excerpt_buffer = cx.new_model(|cx| {
9391 let mut multibuffer = MultiBuffer::new(replica_id, capability);
9392 while let Some(location) = locations.next() {
9393 let buffer = location.buffer.read(cx);
9394 let mut ranges_for_buffer = Vec::new();
9395 let range = location.range.to_offset(buffer);
9396 ranges_for_buffer.push(range.clone());
9397
9398 while let Some(next_location) = locations.peek() {
9399 if next_location.buffer == location.buffer {
9400 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9401 locations.next();
9402 } else {
9403 break;
9404 }
9405 }
9406
9407 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9408 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9409 location.buffer.clone(),
9410 ranges_for_buffer,
9411 DEFAULT_MULTIBUFFER_CONTEXT,
9412 cx,
9413 ))
9414 }
9415
9416 multibuffer.with_title(title)
9417 });
9418
9419 let editor = cx.new_view(|cx| {
9420 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9421 });
9422 editor.update(cx, |editor, cx| {
9423 if let Some(first_range) = ranges_to_highlight.first() {
9424 editor.change_selections(None, cx, |selections| {
9425 selections.clear_disjoint();
9426 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9427 });
9428 }
9429 editor.highlight_background::<Self>(
9430 &ranges_to_highlight,
9431 |theme| theme.editor_highlighted_line_background,
9432 cx,
9433 );
9434 });
9435
9436 let item = Box::new(editor);
9437 let item_id = item.item_id();
9438
9439 if split {
9440 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9441 } else {
9442 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9443 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9444 pane.close_current_preview_item(cx)
9445 } else {
9446 None
9447 }
9448 });
9449 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9450 }
9451 workspace.active_pane().update(cx, |pane, cx| {
9452 pane.set_preview_item_id(Some(item_id), cx);
9453 });
9454 }
9455
9456 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9457 use language::ToOffset as _;
9458
9459 let project = self.project.clone()?;
9460 let selection = self.selections.newest_anchor().clone();
9461 let (cursor_buffer, cursor_buffer_position) = self
9462 .buffer
9463 .read(cx)
9464 .text_anchor_for_position(selection.head(), cx)?;
9465 let (tail_buffer, cursor_buffer_position_end) = self
9466 .buffer
9467 .read(cx)
9468 .text_anchor_for_position(selection.tail(), cx)?;
9469 if tail_buffer != cursor_buffer {
9470 return None;
9471 }
9472
9473 let snapshot = cursor_buffer.read(cx).snapshot();
9474 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9475 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9476 let prepare_rename = project.update(cx, |project, cx| {
9477 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
9478 });
9479 drop(snapshot);
9480
9481 Some(cx.spawn(|this, mut cx| async move {
9482 let rename_range = if let Some(range) = prepare_rename.await? {
9483 Some(range)
9484 } else {
9485 this.update(&mut cx, |this, cx| {
9486 let buffer = this.buffer.read(cx).snapshot(cx);
9487 let mut buffer_highlights = this
9488 .document_highlights_for_position(selection.head(), &buffer)
9489 .filter(|highlight| {
9490 highlight.start.excerpt_id == selection.head().excerpt_id
9491 && highlight.end.excerpt_id == selection.head().excerpt_id
9492 });
9493 buffer_highlights
9494 .next()
9495 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9496 })?
9497 };
9498 if let Some(rename_range) = rename_range {
9499 this.update(&mut cx, |this, cx| {
9500 let snapshot = cursor_buffer.read(cx).snapshot();
9501 let rename_buffer_range = rename_range.to_offset(&snapshot);
9502 let cursor_offset_in_rename_range =
9503 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9504 let cursor_offset_in_rename_range_end =
9505 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9506
9507 this.take_rename(false, cx);
9508 let buffer = this.buffer.read(cx).read(cx);
9509 let cursor_offset = selection.head().to_offset(&buffer);
9510 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9511 let rename_end = rename_start + rename_buffer_range.len();
9512 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9513 let mut old_highlight_id = None;
9514 let old_name: Arc<str> = buffer
9515 .chunks(rename_start..rename_end, true)
9516 .map(|chunk| {
9517 if old_highlight_id.is_none() {
9518 old_highlight_id = chunk.syntax_highlight_id;
9519 }
9520 chunk.text
9521 })
9522 .collect::<String>()
9523 .into();
9524
9525 drop(buffer);
9526
9527 // Position the selection in the rename editor so that it matches the current selection.
9528 this.show_local_selections = false;
9529 let rename_editor = cx.new_view(|cx| {
9530 let mut editor = Editor::single_line(cx);
9531 editor.buffer.update(cx, |buffer, cx| {
9532 buffer.edit([(0..0, old_name.clone())], None, cx)
9533 });
9534 let rename_selection_range = match cursor_offset_in_rename_range
9535 .cmp(&cursor_offset_in_rename_range_end)
9536 {
9537 Ordering::Equal => {
9538 editor.select_all(&SelectAll, cx);
9539 return editor;
9540 }
9541 Ordering::Less => {
9542 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9543 }
9544 Ordering::Greater => {
9545 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9546 }
9547 };
9548 if rename_selection_range.end > old_name.len() {
9549 editor.select_all(&SelectAll, cx);
9550 } else {
9551 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9552 s.select_ranges([rename_selection_range]);
9553 });
9554 }
9555 editor
9556 });
9557 cx.subscribe(&rename_editor, |_, _, e, cx| match e {
9558 EditorEvent::Focused => cx.emit(EditorEvent::FocusedIn),
9559 _ => {}
9560 })
9561 .detach();
9562
9563 let write_highlights =
9564 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
9565 let read_highlights =
9566 this.clear_background_highlights::<DocumentHighlightRead>(cx);
9567 let ranges = write_highlights
9568 .iter()
9569 .flat_map(|(_, ranges)| ranges.iter())
9570 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
9571 .cloned()
9572 .collect();
9573
9574 this.highlight_text::<Rename>(
9575 ranges,
9576 HighlightStyle {
9577 fade_out: Some(0.6),
9578 ..Default::default()
9579 },
9580 cx,
9581 );
9582 let rename_focus_handle = rename_editor.focus_handle(cx);
9583 cx.focus(&rename_focus_handle);
9584 let block_id = this.insert_blocks(
9585 [BlockProperties {
9586 style: BlockStyle::Flex,
9587 position: range.start,
9588 height: 1,
9589 render: Box::new({
9590 let rename_editor = rename_editor.clone();
9591 move |cx: &mut BlockContext| {
9592 let mut text_style = cx.editor_style.text.clone();
9593 if let Some(highlight_style) = old_highlight_id
9594 .and_then(|h| h.style(&cx.editor_style.syntax))
9595 {
9596 text_style = text_style.highlight(highlight_style);
9597 }
9598 div()
9599 .pl(cx.anchor_x)
9600 .child(EditorElement::new(
9601 &rename_editor,
9602 EditorStyle {
9603 background: cx.theme().system().transparent,
9604 local_player: cx.editor_style.local_player,
9605 text: text_style,
9606 scrollbar_width: cx.editor_style.scrollbar_width,
9607 syntax: cx.editor_style.syntax.clone(),
9608 status: cx.editor_style.status.clone(),
9609 inlay_hints_style: HighlightStyle {
9610 color: Some(cx.theme().status().hint),
9611 font_weight: Some(FontWeight::BOLD),
9612 ..HighlightStyle::default()
9613 },
9614 suggestions_style: HighlightStyle {
9615 color: Some(cx.theme().status().predictive),
9616 ..HighlightStyle::default()
9617 },
9618 },
9619 ))
9620 .into_any_element()
9621 }
9622 }),
9623 disposition: BlockDisposition::Below,
9624 }],
9625 Some(Autoscroll::fit()),
9626 cx,
9627 )[0];
9628 this.pending_rename = Some(RenameState {
9629 range,
9630 old_name,
9631 editor: rename_editor,
9632 block_id,
9633 });
9634 })?;
9635 }
9636
9637 Ok(())
9638 }))
9639 }
9640
9641 pub fn confirm_rename(
9642 &mut self,
9643 _: &ConfirmRename,
9644 cx: &mut ViewContext<Self>,
9645 ) -> Option<Task<Result<()>>> {
9646 let rename = self.take_rename(false, cx)?;
9647 let workspace = self.workspace()?;
9648 let (start_buffer, start) = self
9649 .buffer
9650 .read(cx)
9651 .text_anchor_for_position(rename.range.start, cx)?;
9652 let (end_buffer, end) = self
9653 .buffer
9654 .read(cx)
9655 .text_anchor_for_position(rename.range.end, cx)?;
9656 if start_buffer != end_buffer {
9657 return None;
9658 }
9659
9660 let buffer = start_buffer;
9661 let range = start..end;
9662 let old_name = rename.old_name;
9663 let new_name = rename.editor.read(cx).text(cx);
9664
9665 let rename = workspace
9666 .read(cx)
9667 .project()
9668 .clone()
9669 .update(cx, |project, cx| {
9670 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
9671 });
9672 let workspace = workspace.downgrade();
9673
9674 Some(cx.spawn(|editor, mut cx| async move {
9675 let project_transaction = rename.await?;
9676 Self::open_project_transaction(
9677 &editor,
9678 workspace,
9679 project_transaction,
9680 format!("Rename: {} → {}", old_name, new_name),
9681 cx.clone(),
9682 )
9683 .await?;
9684
9685 editor.update(&mut cx, |editor, cx| {
9686 editor.refresh_document_highlights(cx);
9687 })?;
9688 Ok(())
9689 }))
9690 }
9691
9692 fn take_rename(
9693 &mut self,
9694 moving_cursor: bool,
9695 cx: &mut ViewContext<Self>,
9696 ) -> Option<RenameState> {
9697 let rename = self.pending_rename.take()?;
9698 if rename.editor.focus_handle(cx).is_focused(cx) {
9699 cx.focus(&self.focus_handle);
9700 }
9701
9702 self.remove_blocks(
9703 [rename.block_id].into_iter().collect(),
9704 Some(Autoscroll::fit()),
9705 cx,
9706 );
9707 self.clear_highlights::<Rename>(cx);
9708 self.show_local_selections = true;
9709
9710 if moving_cursor {
9711 let rename_editor = rename.editor.read(cx);
9712 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
9713
9714 // Update the selection to match the position of the selection inside
9715 // the rename editor.
9716 let snapshot = self.buffer.read(cx).read(cx);
9717 let rename_range = rename.range.to_offset(&snapshot);
9718 let cursor_in_editor = snapshot
9719 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
9720 .min(rename_range.end);
9721 drop(snapshot);
9722
9723 self.change_selections(None, cx, |s| {
9724 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
9725 });
9726 } else {
9727 self.refresh_document_highlights(cx);
9728 }
9729
9730 Some(rename)
9731 }
9732
9733 pub fn pending_rename(&self) -> Option<&RenameState> {
9734 self.pending_rename.as_ref()
9735 }
9736
9737 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9738 let project = match &self.project {
9739 Some(project) => project.clone(),
9740 None => return None,
9741 };
9742
9743 Some(self.perform_format(project, FormatTrigger::Manual, cx))
9744 }
9745
9746 fn perform_format(
9747 &mut self,
9748 project: Model<Project>,
9749 trigger: FormatTrigger,
9750 cx: &mut ViewContext<Self>,
9751 ) -> Task<Result<()>> {
9752 let buffer = self.buffer().clone();
9753 let mut buffers = buffer.read(cx).all_buffers();
9754 if trigger == FormatTrigger::Save {
9755 buffers.retain(|buffer| buffer.read(cx).is_dirty());
9756 }
9757
9758 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
9759 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
9760
9761 cx.spawn(|_, mut cx| async move {
9762 let transaction = futures::select_biased! {
9763 () = timeout => {
9764 log::warn!("timed out waiting for formatting");
9765 None
9766 }
9767 transaction = format.log_err().fuse() => transaction,
9768 };
9769
9770 buffer
9771 .update(&mut cx, |buffer, cx| {
9772 if let Some(transaction) = transaction {
9773 if !buffer.is_singleton() {
9774 buffer.push_transaction(&transaction.0, cx);
9775 }
9776 }
9777
9778 cx.notify();
9779 })
9780 .ok();
9781
9782 Ok(())
9783 })
9784 }
9785
9786 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
9787 if let Some(project) = self.project.clone() {
9788 self.buffer.update(cx, |multi_buffer, cx| {
9789 project.update(cx, |project, cx| {
9790 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
9791 });
9792 })
9793 }
9794 }
9795
9796 fn cancel_language_server_work(
9797 &mut self,
9798 _: &CancelLanguageServerWork,
9799 cx: &mut ViewContext<Self>,
9800 ) {
9801 if let Some(project) = self.project.clone() {
9802 self.buffer.update(cx, |multi_buffer, cx| {
9803 project.update(cx, |project, cx| {
9804 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
9805 });
9806 })
9807 }
9808 }
9809
9810 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
9811 cx.show_character_palette();
9812 }
9813
9814 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
9815 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
9816 let buffer = self.buffer.read(cx).snapshot(cx);
9817 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
9818 let is_valid = buffer
9819 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
9820 .any(|entry| {
9821 entry.diagnostic.is_primary
9822 && !entry.range.is_empty()
9823 && entry.range.start == primary_range_start
9824 && entry.diagnostic.message == active_diagnostics.primary_message
9825 });
9826
9827 if is_valid != active_diagnostics.is_valid {
9828 active_diagnostics.is_valid = is_valid;
9829 let mut new_styles = HashMap::default();
9830 for (block_id, diagnostic) in &active_diagnostics.blocks {
9831 new_styles.insert(
9832 *block_id,
9833 (
9834 None,
9835 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
9836 ),
9837 );
9838 }
9839 self.display_map.update(cx, |display_map, cx| {
9840 display_map.replace_blocks(new_styles, cx)
9841 });
9842 }
9843 }
9844 }
9845
9846 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
9847 self.dismiss_diagnostics(cx);
9848 let snapshot = self.snapshot(cx);
9849 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
9850 let buffer = self.buffer.read(cx).snapshot(cx);
9851
9852 let mut primary_range = None;
9853 let mut primary_message = None;
9854 let mut group_end = Point::zero();
9855 let diagnostic_group = buffer
9856 .diagnostic_group::<MultiBufferPoint>(group_id)
9857 .filter_map(|entry| {
9858 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
9859 && (entry.range.start.row == entry.range.end.row
9860 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
9861 {
9862 return None;
9863 }
9864 if entry.range.end > group_end {
9865 group_end = entry.range.end;
9866 }
9867 if entry.diagnostic.is_primary {
9868 primary_range = Some(entry.range.clone());
9869 primary_message = Some(entry.diagnostic.message.clone());
9870 }
9871 Some(entry)
9872 })
9873 .collect::<Vec<_>>();
9874 let primary_range = primary_range?;
9875 let primary_message = primary_message?;
9876 let primary_range =
9877 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
9878
9879 let blocks = display_map
9880 .insert_blocks(
9881 diagnostic_group.iter().map(|entry| {
9882 let diagnostic = entry.diagnostic.clone();
9883 let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
9884 BlockProperties {
9885 style: BlockStyle::Fixed,
9886 position: buffer.anchor_after(entry.range.start),
9887 height: message_height,
9888 render: diagnostic_block_renderer(diagnostic, None, true, true),
9889 disposition: BlockDisposition::Below,
9890 }
9891 }),
9892 cx,
9893 )
9894 .into_iter()
9895 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
9896 .collect();
9897
9898 Some(ActiveDiagnosticGroup {
9899 primary_range,
9900 primary_message,
9901 group_id,
9902 blocks,
9903 is_valid: true,
9904 })
9905 });
9906 self.active_diagnostics.is_some()
9907 }
9908
9909 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
9910 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
9911 self.display_map.update(cx, |display_map, cx| {
9912 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
9913 });
9914 cx.notify();
9915 }
9916 }
9917
9918 pub fn set_selections_from_remote(
9919 &mut self,
9920 selections: Vec<Selection<Anchor>>,
9921 pending_selection: Option<Selection<Anchor>>,
9922 cx: &mut ViewContext<Self>,
9923 ) {
9924 let old_cursor_position = self.selections.newest_anchor().head();
9925 self.selections.change_with(cx, |s| {
9926 s.select_anchors(selections);
9927 if let Some(pending_selection) = pending_selection {
9928 s.set_pending(pending_selection, SelectMode::Character);
9929 } else {
9930 s.clear_pending();
9931 }
9932 });
9933 self.selections_did_change(false, &old_cursor_position, true, cx);
9934 }
9935
9936 fn push_to_selection_history(&mut self) {
9937 self.selection_history.push(SelectionHistoryEntry {
9938 selections: self.selections.disjoint_anchors(),
9939 select_next_state: self.select_next_state.clone(),
9940 select_prev_state: self.select_prev_state.clone(),
9941 add_selections_state: self.add_selections_state.clone(),
9942 });
9943 }
9944
9945 pub fn transact(
9946 &mut self,
9947 cx: &mut ViewContext<Self>,
9948 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
9949 ) -> Option<TransactionId> {
9950 self.start_transaction_at(Instant::now(), cx);
9951 update(self, cx);
9952 self.end_transaction_at(Instant::now(), cx)
9953 }
9954
9955 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
9956 self.end_selection(cx);
9957 if let Some(tx_id) = self
9958 .buffer
9959 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
9960 {
9961 self.selection_history
9962 .insert_transaction(tx_id, self.selections.disjoint_anchors());
9963 cx.emit(EditorEvent::TransactionBegun {
9964 transaction_id: tx_id,
9965 })
9966 }
9967 }
9968
9969 fn end_transaction_at(
9970 &mut self,
9971 now: Instant,
9972 cx: &mut ViewContext<Self>,
9973 ) -> Option<TransactionId> {
9974 if let Some(transaction_id) = self
9975 .buffer
9976 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
9977 {
9978 if let Some((_, end_selections)) =
9979 self.selection_history.transaction_mut(transaction_id)
9980 {
9981 *end_selections = Some(self.selections.disjoint_anchors());
9982 } else {
9983 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
9984 }
9985
9986 cx.emit(EditorEvent::Edited { transaction_id });
9987 Some(transaction_id)
9988 } else {
9989 None
9990 }
9991 }
9992
9993 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
9994 let mut fold_ranges = Vec::new();
9995
9996 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9997
9998 let selections = self.selections.all_adjusted(cx);
9999 for selection in selections {
10000 let range = selection.range().sorted();
10001 let buffer_start_row = range.start.row;
10002
10003 for row in (0..=range.end.row).rev() {
10004 if let Some((foldable_range, fold_text)) =
10005 display_map.foldable_range(MultiBufferRow(row))
10006 {
10007 if foldable_range.end.row >= buffer_start_row {
10008 fold_ranges.push((foldable_range, fold_text));
10009 if row <= range.start.row {
10010 break;
10011 }
10012 }
10013 }
10014 }
10015 }
10016
10017 self.fold_ranges(fold_ranges, true, cx);
10018 }
10019
10020 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10021 let buffer_row = fold_at.buffer_row;
10022 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10023
10024 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10025 let autoscroll = self
10026 .selections
10027 .all::<Point>(cx)
10028 .iter()
10029 .any(|selection| fold_range.overlaps(&selection.range()));
10030
10031 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10032 }
10033 }
10034
10035 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10036 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10037 let buffer = &display_map.buffer_snapshot;
10038 let selections = self.selections.all::<Point>(cx);
10039 let ranges = selections
10040 .iter()
10041 .map(|s| {
10042 let range = s.display_range(&display_map).sorted();
10043 let mut start = range.start.to_point(&display_map);
10044 let mut end = range.end.to_point(&display_map);
10045 start.column = 0;
10046 end.column = buffer.line_len(MultiBufferRow(end.row));
10047 start..end
10048 })
10049 .collect::<Vec<_>>();
10050
10051 self.unfold_ranges(ranges, true, true, cx);
10052 }
10053
10054 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10055 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10056
10057 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10058 ..Point::new(
10059 unfold_at.buffer_row.0,
10060 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10061 );
10062
10063 let autoscroll = self
10064 .selections
10065 .all::<Point>(cx)
10066 .iter()
10067 .any(|selection| selection.range().overlaps(&intersection_range));
10068
10069 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10070 }
10071
10072 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10073 let selections = self.selections.all::<Point>(cx);
10074 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10075 let line_mode = self.selections.line_mode;
10076 let ranges = selections.into_iter().map(|s| {
10077 if line_mode {
10078 let start = Point::new(s.start.row, 0);
10079 let end = Point::new(
10080 s.end.row,
10081 display_map
10082 .buffer_snapshot
10083 .line_len(MultiBufferRow(s.end.row)),
10084 );
10085 (start..end, display_map.fold_placeholder.clone())
10086 } else {
10087 (s.start..s.end, display_map.fold_placeholder.clone())
10088 }
10089 });
10090 self.fold_ranges(ranges, true, cx);
10091 }
10092
10093 pub fn fold_ranges<T: ToOffset + Clone>(
10094 &mut self,
10095 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10096 auto_scroll: bool,
10097 cx: &mut ViewContext<Self>,
10098 ) {
10099 let mut fold_ranges = Vec::new();
10100 let mut buffers_affected = HashMap::default();
10101 let multi_buffer = self.buffer().read(cx);
10102 for (fold_range, fold_text) in ranges {
10103 if let Some((_, buffer, _)) =
10104 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10105 {
10106 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10107 };
10108 fold_ranges.push((fold_range, fold_text));
10109 }
10110
10111 let mut ranges = fold_ranges.into_iter().peekable();
10112 if ranges.peek().is_some() {
10113 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10114
10115 if auto_scroll {
10116 self.request_autoscroll(Autoscroll::fit(), cx);
10117 }
10118
10119 for buffer in buffers_affected.into_values() {
10120 self.sync_expanded_diff_hunks(buffer, cx);
10121 }
10122
10123 cx.notify();
10124
10125 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10126 // Clear diagnostics block when folding a range that contains it.
10127 let snapshot = self.snapshot(cx);
10128 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10129 drop(snapshot);
10130 self.active_diagnostics = Some(active_diagnostics);
10131 self.dismiss_diagnostics(cx);
10132 } else {
10133 self.active_diagnostics = Some(active_diagnostics);
10134 }
10135 }
10136
10137 self.scrollbar_marker_state.dirty = true;
10138 }
10139 }
10140
10141 pub fn unfold_ranges<T: ToOffset + Clone>(
10142 &mut self,
10143 ranges: impl IntoIterator<Item = Range<T>>,
10144 inclusive: bool,
10145 auto_scroll: bool,
10146 cx: &mut ViewContext<Self>,
10147 ) {
10148 let mut unfold_ranges = Vec::new();
10149 let mut buffers_affected = HashMap::default();
10150 let multi_buffer = self.buffer().read(cx);
10151 for range in ranges {
10152 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10153 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10154 };
10155 unfold_ranges.push(range);
10156 }
10157
10158 let mut ranges = unfold_ranges.into_iter().peekable();
10159 if ranges.peek().is_some() {
10160 self.display_map
10161 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10162 if auto_scroll {
10163 self.request_autoscroll(Autoscroll::fit(), cx);
10164 }
10165
10166 for buffer in buffers_affected.into_values() {
10167 self.sync_expanded_diff_hunks(buffer, cx);
10168 }
10169
10170 cx.notify();
10171 self.scrollbar_marker_state.dirty = true;
10172 self.active_indent_guides_state.dirty = true;
10173 }
10174 }
10175
10176 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10177 if hovered != self.gutter_hovered {
10178 self.gutter_hovered = hovered;
10179 cx.notify();
10180 }
10181 }
10182
10183 pub fn insert_blocks(
10184 &mut self,
10185 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10186 autoscroll: Option<Autoscroll>,
10187 cx: &mut ViewContext<Self>,
10188 ) -> Vec<CustomBlockId> {
10189 let blocks = self
10190 .display_map
10191 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10192 if let Some(autoscroll) = autoscroll {
10193 self.request_autoscroll(autoscroll, cx);
10194 }
10195 blocks
10196 }
10197
10198 pub fn replace_blocks(
10199 &mut self,
10200 blocks: HashMap<CustomBlockId, (Option<u8>, RenderBlock)>,
10201 autoscroll: Option<Autoscroll>,
10202 cx: &mut ViewContext<Self>,
10203 ) {
10204 self.display_map
10205 .update(cx, |display_map, cx| display_map.replace_blocks(blocks, cx));
10206 if let Some(autoscroll) = autoscroll {
10207 self.request_autoscroll(autoscroll, cx);
10208 }
10209 }
10210
10211 pub fn remove_blocks(
10212 &mut self,
10213 block_ids: HashSet<CustomBlockId>,
10214 autoscroll: Option<Autoscroll>,
10215 cx: &mut ViewContext<Self>,
10216 ) {
10217 self.display_map.update(cx, |display_map, cx| {
10218 display_map.remove_blocks(block_ids, cx)
10219 });
10220 if let Some(autoscroll) = autoscroll {
10221 self.request_autoscroll(autoscroll, cx);
10222 }
10223 }
10224
10225 pub fn row_for_block(
10226 &self,
10227 block_id: CustomBlockId,
10228 cx: &mut ViewContext<Self>,
10229 ) -> Option<DisplayRow> {
10230 self.display_map
10231 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10232 }
10233
10234 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10235 self.focused_block = Some(focused_block);
10236 }
10237
10238 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10239 self.focused_block.take()
10240 }
10241
10242 pub fn insert_creases(
10243 &mut self,
10244 creases: impl IntoIterator<Item = Crease>,
10245 cx: &mut ViewContext<Self>,
10246 ) -> Vec<CreaseId> {
10247 self.display_map
10248 .update(cx, |map, cx| map.insert_creases(creases, cx))
10249 }
10250
10251 pub fn remove_creases(
10252 &mut self,
10253 ids: impl IntoIterator<Item = CreaseId>,
10254 cx: &mut ViewContext<Self>,
10255 ) {
10256 self.display_map
10257 .update(cx, |map, cx| map.remove_creases(ids, cx));
10258 }
10259
10260 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10261 self.display_map
10262 .update(cx, |map, cx| map.snapshot(cx))
10263 .longest_row()
10264 }
10265
10266 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10267 self.display_map
10268 .update(cx, |map, cx| map.snapshot(cx))
10269 .max_point()
10270 }
10271
10272 pub fn text(&self, cx: &AppContext) -> String {
10273 self.buffer.read(cx).read(cx).text()
10274 }
10275
10276 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10277 let text = self.text(cx);
10278 let text = text.trim();
10279
10280 if text.is_empty() {
10281 return None;
10282 }
10283
10284 Some(text.to_string())
10285 }
10286
10287 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10288 self.transact(cx, |this, cx| {
10289 this.buffer
10290 .read(cx)
10291 .as_singleton()
10292 .expect("you can only call set_text on editors for singleton buffers")
10293 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10294 });
10295 }
10296
10297 pub fn display_text(&self, cx: &mut AppContext) -> String {
10298 self.display_map
10299 .update(cx, |map, cx| map.snapshot(cx))
10300 .text()
10301 }
10302
10303 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10304 let mut wrap_guides = smallvec::smallvec![];
10305
10306 if self.show_wrap_guides == Some(false) {
10307 return wrap_guides;
10308 }
10309
10310 let settings = self.buffer.read(cx).settings_at(0, cx);
10311 if settings.show_wrap_guides {
10312 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10313 wrap_guides.push((soft_wrap as usize, true));
10314 }
10315 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10316 }
10317
10318 wrap_guides
10319 }
10320
10321 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10322 let settings = self.buffer.read(cx).settings_at(0, cx);
10323 let mode = self
10324 .soft_wrap_mode_override
10325 .unwrap_or_else(|| settings.soft_wrap);
10326 match mode {
10327 language_settings::SoftWrap::None => SoftWrap::None,
10328 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10329 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10330 language_settings::SoftWrap::PreferredLineLength => {
10331 SoftWrap::Column(settings.preferred_line_length)
10332 }
10333 }
10334 }
10335
10336 pub fn set_soft_wrap_mode(
10337 &mut self,
10338 mode: language_settings::SoftWrap,
10339 cx: &mut ViewContext<Self>,
10340 ) {
10341 self.soft_wrap_mode_override = Some(mode);
10342 cx.notify();
10343 }
10344
10345 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10346 let rem_size = cx.rem_size();
10347 self.display_map.update(cx, |map, cx| {
10348 map.set_font(
10349 style.text.font(),
10350 style.text.font_size.to_pixels(rem_size),
10351 cx,
10352 )
10353 });
10354 self.style = Some(style);
10355 }
10356
10357 pub fn style(&self) -> Option<&EditorStyle> {
10358 self.style.as_ref()
10359 }
10360
10361 // Called by the element. This method is not designed to be called outside of the editor
10362 // element's layout code because it does not notify when rewrapping is computed synchronously.
10363 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10364 self.display_map
10365 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10366 }
10367
10368 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10369 if self.soft_wrap_mode_override.is_some() {
10370 self.soft_wrap_mode_override.take();
10371 } else {
10372 let soft_wrap = match self.soft_wrap_mode(cx) {
10373 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10374 SoftWrap::EditorWidth | SoftWrap::Column(_) => {
10375 language_settings::SoftWrap::PreferLine
10376 }
10377 };
10378 self.soft_wrap_mode_override = Some(soft_wrap);
10379 }
10380 cx.notify();
10381 }
10382
10383 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10384 let Some(workspace) = self.workspace() else {
10385 return;
10386 };
10387 let fs = workspace.read(cx).app_state().fs.clone();
10388 let current_show = TabBarSettings::get_global(cx).show;
10389 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10390 setting.show = Some(!current_show);
10391 });
10392 }
10393
10394 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10395 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10396 self.buffer
10397 .read(cx)
10398 .settings_at(0, cx)
10399 .indent_guides
10400 .enabled
10401 });
10402 self.show_indent_guides = Some(!currently_enabled);
10403 cx.notify();
10404 }
10405
10406 fn should_show_indent_guides(&self) -> Option<bool> {
10407 self.show_indent_guides
10408 }
10409
10410 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10411 let mut editor_settings = EditorSettings::get_global(cx).clone();
10412 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10413 EditorSettings::override_global(editor_settings, cx);
10414 }
10415
10416 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10417 self.show_gutter = show_gutter;
10418 cx.notify();
10419 }
10420
10421 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10422 self.show_line_numbers = Some(show_line_numbers);
10423 cx.notify();
10424 }
10425
10426 pub fn set_show_git_diff_gutter(
10427 &mut self,
10428 show_git_diff_gutter: bool,
10429 cx: &mut ViewContext<Self>,
10430 ) {
10431 self.show_git_diff_gutter = Some(show_git_diff_gutter);
10432 cx.notify();
10433 }
10434
10435 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10436 self.show_code_actions = Some(show_code_actions);
10437 cx.notify();
10438 }
10439
10440 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10441 self.show_runnables = Some(show_runnables);
10442 cx.notify();
10443 }
10444
10445 pub fn set_redact_all(&mut self, redact_all: bool, cx: &mut ViewContext<Self>) {
10446 self.redact_all = redact_all;
10447 cx.notify();
10448 }
10449
10450 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10451 self.show_wrap_guides = Some(show_wrap_guides);
10452 cx.notify();
10453 }
10454
10455 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10456 self.show_indent_guides = Some(show_indent_guides);
10457 cx.notify();
10458 }
10459
10460 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10461 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10462 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10463 if let Some(dir) = file.abs_path(cx).parent() {
10464 return Some(dir.to_owned());
10465 }
10466 }
10467
10468 if let Some(project_path) = buffer.read(cx).project_path(cx) {
10469 return Some(project_path.path.to_path_buf());
10470 }
10471 }
10472
10473 None
10474 }
10475
10476 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10477 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10478 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10479 cx.reveal_path(&file.abs_path(cx));
10480 }
10481 }
10482 }
10483
10484 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10485 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10486 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10487 if let Some(path) = file.abs_path(cx).to_str() {
10488 cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10489 }
10490 }
10491 }
10492 }
10493
10494 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10495 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10496 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10497 if let Some(path) = file.path().to_str() {
10498 cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10499 }
10500 }
10501 }
10502 }
10503
10504 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10505 self.show_git_blame_gutter = !self.show_git_blame_gutter;
10506
10507 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10508 self.start_git_blame(true, cx);
10509 }
10510
10511 cx.notify();
10512 }
10513
10514 pub fn toggle_git_blame_inline(
10515 &mut self,
10516 _: &ToggleGitBlameInline,
10517 cx: &mut ViewContext<Self>,
10518 ) {
10519 self.toggle_git_blame_inline_internal(true, cx);
10520 cx.notify();
10521 }
10522
10523 pub fn git_blame_inline_enabled(&self) -> bool {
10524 self.git_blame_inline_enabled
10525 }
10526
10527 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10528 self.show_selection_menu = self
10529 .show_selection_menu
10530 .map(|show_selections_menu| !show_selections_menu)
10531 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10532
10533 cx.notify();
10534 }
10535
10536 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10537 self.show_selection_menu
10538 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10539 }
10540
10541 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10542 if let Some(project) = self.project.as_ref() {
10543 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10544 return;
10545 };
10546
10547 if buffer.read(cx).file().is_none() {
10548 return;
10549 }
10550
10551 let focused = self.focus_handle(cx).contains_focused(cx);
10552
10553 let project = project.clone();
10554 let blame =
10555 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10556 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10557 self.blame = Some(blame);
10558 }
10559 }
10560
10561 fn toggle_git_blame_inline_internal(
10562 &mut self,
10563 user_triggered: bool,
10564 cx: &mut ViewContext<Self>,
10565 ) {
10566 if self.git_blame_inline_enabled {
10567 self.git_blame_inline_enabled = false;
10568 self.show_git_blame_inline = false;
10569 self.show_git_blame_inline_delay_task.take();
10570 } else {
10571 self.git_blame_inline_enabled = true;
10572 self.start_git_blame_inline(user_triggered, cx);
10573 }
10574
10575 cx.notify();
10576 }
10577
10578 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10579 self.start_git_blame(user_triggered, cx);
10580
10581 if ProjectSettings::get_global(cx)
10582 .git
10583 .inline_blame_delay()
10584 .is_some()
10585 {
10586 self.start_inline_blame_timer(cx);
10587 } else {
10588 self.show_git_blame_inline = true
10589 }
10590 }
10591
10592 pub fn blame(&self) -> Option<&Model<GitBlame>> {
10593 self.blame.as_ref()
10594 }
10595
10596 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10597 self.show_git_blame_gutter && self.has_blame_entries(cx)
10598 }
10599
10600 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10601 self.show_git_blame_inline
10602 && self.focus_handle.is_focused(cx)
10603 && !self.newest_selection_head_on_empty_line(cx)
10604 && self.has_blame_entries(cx)
10605 }
10606
10607 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10608 self.blame()
10609 .map_or(false, |blame| blame.read(cx).has_generated_entries())
10610 }
10611
10612 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10613 let cursor_anchor = self.selections.newest_anchor().head();
10614
10615 let snapshot = self.buffer.read(cx).snapshot(cx);
10616 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10617
10618 snapshot.line_len(buffer_row) == 0
10619 }
10620
10621 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10622 let (path, selection, repo) = maybe!({
10623 let project_handle = self.project.as_ref()?.clone();
10624 let project = project_handle.read(cx);
10625
10626 let selection = self.selections.newest::<Point>(cx);
10627 let selection_range = selection.range();
10628
10629 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10630 (buffer, selection_range.start.row..selection_range.end.row)
10631 } else {
10632 let buffer_ranges = self
10633 .buffer()
10634 .read(cx)
10635 .range_to_buffer_ranges(selection_range, cx);
10636
10637 let (buffer, range, _) = if selection.reversed {
10638 buffer_ranges.first()
10639 } else {
10640 buffer_ranges.last()
10641 }?;
10642
10643 let snapshot = buffer.read(cx).snapshot();
10644 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10645 ..text::ToPoint::to_point(&range.end, &snapshot).row;
10646 (buffer.clone(), selection)
10647 };
10648
10649 let path = buffer
10650 .read(cx)
10651 .file()?
10652 .as_local()?
10653 .path()
10654 .to_str()?
10655 .to_string();
10656 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10657 Some((path, selection, repo))
10658 })
10659 .ok_or_else(|| anyhow!("unable to open git repository"))?;
10660
10661 const REMOTE_NAME: &str = "origin";
10662 let origin_url = repo
10663 .remote_url(REMOTE_NAME)
10664 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10665 let sha = repo
10666 .head_sha()
10667 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10668
10669 let (provider, remote) =
10670 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10671 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10672
10673 Ok(provider.build_permalink(
10674 remote,
10675 BuildPermalinkParams {
10676 sha: &sha,
10677 path: &path,
10678 selection: Some(selection),
10679 },
10680 ))
10681 }
10682
10683 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10684 let permalink = self.get_permalink_to_line(cx);
10685
10686 match permalink {
10687 Ok(permalink) => {
10688 cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
10689 }
10690 Err(err) => {
10691 let message = format!("Failed to copy permalink: {err}");
10692
10693 Err::<(), anyhow::Error>(err).log_err();
10694
10695 if let Some(workspace) = self.workspace() {
10696 workspace.update(cx, |workspace, cx| {
10697 struct CopyPermalinkToLine;
10698
10699 workspace.show_toast(
10700 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10701 cx,
10702 )
10703 })
10704 }
10705 }
10706 }
10707 }
10708
10709 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10710 let permalink = self.get_permalink_to_line(cx);
10711
10712 match permalink {
10713 Ok(permalink) => {
10714 cx.open_url(permalink.as_ref());
10715 }
10716 Err(err) => {
10717 let message = format!("Failed to open permalink: {err}");
10718
10719 Err::<(), anyhow::Error>(err).log_err();
10720
10721 if let Some(workspace) = self.workspace() {
10722 workspace.update(cx, |workspace, cx| {
10723 struct OpenPermalinkToLine;
10724
10725 workspace.show_toast(
10726 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
10727 cx,
10728 )
10729 })
10730 }
10731 }
10732 }
10733 }
10734
10735 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
10736 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
10737 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
10738 pub fn highlight_rows<T: 'static>(
10739 &mut self,
10740 rows: RangeInclusive<Anchor>,
10741 color: Option<Hsla>,
10742 should_autoscroll: bool,
10743 cx: &mut ViewContext<Self>,
10744 ) {
10745 let snapshot = self.buffer().read(cx).snapshot(cx);
10746 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
10747 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
10748 highlight
10749 .range
10750 .start()
10751 .cmp(&rows.start(), &snapshot)
10752 .then(highlight.range.end().cmp(&rows.end(), &snapshot))
10753 });
10754 match (color, existing_highlight_index) {
10755 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
10756 ix,
10757 RowHighlight {
10758 index: post_inc(&mut self.highlight_order),
10759 range: rows,
10760 should_autoscroll,
10761 color,
10762 },
10763 ),
10764 (None, Ok(i)) => {
10765 row_highlights.remove(i);
10766 }
10767 }
10768 }
10769
10770 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
10771 pub fn clear_row_highlights<T: 'static>(&mut self) {
10772 self.highlighted_rows.remove(&TypeId::of::<T>());
10773 }
10774
10775 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
10776 pub fn highlighted_rows<T: 'static>(
10777 &self,
10778 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
10779 Some(
10780 self.highlighted_rows
10781 .get(&TypeId::of::<T>())?
10782 .iter()
10783 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
10784 )
10785 }
10786
10787 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
10788 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
10789 /// Allows to ignore certain kinds of highlights.
10790 pub fn highlighted_display_rows(
10791 &mut self,
10792 cx: &mut WindowContext,
10793 ) -> BTreeMap<DisplayRow, Hsla> {
10794 let snapshot = self.snapshot(cx);
10795 let mut used_highlight_orders = HashMap::default();
10796 self.highlighted_rows
10797 .iter()
10798 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
10799 .fold(
10800 BTreeMap::<DisplayRow, Hsla>::new(),
10801 |mut unique_rows, highlight| {
10802 let start_row = highlight.range.start().to_display_point(&snapshot).row();
10803 let end_row = highlight.range.end().to_display_point(&snapshot).row();
10804 for row in start_row.0..=end_row.0 {
10805 let used_index =
10806 used_highlight_orders.entry(row).or_insert(highlight.index);
10807 if highlight.index >= *used_index {
10808 *used_index = highlight.index;
10809 match highlight.color {
10810 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
10811 None => unique_rows.remove(&DisplayRow(row)),
10812 };
10813 }
10814 }
10815 unique_rows
10816 },
10817 )
10818 }
10819
10820 pub fn highlighted_display_row_for_autoscroll(
10821 &self,
10822 snapshot: &DisplaySnapshot,
10823 ) -> Option<DisplayRow> {
10824 self.highlighted_rows
10825 .values()
10826 .flat_map(|highlighted_rows| highlighted_rows.iter())
10827 .filter_map(|highlight| {
10828 if highlight.color.is_none() || !highlight.should_autoscroll {
10829 return None;
10830 }
10831 Some(highlight.range.start().to_display_point(&snapshot).row())
10832 })
10833 .min()
10834 }
10835
10836 pub fn set_search_within_ranges(
10837 &mut self,
10838 ranges: &[Range<Anchor>],
10839 cx: &mut ViewContext<Self>,
10840 ) {
10841 self.highlight_background::<SearchWithinRange>(
10842 ranges,
10843 |colors| colors.editor_document_highlight_read_background,
10844 cx,
10845 )
10846 }
10847
10848 pub fn set_breadcrumb_header(&mut self, new_header: String) {
10849 self.breadcrumb_header = Some(new_header);
10850 }
10851
10852 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
10853 self.clear_background_highlights::<SearchWithinRange>(cx);
10854 }
10855
10856 pub fn highlight_background<T: 'static>(
10857 &mut self,
10858 ranges: &[Range<Anchor>],
10859 color_fetcher: fn(&ThemeColors) -> Hsla,
10860 cx: &mut ViewContext<Self>,
10861 ) {
10862 self.background_highlights
10863 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10864 self.scrollbar_marker_state.dirty = true;
10865 cx.notify();
10866 }
10867
10868 pub fn clear_background_highlights<T: 'static>(
10869 &mut self,
10870 cx: &mut ViewContext<Self>,
10871 ) -> Option<BackgroundHighlight> {
10872 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
10873 if !text_highlights.1.is_empty() {
10874 self.scrollbar_marker_state.dirty = true;
10875 cx.notify();
10876 }
10877 Some(text_highlights)
10878 }
10879
10880 pub fn highlight_gutter<T: 'static>(
10881 &mut self,
10882 ranges: &[Range<Anchor>],
10883 color_fetcher: fn(&AppContext) -> Hsla,
10884 cx: &mut ViewContext<Self>,
10885 ) {
10886 self.gutter_highlights
10887 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10888 cx.notify();
10889 }
10890
10891 pub fn clear_gutter_highlights<T: 'static>(
10892 &mut self,
10893 cx: &mut ViewContext<Self>,
10894 ) -> Option<GutterHighlight> {
10895 cx.notify();
10896 self.gutter_highlights.remove(&TypeId::of::<T>())
10897 }
10898
10899 #[cfg(feature = "test-support")]
10900 pub fn all_text_background_highlights(
10901 &mut self,
10902 cx: &mut ViewContext<Self>,
10903 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10904 let snapshot = self.snapshot(cx);
10905 let buffer = &snapshot.buffer_snapshot;
10906 let start = buffer.anchor_before(0);
10907 let end = buffer.anchor_after(buffer.len());
10908 let theme = cx.theme().colors();
10909 self.background_highlights_in_range(start..end, &snapshot, theme)
10910 }
10911
10912 #[cfg(feature = "test-support")]
10913 pub fn search_background_highlights(
10914 &mut self,
10915 cx: &mut ViewContext<Self>,
10916 ) -> Vec<Range<Point>> {
10917 let snapshot = self.buffer().read(cx).snapshot(cx);
10918
10919 let highlights = self
10920 .background_highlights
10921 .get(&TypeId::of::<items::BufferSearchHighlights>());
10922
10923 if let Some((_color, ranges)) = highlights {
10924 ranges
10925 .iter()
10926 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
10927 .collect_vec()
10928 } else {
10929 vec![]
10930 }
10931 }
10932
10933 fn document_highlights_for_position<'a>(
10934 &'a self,
10935 position: Anchor,
10936 buffer: &'a MultiBufferSnapshot,
10937 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
10938 let read_highlights = self
10939 .background_highlights
10940 .get(&TypeId::of::<DocumentHighlightRead>())
10941 .map(|h| &h.1);
10942 let write_highlights = self
10943 .background_highlights
10944 .get(&TypeId::of::<DocumentHighlightWrite>())
10945 .map(|h| &h.1);
10946 let left_position = position.bias_left(buffer);
10947 let right_position = position.bias_right(buffer);
10948 read_highlights
10949 .into_iter()
10950 .chain(write_highlights)
10951 .flat_map(move |ranges| {
10952 let start_ix = match ranges.binary_search_by(|probe| {
10953 let cmp = probe.end.cmp(&left_position, buffer);
10954 if cmp.is_ge() {
10955 Ordering::Greater
10956 } else {
10957 Ordering::Less
10958 }
10959 }) {
10960 Ok(i) | Err(i) => i,
10961 };
10962
10963 ranges[start_ix..]
10964 .iter()
10965 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
10966 })
10967 }
10968
10969 pub fn has_background_highlights<T: 'static>(&self) -> bool {
10970 self.background_highlights
10971 .get(&TypeId::of::<T>())
10972 .map_or(false, |(_, highlights)| !highlights.is_empty())
10973 }
10974
10975 pub fn background_highlights_in_range(
10976 &self,
10977 search_range: Range<Anchor>,
10978 display_snapshot: &DisplaySnapshot,
10979 theme: &ThemeColors,
10980 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10981 let mut results = Vec::new();
10982 for (color_fetcher, ranges) in self.background_highlights.values() {
10983 let color = color_fetcher(theme);
10984 let start_ix = match ranges.binary_search_by(|probe| {
10985 let cmp = probe
10986 .end
10987 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10988 if cmp.is_gt() {
10989 Ordering::Greater
10990 } else {
10991 Ordering::Less
10992 }
10993 }) {
10994 Ok(i) | Err(i) => i,
10995 };
10996 for range in &ranges[start_ix..] {
10997 if range
10998 .start
10999 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11000 .is_ge()
11001 {
11002 break;
11003 }
11004
11005 let start = range.start.to_display_point(&display_snapshot);
11006 let end = range.end.to_display_point(&display_snapshot);
11007 results.push((start..end, color))
11008 }
11009 }
11010 results
11011 }
11012
11013 pub fn background_highlight_row_ranges<T: 'static>(
11014 &self,
11015 search_range: Range<Anchor>,
11016 display_snapshot: &DisplaySnapshot,
11017 count: usize,
11018 ) -> Vec<RangeInclusive<DisplayPoint>> {
11019 let mut results = Vec::new();
11020 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11021 return vec![];
11022 };
11023
11024 let start_ix = match ranges.binary_search_by(|probe| {
11025 let cmp = probe
11026 .end
11027 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11028 if cmp.is_gt() {
11029 Ordering::Greater
11030 } else {
11031 Ordering::Less
11032 }
11033 }) {
11034 Ok(i) | Err(i) => i,
11035 };
11036 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11037 if let (Some(start_display), Some(end_display)) = (start, end) {
11038 results.push(
11039 start_display.to_display_point(display_snapshot)
11040 ..=end_display.to_display_point(display_snapshot),
11041 );
11042 }
11043 };
11044 let mut start_row: Option<Point> = None;
11045 let mut end_row: Option<Point> = None;
11046 if ranges.len() > count {
11047 return Vec::new();
11048 }
11049 for range in &ranges[start_ix..] {
11050 if range
11051 .start
11052 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11053 .is_ge()
11054 {
11055 break;
11056 }
11057 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11058 if let Some(current_row) = &end_row {
11059 if end.row == current_row.row {
11060 continue;
11061 }
11062 }
11063 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11064 if start_row.is_none() {
11065 assert_eq!(end_row, None);
11066 start_row = Some(start);
11067 end_row = Some(end);
11068 continue;
11069 }
11070 if let Some(current_end) = end_row.as_mut() {
11071 if start.row > current_end.row + 1 {
11072 push_region(start_row, end_row);
11073 start_row = Some(start);
11074 end_row = Some(end);
11075 } else {
11076 // Merge two hunks.
11077 *current_end = end;
11078 }
11079 } else {
11080 unreachable!();
11081 }
11082 }
11083 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11084 push_region(start_row, end_row);
11085 results
11086 }
11087
11088 pub fn gutter_highlights_in_range(
11089 &self,
11090 search_range: Range<Anchor>,
11091 display_snapshot: &DisplaySnapshot,
11092 cx: &AppContext,
11093 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11094 let mut results = Vec::new();
11095 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11096 let color = color_fetcher(cx);
11097 let start_ix = match ranges.binary_search_by(|probe| {
11098 let cmp = probe
11099 .end
11100 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11101 if cmp.is_gt() {
11102 Ordering::Greater
11103 } else {
11104 Ordering::Less
11105 }
11106 }) {
11107 Ok(i) | Err(i) => i,
11108 };
11109 for range in &ranges[start_ix..] {
11110 if range
11111 .start
11112 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11113 .is_ge()
11114 {
11115 break;
11116 }
11117
11118 let start = range.start.to_display_point(&display_snapshot);
11119 let end = range.end.to_display_point(&display_snapshot);
11120 results.push((start..end, color))
11121 }
11122 }
11123 results
11124 }
11125
11126 /// Get the text ranges corresponding to the redaction query
11127 pub fn redacted_ranges(
11128 &self,
11129 search_range: Range<Anchor>,
11130 display_snapshot: &DisplaySnapshot,
11131 cx: &WindowContext,
11132 ) -> Vec<Range<DisplayPoint>> {
11133 if self.redact_all {
11134 return vec![DisplayPoint::zero()..display_snapshot.max_point()];
11135 }
11136
11137 display_snapshot
11138 .buffer_snapshot
11139 .redacted_ranges(search_range, |file| {
11140 if let Some(file) = file {
11141 file.is_private()
11142 && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
11143 } else {
11144 false
11145 }
11146 })
11147 .map(|range| {
11148 range.start.to_display_point(display_snapshot)
11149 ..range.end.to_display_point(display_snapshot)
11150 })
11151 .collect()
11152 }
11153
11154 pub fn highlight_text<T: 'static>(
11155 &mut self,
11156 ranges: Vec<Range<Anchor>>,
11157 style: HighlightStyle,
11158 cx: &mut ViewContext<Self>,
11159 ) {
11160 self.display_map.update(cx, |map, _| {
11161 map.highlight_text(TypeId::of::<T>(), ranges, style)
11162 });
11163 cx.notify();
11164 }
11165
11166 pub(crate) fn highlight_inlays<T: 'static>(
11167 &mut self,
11168 highlights: Vec<InlayHighlight>,
11169 style: HighlightStyle,
11170 cx: &mut ViewContext<Self>,
11171 ) {
11172 self.display_map.update(cx, |map, _| {
11173 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11174 });
11175 cx.notify();
11176 }
11177
11178 pub fn text_highlights<'a, T: 'static>(
11179 &'a self,
11180 cx: &'a AppContext,
11181 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11182 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11183 }
11184
11185 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11186 let cleared = self
11187 .display_map
11188 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11189 if cleared {
11190 cx.notify();
11191 }
11192 }
11193
11194 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11195 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11196 && self.focus_handle.is_focused(cx)
11197 }
11198
11199 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11200 self.show_cursor_when_unfocused = is_enabled;
11201 cx.notify();
11202 }
11203
11204 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11205 cx.notify();
11206 }
11207
11208 fn on_buffer_event(
11209 &mut self,
11210 multibuffer: Model<MultiBuffer>,
11211 event: &multi_buffer::Event,
11212 cx: &mut ViewContext<Self>,
11213 ) {
11214 match event {
11215 multi_buffer::Event::Edited {
11216 singleton_buffer_edited,
11217 } => {
11218 self.scrollbar_marker_state.dirty = true;
11219 self.active_indent_guides_state.dirty = true;
11220 self.refresh_active_diagnostics(cx);
11221 self.refresh_code_actions(cx);
11222 if self.has_active_inline_completion(cx) {
11223 self.update_visible_inline_completion(cx);
11224 }
11225 cx.emit(EditorEvent::BufferEdited);
11226 cx.emit(SearchEvent::MatchesInvalidated);
11227 if *singleton_buffer_edited {
11228 if let Some(project) = &self.project {
11229 let project = project.read(cx);
11230 #[allow(clippy::mutable_key_type)]
11231 let languages_affected = multibuffer
11232 .read(cx)
11233 .all_buffers()
11234 .into_iter()
11235 .filter_map(|buffer| {
11236 let buffer = buffer.read(cx);
11237 let language = buffer.language()?;
11238 if project.is_local()
11239 && project.language_servers_for_buffer(buffer, cx).count() == 0
11240 {
11241 None
11242 } else {
11243 Some(language)
11244 }
11245 })
11246 .cloned()
11247 .collect::<HashSet<_>>();
11248 if !languages_affected.is_empty() {
11249 self.refresh_inlay_hints(
11250 InlayHintRefreshReason::BufferEdited(languages_affected),
11251 cx,
11252 );
11253 }
11254 }
11255 }
11256
11257 let Some(project) = &self.project else { return };
11258 let telemetry = project.read(cx).client().telemetry().clone();
11259 refresh_linked_ranges(self, cx);
11260 telemetry.log_edit_event("editor");
11261 }
11262 multi_buffer::Event::ExcerptsAdded {
11263 buffer,
11264 predecessor,
11265 excerpts,
11266 } => {
11267 self.tasks_update_task = Some(self.refresh_runnables(cx));
11268 cx.emit(EditorEvent::ExcerptsAdded {
11269 buffer: buffer.clone(),
11270 predecessor: *predecessor,
11271 excerpts: excerpts.clone(),
11272 });
11273 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11274 }
11275 multi_buffer::Event::ExcerptsRemoved { ids } => {
11276 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11277 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11278 }
11279 multi_buffer::Event::ExcerptsEdited { ids } => {
11280 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11281 }
11282 multi_buffer::Event::ExcerptsExpanded { ids } => {
11283 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11284 }
11285 multi_buffer::Event::Reparsed(buffer_id) => {
11286 self.tasks_update_task = Some(self.refresh_runnables(cx));
11287
11288 cx.emit(EditorEvent::Reparsed(*buffer_id));
11289 }
11290 multi_buffer::Event::LanguageChanged(buffer_id) => {
11291 linked_editing_ranges::refresh_linked_ranges(self, cx);
11292 cx.emit(EditorEvent::Reparsed(*buffer_id));
11293 cx.notify();
11294 }
11295 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11296 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11297 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11298 cx.emit(EditorEvent::TitleChanged)
11299 }
11300 multi_buffer::Event::DiffBaseChanged => {
11301 self.scrollbar_marker_state.dirty = true;
11302 cx.emit(EditorEvent::DiffBaseChanged);
11303 cx.notify();
11304 }
11305 multi_buffer::Event::DiffUpdated { buffer } => {
11306 self.sync_expanded_diff_hunks(buffer.clone(), cx);
11307 cx.notify();
11308 }
11309 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11310 multi_buffer::Event::DiagnosticsUpdated => {
11311 self.refresh_active_diagnostics(cx);
11312 self.scrollbar_marker_state.dirty = true;
11313 cx.notify();
11314 }
11315 _ => {}
11316 };
11317 }
11318
11319 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11320 cx.notify();
11321 }
11322
11323 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11324 self.tasks_update_task = Some(self.refresh_runnables(cx));
11325 self.refresh_inline_completion(true, cx);
11326 self.refresh_inlay_hints(
11327 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11328 self.selections.newest_anchor().head(),
11329 &self.buffer.read(cx).snapshot(cx),
11330 cx,
11331 )),
11332 cx,
11333 );
11334 let editor_settings = EditorSettings::get_global(cx);
11335 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11336 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11337
11338 let project_settings = ProjectSettings::get_global(cx);
11339 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11340
11341 if self.mode == EditorMode::Full {
11342 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11343 if self.git_blame_inline_enabled != inline_blame_enabled {
11344 self.toggle_git_blame_inline_internal(false, cx);
11345 }
11346 }
11347
11348 cx.notify();
11349 }
11350
11351 pub fn set_searchable(&mut self, searchable: bool) {
11352 self.searchable = searchable;
11353 }
11354
11355 pub fn searchable(&self) -> bool {
11356 self.searchable
11357 }
11358
11359 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11360 self.open_excerpts_common(true, cx)
11361 }
11362
11363 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11364 self.open_excerpts_common(false, cx)
11365 }
11366
11367 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11368 let buffer = self.buffer.read(cx);
11369 if buffer.is_singleton() {
11370 cx.propagate();
11371 return;
11372 }
11373
11374 let Some(workspace) = self.workspace() else {
11375 cx.propagate();
11376 return;
11377 };
11378
11379 let mut new_selections_by_buffer = HashMap::default();
11380 for selection in self.selections.all::<usize>(cx) {
11381 for (buffer, mut range, _) in
11382 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11383 {
11384 if selection.reversed {
11385 mem::swap(&mut range.start, &mut range.end);
11386 }
11387 new_selections_by_buffer
11388 .entry(buffer)
11389 .or_insert(Vec::new())
11390 .push(range)
11391 }
11392 }
11393
11394 // We defer the pane interaction because we ourselves are a workspace item
11395 // and activating a new item causes the pane to call a method on us reentrantly,
11396 // which panics if we're on the stack.
11397 cx.window_context().defer(move |cx| {
11398 workspace.update(cx, |workspace, cx| {
11399 let pane = if split {
11400 workspace.adjacent_pane(cx)
11401 } else {
11402 workspace.active_pane().clone()
11403 };
11404
11405 for (buffer, ranges) in new_selections_by_buffer {
11406 let editor =
11407 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
11408 editor.update(cx, |editor, cx| {
11409 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11410 s.select_ranges(ranges);
11411 });
11412 });
11413 }
11414 })
11415 });
11416 }
11417
11418 fn jump(
11419 &mut self,
11420 path: ProjectPath,
11421 position: Point,
11422 anchor: language::Anchor,
11423 offset_from_top: u32,
11424 cx: &mut ViewContext<Self>,
11425 ) {
11426 let workspace = self.workspace();
11427 cx.spawn(|_, mut cx| async move {
11428 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11429 let editor = workspace.update(&mut cx, |workspace, cx| {
11430 // Reset the preview item id before opening the new item
11431 workspace.active_pane().update(cx, |pane, cx| {
11432 pane.set_preview_item_id(None, cx);
11433 });
11434 workspace.open_path_preview(path, None, true, true, cx)
11435 })?;
11436 let editor = editor
11437 .await?
11438 .downcast::<Editor>()
11439 .ok_or_else(|| anyhow!("opened item was not an editor"))?
11440 .downgrade();
11441 editor.update(&mut cx, |editor, cx| {
11442 let buffer = editor
11443 .buffer()
11444 .read(cx)
11445 .as_singleton()
11446 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11447 let buffer = buffer.read(cx);
11448 let cursor = if buffer.can_resolve(&anchor) {
11449 language::ToPoint::to_point(&anchor, buffer)
11450 } else {
11451 buffer.clip_point(position, Bias::Left)
11452 };
11453
11454 let nav_history = editor.nav_history.take();
11455 editor.change_selections(
11456 Some(Autoscroll::top_relative(offset_from_top as usize)),
11457 cx,
11458 |s| {
11459 s.select_ranges([cursor..cursor]);
11460 },
11461 );
11462 editor.nav_history = nav_history;
11463
11464 anyhow::Ok(())
11465 })??;
11466
11467 anyhow::Ok(())
11468 })
11469 .detach_and_log_err(cx);
11470 }
11471
11472 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11473 let snapshot = self.buffer.read(cx).read(cx);
11474 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11475 Some(
11476 ranges
11477 .iter()
11478 .map(move |range| {
11479 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11480 })
11481 .collect(),
11482 )
11483 }
11484
11485 fn selection_replacement_ranges(
11486 &self,
11487 range: Range<OffsetUtf16>,
11488 cx: &AppContext,
11489 ) -> Vec<Range<OffsetUtf16>> {
11490 let selections = self.selections.all::<OffsetUtf16>(cx);
11491 let newest_selection = selections
11492 .iter()
11493 .max_by_key(|selection| selection.id)
11494 .unwrap();
11495 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11496 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11497 let snapshot = self.buffer.read(cx).read(cx);
11498 selections
11499 .into_iter()
11500 .map(|mut selection| {
11501 selection.start.0 =
11502 (selection.start.0 as isize).saturating_add(start_delta) as usize;
11503 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11504 snapshot.clip_offset_utf16(selection.start, Bias::Left)
11505 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11506 })
11507 .collect()
11508 }
11509
11510 fn report_editor_event(
11511 &self,
11512 operation: &'static str,
11513 file_extension: Option<String>,
11514 cx: &AppContext,
11515 ) {
11516 if cfg!(any(test, feature = "test-support")) {
11517 return;
11518 }
11519
11520 let Some(project) = &self.project else { return };
11521
11522 // If None, we are in a file without an extension
11523 let file = self
11524 .buffer
11525 .read(cx)
11526 .as_singleton()
11527 .and_then(|b| b.read(cx).file());
11528 let file_extension = file_extension.or(file
11529 .as_ref()
11530 .and_then(|file| Path::new(file.file_name(cx)).extension())
11531 .and_then(|e| e.to_str())
11532 .map(|a| a.to_string()));
11533
11534 let vim_mode = cx
11535 .global::<SettingsStore>()
11536 .raw_user_settings()
11537 .get("vim_mode")
11538 == Some(&serde_json::Value::Bool(true));
11539
11540 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11541 == language::language_settings::InlineCompletionProvider::Copilot;
11542 let copilot_enabled_for_language = self
11543 .buffer
11544 .read(cx)
11545 .settings_at(0, cx)
11546 .show_inline_completions;
11547
11548 let telemetry = project.read(cx).client().telemetry().clone();
11549 telemetry.report_editor_event(
11550 file_extension,
11551 vim_mode,
11552 operation,
11553 copilot_enabled,
11554 copilot_enabled_for_language,
11555 )
11556 }
11557
11558 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11559 /// with each line being an array of {text, highlight} objects.
11560 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11561 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11562 return;
11563 };
11564
11565 #[derive(Serialize)]
11566 struct Chunk<'a> {
11567 text: String,
11568 highlight: Option<&'a str>,
11569 }
11570
11571 let snapshot = buffer.read(cx).snapshot();
11572 let range = self
11573 .selected_text_range(cx)
11574 .and_then(|selected_range| {
11575 if selected_range.is_empty() {
11576 None
11577 } else {
11578 Some(selected_range)
11579 }
11580 })
11581 .unwrap_or_else(|| 0..snapshot.len());
11582
11583 let chunks = snapshot.chunks(range, true);
11584 let mut lines = Vec::new();
11585 let mut line: VecDeque<Chunk> = VecDeque::new();
11586
11587 let Some(style) = self.style.as_ref() else {
11588 return;
11589 };
11590
11591 for chunk in chunks {
11592 let highlight = chunk
11593 .syntax_highlight_id
11594 .and_then(|id| id.name(&style.syntax));
11595 let mut chunk_lines = chunk.text.split('\n').peekable();
11596 while let Some(text) = chunk_lines.next() {
11597 let mut merged_with_last_token = false;
11598 if let Some(last_token) = line.back_mut() {
11599 if last_token.highlight == highlight {
11600 last_token.text.push_str(text);
11601 merged_with_last_token = true;
11602 }
11603 }
11604
11605 if !merged_with_last_token {
11606 line.push_back(Chunk {
11607 text: text.into(),
11608 highlight,
11609 });
11610 }
11611
11612 if chunk_lines.peek().is_some() {
11613 if line.len() > 1 && line.front().unwrap().text.is_empty() {
11614 line.pop_front();
11615 }
11616 if line.len() > 1 && line.back().unwrap().text.is_empty() {
11617 line.pop_back();
11618 }
11619
11620 lines.push(mem::take(&mut line));
11621 }
11622 }
11623 }
11624
11625 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11626 return;
11627 };
11628 cx.write_to_clipboard(ClipboardItem::new(lines));
11629 }
11630
11631 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11632 &self.inlay_hint_cache
11633 }
11634
11635 pub fn replay_insert_event(
11636 &mut self,
11637 text: &str,
11638 relative_utf16_range: Option<Range<isize>>,
11639 cx: &mut ViewContext<Self>,
11640 ) {
11641 if !self.input_enabled {
11642 cx.emit(EditorEvent::InputIgnored { text: text.into() });
11643 return;
11644 }
11645 if let Some(relative_utf16_range) = relative_utf16_range {
11646 let selections = self.selections.all::<OffsetUtf16>(cx);
11647 self.change_selections(None, cx, |s| {
11648 let new_ranges = selections.into_iter().map(|range| {
11649 let start = OffsetUtf16(
11650 range
11651 .head()
11652 .0
11653 .saturating_add_signed(relative_utf16_range.start),
11654 );
11655 let end = OffsetUtf16(
11656 range
11657 .head()
11658 .0
11659 .saturating_add_signed(relative_utf16_range.end),
11660 );
11661 start..end
11662 });
11663 s.select_ranges(new_ranges);
11664 });
11665 }
11666
11667 self.handle_input(text, cx);
11668 }
11669
11670 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11671 let Some(project) = self.project.as_ref() else {
11672 return false;
11673 };
11674 let project = project.read(cx);
11675
11676 let mut supports = false;
11677 self.buffer().read(cx).for_each_buffer(|buffer| {
11678 if !supports {
11679 supports = project
11680 .language_servers_for_buffer(buffer.read(cx), cx)
11681 .any(
11682 |(_, server)| match server.capabilities().inlay_hint_provider {
11683 Some(lsp::OneOf::Left(enabled)) => enabled,
11684 Some(lsp::OneOf::Right(_)) => true,
11685 None => false,
11686 },
11687 )
11688 }
11689 });
11690 supports
11691 }
11692
11693 pub fn focus(&self, cx: &mut WindowContext) {
11694 cx.focus(&self.focus_handle)
11695 }
11696
11697 pub fn is_focused(&self, cx: &WindowContext) -> bool {
11698 self.focus_handle.is_focused(cx)
11699 }
11700
11701 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11702 cx.emit(EditorEvent::Focused);
11703
11704 if let Some(descendant) = self
11705 .last_focused_descendant
11706 .take()
11707 .and_then(|descendant| descendant.upgrade())
11708 {
11709 cx.focus(&descendant);
11710 } else {
11711 if let Some(blame) = self.blame.as_ref() {
11712 blame.update(cx, GitBlame::focus)
11713 }
11714
11715 self.blink_manager.update(cx, BlinkManager::enable);
11716 self.show_cursor_names(cx);
11717 self.buffer.update(cx, |buffer, cx| {
11718 buffer.finalize_last_transaction(cx);
11719 if self.leader_peer_id.is_none() {
11720 buffer.set_active_selections(
11721 &self.selections.disjoint_anchors(),
11722 self.selections.line_mode,
11723 self.cursor_shape,
11724 cx,
11725 );
11726 }
11727 });
11728 }
11729 }
11730
11731 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
11732 cx.emit(EditorEvent::FocusedIn)
11733 }
11734
11735 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
11736 if event.blurred != self.focus_handle {
11737 self.last_focused_descendant = Some(event.blurred);
11738 }
11739 }
11740
11741 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
11742 self.blink_manager.update(cx, BlinkManager::disable);
11743 self.buffer
11744 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
11745
11746 if let Some(blame) = self.blame.as_ref() {
11747 blame.update(cx, GitBlame::blur)
11748 }
11749 if !self.hover_state.focused(cx) {
11750 hide_hover(self, cx);
11751 }
11752
11753 self.hide_context_menu(cx);
11754 cx.emit(EditorEvent::Blurred);
11755 cx.notify();
11756 }
11757
11758 pub fn register_action<A: Action>(
11759 &mut self,
11760 listener: impl Fn(&A, &mut WindowContext) + 'static,
11761 ) -> Subscription {
11762 let id = self.next_editor_action_id.post_inc();
11763 let listener = Arc::new(listener);
11764 self.editor_actions.borrow_mut().insert(
11765 id,
11766 Box::new(move |cx| {
11767 let _view = cx.view().clone();
11768 let cx = cx.window_context();
11769 let listener = listener.clone();
11770 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
11771 let action = action.downcast_ref().unwrap();
11772 if phase == DispatchPhase::Bubble {
11773 listener(action, cx)
11774 }
11775 })
11776 }),
11777 );
11778
11779 let editor_actions = self.editor_actions.clone();
11780 Subscription::new(move || {
11781 editor_actions.borrow_mut().remove(&id);
11782 })
11783 }
11784
11785 pub fn file_header_size(&self) -> u8 {
11786 self.file_header_size
11787 }
11788
11789 pub fn revert(
11790 &mut self,
11791 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
11792 cx: &mut ViewContext<Self>,
11793 ) {
11794 self.buffer().update(cx, |multi_buffer, cx| {
11795 for (buffer_id, changes) in revert_changes {
11796 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
11797 buffer.update(cx, |buffer, cx| {
11798 buffer.edit(
11799 changes.into_iter().map(|(range, text)| {
11800 (range, text.to_string().map(Arc::<str>::from))
11801 }),
11802 None,
11803 cx,
11804 );
11805 });
11806 }
11807 }
11808 });
11809 self.change_selections(None, cx, |selections| selections.refresh());
11810 }
11811
11812 pub fn to_pixel_point(
11813 &mut self,
11814 source: multi_buffer::Anchor,
11815 editor_snapshot: &EditorSnapshot,
11816 cx: &mut ViewContext<Self>,
11817 ) -> Option<gpui::Point<Pixels>> {
11818 let text_layout_details = self.text_layout_details(cx);
11819 let line_height = text_layout_details
11820 .editor_style
11821 .text
11822 .line_height_in_pixels(cx.rem_size());
11823 let source_point = source.to_display_point(editor_snapshot);
11824 let first_visible_line = text_layout_details
11825 .scroll_anchor
11826 .anchor
11827 .to_display_point(editor_snapshot);
11828 if first_visible_line > source_point {
11829 return None;
11830 }
11831 let source_x = editor_snapshot.x_for_display_point(source_point, &text_layout_details);
11832 let source_y = line_height
11833 * ((source_point.row() - first_visible_line.row()).0 as f32
11834 - text_layout_details.scroll_anchor.offset.y);
11835 Some(gpui::Point::new(source_x, source_y))
11836 }
11837
11838 pub fn display_to_pixel_point(
11839 &mut self,
11840 source: DisplayPoint,
11841 editor_snapshot: &EditorSnapshot,
11842 cx: &mut ViewContext<Self>,
11843 ) -> Option<gpui::Point<Pixels>> {
11844 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
11845 let text_layout_details = self.text_layout_details(cx);
11846 let first_visible_line = text_layout_details
11847 .scroll_anchor
11848 .anchor
11849 .to_display_point(editor_snapshot);
11850 if first_visible_line > source {
11851 return None;
11852 }
11853 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
11854 let source_y = line_height * (source.row() - first_visible_line.row()).0 as f32;
11855 Some(gpui::Point::new(source_x, source_y))
11856 }
11857}
11858
11859fn hunks_for_selections(
11860 multi_buffer_snapshot: &MultiBufferSnapshot,
11861 selections: &[Selection<Anchor>],
11862) -> Vec<DiffHunk<MultiBufferRow>> {
11863 let buffer_rows_for_selections = selections.iter().map(|selection| {
11864 let head = selection.head();
11865 let tail = selection.tail();
11866 let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
11867 let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
11868 if start > end {
11869 end..start
11870 } else {
11871 start..end
11872 }
11873 });
11874
11875 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
11876}
11877
11878pub fn hunks_for_rows(
11879 rows: impl Iterator<Item = Range<MultiBufferRow>>,
11880 multi_buffer_snapshot: &MultiBufferSnapshot,
11881) -> Vec<DiffHunk<MultiBufferRow>> {
11882 let mut hunks = Vec::new();
11883 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
11884 HashMap::default();
11885 for selected_multi_buffer_rows in rows {
11886 let query_rows =
11887 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
11888 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
11889 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
11890 // when the caret is just above or just below the deleted hunk.
11891 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
11892 let related_to_selection = if allow_adjacent {
11893 hunk.associated_range.overlaps(&query_rows)
11894 || hunk.associated_range.start == query_rows.end
11895 || hunk.associated_range.end == query_rows.start
11896 } else {
11897 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
11898 // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
11899 hunk.associated_range.overlaps(&selected_multi_buffer_rows)
11900 || selected_multi_buffer_rows.end == hunk.associated_range.start
11901 };
11902 if related_to_selection {
11903 if !processed_buffer_rows
11904 .entry(hunk.buffer_id)
11905 .or_default()
11906 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
11907 {
11908 continue;
11909 }
11910 hunks.push(hunk);
11911 }
11912 }
11913 }
11914
11915 hunks
11916}
11917
11918pub trait CollaborationHub {
11919 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
11920 fn user_participant_indices<'a>(
11921 &self,
11922 cx: &'a AppContext,
11923 ) -> &'a HashMap<u64, ParticipantIndex>;
11924 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
11925}
11926
11927impl CollaborationHub for Model<Project> {
11928 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
11929 self.read(cx).collaborators()
11930 }
11931
11932 fn user_participant_indices<'a>(
11933 &self,
11934 cx: &'a AppContext,
11935 ) -> &'a HashMap<u64, ParticipantIndex> {
11936 self.read(cx).user_store().read(cx).participant_indices()
11937 }
11938
11939 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
11940 let this = self.read(cx);
11941 let user_ids = this.collaborators().values().map(|c| c.user_id);
11942 this.user_store().read_with(cx, |user_store, cx| {
11943 user_store.participant_names(user_ids, cx)
11944 })
11945 }
11946}
11947
11948pub trait CompletionProvider {
11949 fn completions(
11950 &self,
11951 buffer: &Model<Buffer>,
11952 buffer_position: text::Anchor,
11953 trigger: CompletionContext,
11954 cx: &mut ViewContext<Editor>,
11955 ) -> Task<Result<Vec<Completion>>>;
11956
11957 fn resolve_completions(
11958 &self,
11959 buffer: Model<Buffer>,
11960 completion_indices: Vec<usize>,
11961 completions: Arc<RwLock<Box<[Completion]>>>,
11962 cx: &mut ViewContext<Editor>,
11963 ) -> Task<Result<bool>>;
11964
11965 fn apply_additional_edits_for_completion(
11966 &self,
11967 buffer: Model<Buffer>,
11968 completion: Completion,
11969 push_to_history: bool,
11970 cx: &mut ViewContext<Editor>,
11971 ) -> Task<Result<Option<language::Transaction>>>;
11972
11973 fn is_completion_trigger(
11974 &self,
11975 buffer: &Model<Buffer>,
11976 position: language::Anchor,
11977 text: &str,
11978 trigger_in_words: bool,
11979 cx: &mut ViewContext<Editor>,
11980 ) -> bool;
11981}
11982
11983fn snippet_completions(
11984 project: &Project,
11985 buffer: &Model<Buffer>,
11986 buffer_position: text::Anchor,
11987 cx: &mut AppContext,
11988) -> Vec<Completion> {
11989 let language = buffer.read(cx).language_at(buffer_position);
11990 let language_name = language.as_ref().map(|language| language.lsp_id());
11991 let snippet_store = project.snippets().read(cx);
11992 let snippets = snippet_store.snippets_for(language_name, cx);
11993
11994 if snippets.is_empty() {
11995 return vec![];
11996 }
11997 let snapshot = buffer.read(cx).text_snapshot();
11998 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
11999
12000 let mut lines = chunks.lines();
12001 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12002 return vec![];
12003 };
12004
12005 let scope = language.map(|language| language.default_scope());
12006 let mut last_word = line_at
12007 .chars()
12008 .rev()
12009 .take_while(|c| char_kind(&scope, *c) == CharKind::Word)
12010 .collect::<String>();
12011 last_word = last_word.chars().rev().collect();
12012 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12013 let to_lsp = |point: &text::Anchor| {
12014 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12015 point_to_lsp(end)
12016 };
12017 let lsp_end = to_lsp(&buffer_position);
12018 snippets
12019 .into_iter()
12020 .filter_map(|snippet| {
12021 let matching_prefix = snippet
12022 .prefix
12023 .iter()
12024 .find(|prefix| prefix.starts_with(&last_word))?;
12025 let start = as_offset - last_word.len();
12026 let start = snapshot.anchor_before(start);
12027 let range = start..buffer_position;
12028 let lsp_start = to_lsp(&start);
12029 let lsp_range = lsp::Range {
12030 start: lsp_start,
12031 end: lsp_end,
12032 };
12033 Some(Completion {
12034 old_range: range,
12035 new_text: snippet.body.clone(),
12036 label: CodeLabel {
12037 text: matching_prefix.clone(),
12038 runs: vec![],
12039 filter_range: 0..matching_prefix.len(),
12040 },
12041 server_id: LanguageServerId(usize::MAX),
12042 documentation: snippet
12043 .description
12044 .clone()
12045 .map(|description| Documentation::SingleLine(description)),
12046 lsp_completion: lsp::CompletionItem {
12047 label: snippet.prefix.first().unwrap().clone(),
12048 kind: Some(CompletionItemKind::SNIPPET),
12049 label_details: snippet.description.as_ref().map(|description| {
12050 lsp::CompletionItemLabelDetails {
12051 detail: Some(description.clone()),
12052 description: None,
12053 }
12054 }),
12055 insert_text_format: Some(InsertTextFormat::SNIPPET),
12056 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12057 lsp::InsertReplaceEdit {
12058 new_text: snippet.body.clone(),
12059 insert: lsp_range,
12060 replace: lsp_range,
12061 },
12062 )),
12063 filter_text: Some(snippet.body.clone()),
12064 sort_text: Some(char::MAX.to_string()),
12065 ..Default::default()
12066 },
12067 confirm: None,
12068 show_new_completions_on_confirm: false,
12069 })
12070 })
12071 .collect()
12072}
12073
12074impl CompletionProvider for Model<Project> {
12075 fn completions(
12076 &self,
12077 buffer: &Model<Buffer>,
12078 buffer_position: text::Anchor,
12079 options: CompletionContext,
12080 cx: &mut ViewContext<Editor>,
12081 ) -> Task<Result<Vec<Completion>>> {
12082 self.update(cx, |project, cx| {
12083 let snippets = snippet_completions(project, buffer, buffer_position, cx);
12084 let project_completions = project.completions(&buffer, buffer_position, options, cx);
12085 cx.background_executor().spawn(async move {
12086 let mut completions = project_completions.await?;
12087 //let snippets = snippets.into_iter().;
12088 completions.extend(snippets);
12089 Ok(completions)
12090 })
12091 })
12092 }
12093
12094 fn resolve_completions(
12095 &self,
12096 buffer: Model<Buffer>,
12097 completion_indices: Vec<usize>,
12098 completions: Arc<RwLock<Box<[Completion]>>>,
12099 cx: &mut ViewContext<Editor>,
12100 ) -> Task<Result<bool>> {
12101 self.update(cx, |project, cx| {
12102 project.resolve_completions(buffer, completion_indices, completions, cx)
12103 })
12104 }
12105
12106 fn apply_additional_edits_for_completion(
12107 &self,
12108 buffer: Model<Buffer>,
12109 completion: Completion,
12110 push_to_history: bool,
12111 cx: &mut ViewContext<Editor>,
12112 ) -> Task<Result<Option<language::Transaction>>> {
12113 self.update(cx, |project, cx| {
12114 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12115 })
12116 }
12117
12118 fn is_completion_trigger(
12119 &self,
12120 buffer: &Model<Buffer>,
12121 position: language::Anchor,
12122 text: &str,
12123 trigger_in_words: bool,
12124 cx: &mut ViewContext<Editor>,
12125 ) -> bool {
12126 if !EditorSettings::get_global(cx).show_completions_on_input {
12127 return false;
12128 }
12129
12130 let mut chars = text.chars();
12131 let char = if let Some(char) = chars.next() {
12132 char
12133 } else {
12134 return false;
12135 };
12136 if chars.next().is_some() {
12137 return false;
12138 }
12139
12140 let buffer = buffer.read(cx);
12141 let scope = buffer.snapshot().language_scope_at(position);
12142 if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
12143 return true;
12144 }
12145
12146 buffer
12147 .completion_triggers()
12148 .iter()
12149 .any(|string| string == text)
12150 }
12151}
12152
12153fn inlay_hint_settings(
12154 location: Anchor,
12155 snapshot: &MultiBufferSnapshot,
12156 cx: &mut ViewContext<'_, Editor>,
12157) -> InlayHintSettings {
12158 let file = snapshot.file_at(location);
12159 let language = snapshot.language_at(location);
12160 let settings = all_language_settings(file, cx);
12161 settings
12162 .language(language.map(|l| l.name()).as_deref())
12163 .inlay_hints
12164}
12165
12166fn consume_contiguous_rows(
12167 contiguous_row_selections: &mut Vec<Selection<Point>>,
12168 selection: &Selection<Point>,
12169 display_map: &DisplaySnapshot,
12170 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12171) -> (MultiBufferRow, MultiBufferRow) {
12172 contiguous_row_selections.push(selection.clone());
12173 let start_row = MultiBufferRow(selection.start.row);
12174 let mut end_row = ending_row(selection, display_map);
12175
12176 while let Some(next_selection) = selections.peek() {
12177 if next_selection.start.row <= end_row.0 {
12178 end_row = ending_row(next_selection, display_map);
12179 contiguous_row_selections.push(selections.next().unwrap().clone());
12180 } else {
12181 break;
12182 }
12183 }
12184 (start_row, end_row)
12185}
12186
12187fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12188 if next_selection.end.column > 0 || next_selection.is_empty() {
12189 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12190 } else {
12191 MultiBufferRow(next_selection.end.row)
12192 }
12193}
12194
12195impl EditorSnapshot {
12196 pub fn remote_selections_in_range<'a>(
12197 &'a self,
12198 range: &'a Range<Anchor>,
12199 collaboration_hub: &dyn CollaborationHub,
12200 cx: &'a AppContext,
12201 ) -> impl 'a + Iterator<Item = RemoteSelection> {
12202 let participant_names = collaboration_hub.user_names(cx);
12203 let participant_indices = collaboration_hub.user_participant_indices(cx);
12204 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12205 let collaborators_by_replica_id = collaborators_by_peer_id
12206 .iter()
12207 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12208 .collect::<HashMap<_, _>>();
12209 self.buffer_snapshot
12210 .selections_in_range(range, false)
12211 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12212 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12213 let participant_index = participant_indices.get(&collaborator.user_id).copied();
12214 let user_name = participant_names.get(&collaborator.user_id).cloned();
12215 Some(RemoteSelection {
12216 replica_id,
12217 selection,
12218 cursor_shape,
12219 line_mode,
12220 participant_index,
12221 peer_id: collaborator.peer_id,
12222 user_name,
12223 })
12224 })
12225 }
12226
12227 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12228 self.display_snapshot.buffer_snapshot.language_at(position)
12229 }
12230
12231 pub fn is_focused(&self) -> bool {
12232 self.is_focused
12233 }
12234
12235 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12236 self.placeholder_text.as_ref()
12237 }
12238
12239 pub fn scroll_position(&self) -> gpui::Point<f32> {
12240 self.scroll_anchor.scroll_position(&self.display_snapshot)
12241 }
12242
12243 pub fn gutter_dimensions(
12244 &self,
12245 font_id: FontId,
12246 font_size: Pixels,
12247 em_width: Pixels,
12248 max_line_number_width: Pixels,
12249 cx: &AppContext,
12250 ) -> GutterDimensions {
12251 if !self.show_gutter {
12252 return GutterDimensions::default();
12253 }
12254 let descent = cx.text_system().descent(font_id, font_size);
12255
12256 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12257 matches!(
12258 ProjectSettings::get_global(cx).git.git_gutter,
12259 Some(GitGutterSetting::TrackedFiles)
12260 )
12261 });
12262 let gutter_settings = EditorSettings::get_global(cx).gutter;
12263 let show_line_numbers = self
12264 .show_line_numbers
12265 .unwrap_or(gutter_settings.line_numbers);
12266 let line_gutter_width = if show_line_numbers {
12267 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12268 let min_width_for_number_on_gutter = em_width * 4.0;
12269 max_line_number_width.max(min_width_for_number_on_gutter)
12270 } else {
12271 0.0.into()
12272 };
12273
12274 let show_code_actions = self
12275 .show_code_actions
12276 .unwrap_or(gutter_settings.code_actions);
12277
12278 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12279
12280 let git_blame_entries_width = self
12281 .render_git_blame_gutter
12282 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12283
12284 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12285 left_padding += if show_code_actions || show_runnables {
12286 em_width * 3.0
12287 } else if show_git_gutter && show_line_numbers {
12288 em_width * 2.0
12289 } else if show_git_gutter || show_line_numbers {
12290 em_width
12291 } else {
12292 px(0.)
12293 };
12294
12295 let right_padding = if gutter_settings.folds && show_line_numbers {
12296 em_width * 4.0
12297 } else if gutter_settings.folds {
12298 em_width * 3.0
12299 } else if show_line_numbers {
12300 em_width
12301 } else {
12302 px(0.)
12303 };
12304
12305 GutterDimensions {
12306 left_padding,
12307 right_padding,
12308 width: line_gutter_width + left_padding + right_padding,
12309 margin: -descent,
12310 git_blame_entries_width,
12311 }
12312 }
12313
12314 pub fn render_fold_toggle(
12315 &self,
12316 buffer_row: MultiBufferRow,
12317 row_contains_cursor: bool,
12318 editor: View<Editor>,
12319 cx: &mut WindowContext,
12320 ) -> Option<AnyElement> {
12321 let folded = self.is_line_folded(buffer_row);
12322
12323 if let Some(crease) = self
12324 .crease_snapshot
12325 .query_row(buffer_row, &self.buffer_snapshot)
12326 {
12327 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12328 if folded {
12329 editor.update(cx, |editor, cx| {
12330 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12331 });
12332 } else {
12333 editor.update(cx, |editor, cx| {
12334 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12335 });
12336 }
12337 });
12338
12339 Some((crease.render_toggle)(
12340 buffer_row,
12341 folded,
12342 toggle_callback,
12343 cx,
12344 ))
12345 } else if folded
12346 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12347 {
12348 Some(
12349 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12350 .selected(folded)
12351 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12352 if folded {
12353 this.unfold_at(&UnfoldAt { buffer_row }, cx);
12354 } else {
12355 this.fold_at(&FoldAt { buffer_row }, cx);
12356 }
12357 }))
12358 .into_any_element(),
12359 )
12360 } else {
12361 None
12362 }
12363 }
12364
12365 pub fn render_crease_trailer(
12366 &self,
12367 buffer_row: MultiBufferRow,
12368 cx: &mut WindowContext,
12369 ) -> Option<AnyElement> {
12370 let folded = self.is_line_folded(buffer_row);
12371 let crease = self
12372 .crease_snapshot
12373 .query_row(buffer_row, &self.buffer_snapshot)?;
12374 Some((crease.render_trailer)(buffer_row, folded, cx))
12375 }
12376}
12377
12378impl Deref for EditorSnapshot {
12379 type Target = DisplaySnapshot;
12380
12381 fn deref(&self) -> &Self::Target {
12382 &self.display_snapshot
12383 }
12384}
12385
12386#[derive(Clone, Debug, PartialEq, Eq)]
12387pub enum EditorEvent {
12388 InputIgnored {
12389 text: Arc<str>,
12390 },
12391 InputHandled {
12392 utf16_range_to_replace: Option<Range<isize>>,
12393 text: Arc<str>,
12394 },
12395 ExcerptsAdded {
12396 buffer: Model<Buffer>,
12397 predecessor: ExcerptId,
12398 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12399 },
12400 ExcerptsRemoved {
12401 ids: Vec<ExcerptId>,
12402 },
12403 ExcerptsEdited {
12404 ids: Vec<ExcerptId>,
12405 },
12406 ExcerptsExpanded {
12407 ids: Vec<ExcerptId>,
12408 },
12409 BufferEdited,
12410 Edited {
12411 transaction_id: clock::Lamport,
12412 },
12413 Reparsed(BufferId),
12414 Focused,
12415 FocusedIn,
12416 Blurred,
12417 DirtyChanged,
12418 Saved,
12419 TitleChanged,
12420 DiffBaseChanged,
12421 SelectionsChanged {
12422 local: bool,
12423 },
12424 ScrollPositionChanged {
12425 local: bool,
12426 autoscroll: bool,
12427 },
12428 Closed,
12429 TransactionUndone {
12430 transaction_id: clock::Lamport,
12431 },
12432 TransactionBegun {
12433 transaction_id: clock::Lamport,
12434 },
12435}
12436
12437impl EventEmitter<EditorEvent> for Editor {}
12438
12439impl FocusableView for Editor {
12440 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12441 self.focus_handle.clone()
12442 }
12443}
12444
12445impl Render for Editor {
12446 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12447 let settings = ThemeSettings::get_global(cx);
12448
12449 let text_style = match self.mode {
12450 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12451 color: cx.theme().colors().editor_foreground,
12452 font_family: settings.ui_font.family.clone(),
12453 font_features: settings.ui_font.features.clone(),
12454 font_size: rems(0.875).into(),
12455 font_weight: settings.ui_font.weight,
12456 line_height: relative(settings.buffer_line_height.value()),
12457 ..Default::default()
12458 },
12459 EditorMode::Full => TextStyle {
12460 color: cx.theme().colors().editor_foreground,
12461 font_family: settings.buffer_font.family.clone(),
12462 font_features: settings.buffer_font.features.clone(),
12463 font_size: settings.buffer_font_size(cx).into(),
12464 font_weight: settings.buffer_font.weight,
12465 line_height: relative(settings.buffer_line_height.value()),
12466 ..Default::default()
12467 },
12468 };
12469
12470 let background = match self.mode {
12471 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12472 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12473 EditorMode::Full => cx.theme().colors().editor_background,
12474 };
12475
12476 EditorElement::new(
12477 cx.view(),
12478 EditorStyle {
12479 background,
12480 local_player: cx.theme().players().local(),
12481 text: text_style,
12482 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12483 syntax: cx.theme().syntax().clone(),
12484 status: cx.theme().status().clone(),
12485 inlay_hints_style: HighlightStyle {
12486 color: Some(cx.theme().status().hint),
12487 ..HighlightStyle::default()
12488 },
12489 suggestions_style: HighlightStyle {
12490 color: Some(cx.theme().status().predictive),
12491 ..HighlightStyle::default()
12492 },
12493 },
12494 )
12495 }
12496}
12497
12498impl ViewInputHandler for Editor {
12499 fn text_for_range(
12500 &mut self,
12501 range_utf16: Range<usize>,
12502 cx: &mut ViewContext<Self>,
12503 ) -> Option<String> {
12504 Some(
12505 self.buffer
12506 .read(cx)
12507 .read(cx)
12508 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12509 .collect(),
12510 )
12511 }
12512
12513 fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12514 // Prevent the IME menu from appearing when holding down an alphabetic key
12515 // while input is disabled.
12516 if !self.input_enabled {
12517 return None;
12518 }
12519
12520 let range = self.selections.newest::<OffsetUtf16>(cx).range();
12521 Some(range.start.0..range.end.0)
12522 }
12523
12524 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12525 let snapshot = self.buffer.read(cx).read(cx);
12526 let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
12527 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12528 }
12529
12530 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12531 self.clear_highlights::<InputComposition>(cx);
12532 self.ime_transaction.take();
12533 }
12534
12535 fn replace_text_in_range(
12536 &mut self,
12537 range_utf16: Option<Range<usize>>,
12538 text: &str,
12539 cx: &mut ViewContext<Self>,
12540 ) {
12541 if !self.input_enabled {
12542 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12543 return;
12544 }
12545
12546 self.transact(cx, |this, cx| {
12547 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12548 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12549 Some(this.selection_replacement_ranges(range_utf16, cx))
12550 } else {
12551 this.marked_text_ranges(cx)
12552 };
12553
12554 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12555 let newest_selection_id = this.selections.newest_anchor().id;
12556 this.selections
12557 .all::<OffsetUtf16>(cx)
12558 .iter()
12559 .zip(ranges_to_replace.iter())
12560 .find_map(|(selection, range)| {
12561 if selection.id == newest_selection_id {
12562 Some(
12563 (range.start.0 as isize - selection.head().0 as isize)
12564 ..(range.end.0 as isize - selection.head().0 as isize),
12565 )
12566 } else {
12567 None
12568 }
12569 })
12570 });
12571
12572 cx.emit(EditorEvent::InputHandled {
12573 utf16_range_to_replace: range_to_replace,
12574 text: text.into(),
12575 });
12576
12577 if let Some(new_selected_ranges) = new_selected_ranges {
12578 this.change_selections(None, cx, |selections| {
12579 selections.select_ranges(new_selected_ranges)
12580 });
12581 this.backspace(&Default::default(), cx);
12582 }
12583
12584 this.handle_input(text, cx);
12585 });
12586
12587 if let Some(transaction) = self.ime_transaction {
12588 self.buffer.update(cx, |buffer, cx| {
12589 buffer.group_until_transaction(transaction, cx);
12590 });
12591 }
12592
12593 self.unmark_text(cx);
12594 }
12595
12596 fn replace_and_mark_text_in_range(
12597 &mut self,
12598 range_utf16: Option<Range<usize>>,
12599 text: &str,
12600 new_selected_range_utf16: Option<Range<usize>>,
12601 cx: &mut ViewContext<Self>,
12602 ) {
12603 if !self.input_enabled {
12604 return;
12605 }
12606
12607 let transaction = self.transact(cx, |this, cx| {
12608 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12609 let snapshot = this.buffer.read(cx).read(cx);
12610 if let Some(relative_range_utf16) = range_utf16.as_ref() {
12611 for marked_range in &mut marked_ranges {
12612 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12613 marked_range.start.0 += relative_range_utf16.start;
12614 marked_range.start =
12615 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12616 marked_range.end =
12617 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12618 }
12619 }
12620 Some(marked_ranges)
12621 } else if let Some(range_utf16) = range_utf16 {
12622 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12623 Some(this.selection_replacement_ranges(range_utf16, cx))
12624 } else {
12625 None
12626 };
12627
12628 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12629 let newest_selection_id = this.selections.newest_anchor().id;
12630 this.selections
12631 .all::<OffsetUtf16>(cx)
12632 .iter()
12633 .zip(ranges_to_replace.iter())
12634 .find_map(|(selection, range)| {
12635 if selection.id == newest_selection_id {
12636 Some(
12637 (range.start.0 as isize - selection.head().0 as isize)
12638 ..(range.end.0 as isize - selection.head().0 as isize),
12639 )
12640 } else {
12641 None
12642 }
12643 })
12644 });
12645
12646 cx.emit(EditorEvent::InputHandled {
12647 utf16_range_to_replace: range_to_replace,
12648 text: text.into(),
12649 });
12650
12651 if let Some(ranges) = ranges_to_replace {
12652 this.change_selections(None, cx, |s| s.select_ranges(ranges));
12653 }
12654
12655 let marked_ranges = {
12656 let snapshot = this.buffer.read(cx).read(cx);
12657 this.selections
12658 .disjoint_anchors()
12659 .iter()
12660 .map(|selection| {
12661 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12662 })
12663 .collect::<Vec<_>>()
12664 };
12665
12666 if text.is_empty() {
12667 this.unmark_text(cx);
12668 } else {
12669 this.highlight_text::<InputComposition>(
12670 marked_ranges.clone(),
12671 HighlightStyle {
12672 underline: Some(UnderlineStyle {
12673 thickness: px(1.),
12674 color: None,
12675 wavy: false,
12676 }),
12677 ..Default::default()
12678 },
12679 cx,
12680 );
12681 }
12682
12683 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12684 let use_autoclose = this.use_autoclose;
12685 let use_auto_surround = this.use_auto_surround;
12686 this.set_use_autoclose(false);
12687 this.set_use_auto_surround(false);
12688 this.handle_input(text, cx);
12689 this.set_use_autoclose(use_autoclose);
12690 this.set_use_auto_surround(use_auto_surround);
12691
12692 if let Some(new_selected_range) = new_selected_range_utf16 {
12693 let snapshot = this.buffer.read(cx).read(cx);
12694 let new_selected_ranges = marked_ranges
12695 .into_iter()
12696 .map(|marked_range| {
12697 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
12698 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
12699 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
12700 snapshot.clip_offset_utf16(new_start, Bias::Left)
12701 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
12702 })
12703 .collect::<Vec<_>>();
12704
12705 drop(snapshot);
12706 this.change_selections(None, cx, |selections| {
12707 selections.select_ranges(new_selected_ranges)
12708 });
12709 }
12710 });
12711
12712 self.ime_transaction = self.ime_transaction.or(transaction);
12713 if let Some(transaction) = self.ime_transaction {
12714 self.buffer.update(cx, |buffer, cx| {
12715 buffer.group_until_transaction(transaction, cx);
12716 });
12717 }
12718
12719 if self.text_highlights::<InputComposition>(cx).is_none() {
12720 self.ime_transaction.take();
12721 }
12722 }
12723
12724 fn bounds_for_range(
12725 &mut self,
12726 range_utf16: Range<usize>,
12727 element_bounds: gpui::Bounds<Pixels>,
12728 cx: &mut ViewContext<Self>,
12729 ) -> Option<gpui::Bounds<Pixels>> {
12730 let text_layout_details = self.text_layout_details(cx);
12731 let style = &text_layout_details.editor_style;
12732 let font_id = cx.text_system().resolve_font(&style.text.font());
12733 let font_size = style.text.font_size.to_pixels(cx.rem_size());
12734 let line_height = style.text.line_height_in_pixels(cx.rem_size());
12735
12736 let em_width = cx
12737 .text_system()
12738 .typographic_bounds(font_id, font_size, 'm')
12739 .unwrap()
12740 .size
12741 .width;
12742
12743 let snapshot = self.snapshot(cx);
12744 let scroll_position = snapshot.scroll_position();
12745 let scroll_left = scroll_position.x * em_width;
12746
12747 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
12748 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
12749 + self.gutter_dimensions.width;
12750 let y = line_height * (start.row().as_f32() - scroll_position.y);
12751
12752 Some(Bounds {
12753 origin: element_bounds.origin + point(x, y),
12754 size: size(em_width, line_height),
12755 })
12756 }
12757}
12758
12759trait SelectionExt {
12760 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
12761 fn spanned_rows(
12762 &self,
12763 include_end_if_at_line_start: bool,
12764 map: &DisplaySnapshot,
12765 ) -> Range<MultiBufferRow>;
12766}
12767
12768impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
12769 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
12770 let start = self
12771 .start
12772 .to_point(&map.buffer_snapshot)
12773 .to_display_point(map);
12774 let end = self
12775 .end
12776 .to_point(&map.buffer_snapshot)
12777 .to_display_point(map);
12778 if self.reversed {
12779 end..start
12780 } else {
12781 start..end
12782 }
12783 }
12784
12785 fn spanned_rows(
12786 &self,
12787 include_end_if_at_line_start: bool,
12788 map: &DisplaySnapshot,
12789 ) -> Range<MultiBufferRow> {
12790 let start = self.start.to_point(&map.buffer_snapshot);
12791 let mut end = self.end.to_point(&map.buffer_snapshot);
12792 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
12793 end.row -= 1;
12794 }
12795
12796 let buffer_start = map.prev_line_boundary(start).0;
12797 let buffer_end = map.next_line_boundary(end).0;
12798 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
12799 }
12800}
12801
12802impl<T: InvalidationRegion> InvalidationStack<T> {
12803 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
12804 where
12805 S: Clone + ToOffset,
12806 {
12807 while let Some(region) = self.last() {
12808 let all_selections_inside_invalidation_ranges =
12809 if selections.len() == region.ranges().len() {
12810 selections
12811 .iter()
12812 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
12813 .all(|(selection, invalidation_range)| {
12814 let head = selection.head().to_offset(buffer);
12815 invalidation_range.start <= head && invalidation_range.end >= head
12816 })
12817 } else {
12818 false
12819 };
12820
12821 if all_selections_inside_invalidation_ranges {
12822 break;
12823 } else {
12824 self.pop();
12825 }
12826 }
12827 }
12828}
12829
12830impl<T> Default for InvalidationStack<T> {
12831 fn default() -> Self {
12832 Self(Default::default())
12833 }
12834}
12835
12836impl<T> Deref for InvalidationStack<T> {
12837 type Target = Vec<T>;
12838
12839 fn deref(&self) -> &Self::Target {
12840 &self.0
12841 }
12842}
12843
12844impl<T> DerefMut for InvalidationStack<T> {
12845 fn deref_mut(&mut self) -> &mut Self::Target {
12846 &mut self.0
12847 }
12848}
12849
12850impl InvalidationRegion for SnippetState {
12851 fn ranges(&self) -> &[Range<Anchor>] {
12852 &self.ranges[self.active_index]
12853 }
12854}
12855
12856pub fn diagnostic_block_renderer(
12857 diagnostic: Diagnostic,
12858 max_message_rows: Option<u8>,
12859 allow_closing: bool,
12860 _is_valid: bool,
12861) -> RenderBlock {
12862 let (text_without_backticks, code_ranges) =
12863 highlight_diagnostic_message(&diagnostic, max_message_rows);
12864
12865 Box::new(move |cx: &mut BlockContext| {
12866 let group_id: SharedString = cx.block_id.to_string().into();
12867
12868 let mut text_style = cx.text_style().clone();
12869 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
12870 let theme_settings = ThemeSettings::get_global(cx);
12871 text_style.font_family = theme_settings.buffer_font.family.clone();
12872 text_style.font_style = theme_settings.buffer_font.style;
12873 text_style.font_features = theme_settings.buffer_font.features.clone();
12874 text_style.font_weight = theme_settings.buffer_font.weight;
12875
12876 let multi_line_diagnostic = diagnostic.message.contains('\n');
12877
12878 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
12879 if multi_line_diagnostic {
12880 v_flex()
12881 } else {
12882 h_flex()
12883 }
12884 .when(allow_closing, |div| {
12885 div.children(diagnostic.is_primary.then(|| {
12886 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
12887 .icon_color(Color::Muted)
12888 .size(ButtonSize::Compact)
12889 .style(ButtonStyle::Transparent)
12890 .visible_on_hover(group_id.clone())
12891 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
12892 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
12893 }))
12894 })
12895 .child(
12896 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
12897 .icon_color(Color::Muted)
12898 .size(ButtonSize::Compact)
12899 .style(ButtonStyle::Transparent)
12900 .visible_on_hover(group_id.clone())
12901 .on_click({
12902 let message = diagnostic.message.clone();
12903 move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
12904 })
12905 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
12906 )
12907 };
12908
12909 let icon_size = buttons(&diagnostic, cx.block_id)
12910 .into_any_element()
12911 .layout_as_root(AvailableSpace::min_size(), cx);
12912
12913 h_flex()
12914 .id(cx.block_id)
12915 .group(group_id.clone())
12916 .relative()
12917 .size_full()
12918 .pl(cx.gutter_dimensions.width)
12919 .w(cx.max_width + cx.gutter_dimensions.width)
12920 .child(
12921 div()
12922 .flex()
12923 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
12924 .flex_shrink(),
12925 )
12926 .child(buttons(&diagnostic, cx.block_id))
12927 .child(div().flex().flex_shrink_0().child(
12928 StyledText::new(text_without_backticks.clone()).with_highlights(
12929 &text_style,
12930 code_ranges.iter().map(|range| {
12931 (
12932 range.clone(),
12933 HighlightStyle {
12934 font_weight: Some(FontWeight::BOLD),
12935 ..Default::default()
12936 },
12937 )
12938 }),
12939 ),
12940 ))
12941 .into_any_element()
12942 })
12943}
12944
12945pub fn highlight_diagnostic_message(
12946 diagnostic: &Diagnostic,
12947 mut max_message_rows: Option<u8>,
12948) -> (SharedString, Vec<Range<usize>>) {
12949 let mut text_without_backticks = String::new();
12950 let mut code_ranges = Vec::new();
12951
12952 if let Some(source) = &diagnostic.source {
12953 text_without_backticks.push_str(&source);
12954 code_ranges.push(0..source.len());
12955 text_without_backticks.push_str(": ");
12956 }
12957
12958 let mut prev_offset = 0;
12959 let mut in_code_block = false;
12960 let has_row_limit = max_message_rows.is_some();
12961 let mut newline_indices = diagnostic
12962 .message
12963 .match_indices('\n')
12964 .filter(|_| has_row_limit)
12965 .map(|(ix, _)| ix)
12966 .fuse()
12967 .peekable();
12968
12969 for (quote_ix, _) in diagnostic
12970 .message
12971 .match_indices('`')
12972 .chain([(diagnostic.message.len(), "")])
12973 {
12974 let mut first_newline_ix = None;
12975 let mut last_newline_ix = None;
12976 while let Some(newline_ix) = newline_indices.peek() {
12977 if *newline_ix < quote_ix {
12978 if first_newline_ix.is_none() {
12979 first_newline_ix = Some(*newline_ix);
12980 }
12981 last_newline_ix = Some(*newline_ix);
12982
12983 if let Some(rows_left) = &mut max_message_rows {
12984 if *rows_left == 0 {
12985 break;
12986 } else {
12987 *rows_left -= 1;
12988 }
12989 }
12990 let _ = newline_indices.next();
12991 } else {
12992 break;
12993 }
12994 }
12995 let prev_len = text_without_backticks.len();
12996 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
12997 text_without_backticks.push_str(new_text);
12998 if in_code_block {
12999 code_ranges.push(prev_len..text_without_backticks.len());
13000 }
13001 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13002 in_code_block = !in_code_block;
13003 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13004 text_without_backticks.push_str("...");
13005 break;
13006 }
13007 }
13008
13009 (text_without_backticks.into(), code_ranges)
13010}
13011
13012fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13013 match severity {
13014 DiagnosticSeverity::ERROR => colors.error,
13015 DiagnosticSeverity::WARNING => colors.warning,
13016 DiagnosticSeverity::INFORMATION => colors.info,
13017 DiagnosticSeverity::HINT => colors.info,
13018 _ => colors.ignored,
13019 }
13020}
13021
13022pub fn styled_runs_for_code_label<'a>(
13023 label: &'a CodeLabel,
13024 syntax_theme: &'a theme::SyntaxTheme,
13025) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13026 let fade_out = HighlightStyle {
13027 fade_out: Some(0.35),
13028 ..Default::default()
13029 };
13030
13031 let mut prev_end = label.filter_range.end;
13032 label
13033 .runs
13034 .iter()
13035 .enumerate()
13036 .flat_map(move |(ix, (range, highlight_id))| {
13037 let style = if let Some(style) = highlight_id.style(syntax_theme) {
13038 style
13039 } else {
13040 return Default::default();
13041 };
13042 let mut muted_style = style;
13043 muted_style.highlight(fade_out);
13044
13045 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13046 if range.start >= label.filter_range.end {
13047 if range.start > prev_end {
13048 runs.push((prev_end..range.start, fade_out));
13049 }
13050 runs.push((range.clone(), muted_style));
13051 } else if range.end <= label.filter_range.end {
13052 runs.push((range.clone(), style));
13053 } else {
13054 runs.push((range.start..label.filter_range.end, style));
13055 runs.push((label.filter_range.end..range.end, muted_style));
13056 }
13057 prev_end = cmp::max(prev_end, range.end);
13058
13059 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13060 runs.push((prev_end..label.text.len(), fade_out));
13061 }
13062
13063 runs
13064 })
13065}
13066
13067pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13068 let mut prev_index = 0;
13069 let mut prev_codepoint: Option<char> = None;
13070 text.char_indices()
13071 .chain([(text.len(), '\0')])
13072 .filter_map(move |(index, codepoint)| {
13073 let prev_codepoint = prev_codepoint.replace(codepoint)?;
13074 let is_boundary = index == text.len()
13075 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13076 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13077 if is_boundary {
13078 let chunk = &text[prev_index..index];
13079 prev_index = index;
13080 Some(chunk)
13081 } else {
13082 None
13083 }
13084 })
13085}
13086
13087pub trait RangeToAnchorExt: Sized {
13088 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13089
13090 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13091 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13092 anchor_range.start.to_display_point(&snapshot)..anchor_range.end.to_display_point(&snapshot)
13093 }
13094}
13095
13096impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13097 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13098 let start_offset = self.start.to_offset(snapshot);
13099 let end_offset = self.end.to_offset(snapshot);
13100 if start_offset == end_offset {
13101 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13102 } else {
13103 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13104 }
13105 }
13106}
13107
13108pub trait RowExt {
13109 fn as_f32(&self) -> f32;
13110
13111 fn next_row(&self) -> Self;
13112
13113 fn previous_row(&self) -> Self;
13114
13115 fn minus(&self, other: Self) -> u32;
13116}
13117
13118impl RowExt for DisplayRow {
13119 fn as_f32(&self) -> f32 {
13120 self.0 as f32
13121 }
13122
13123 fn next_row(&self) -> Self {
13124 Self(self.0 + 1)
13125 }
13126
13127 fn previous_row(&self) -> Self {
13128 Self(self.0.saturating_sub(1))
13129 }
13130
13131 fn minus(&self, other: Self) -> u32 {
13132 self.0 - other.0
13133 }
13134}
13135
13136impl RowExt for MultiBufferRow {
13137 fn as_f32(&self) -> f32 {
13138 self.0 as f32
13139 }
13140
13141 fn next_row(&self) -> Self {
13142 Self(self.0 + 1)
13143 }
13144
13145 fn previous_row(&self) -> Self {
13146 Self(self.0.saturating_sub(1))
13147 }
13148
13149 fn minus(&self, other: Self) -> u32 {
13150 self.0 - other.0
13151 }
13152}
13153
13154trait RowRangeExt {
13155 type Row;
13156
13157 fn len(&self) -> usize;
13158
13159 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13160}
13161
13162impl RowRangeExt for Range<MultiBufferRow> {
13163 type Row = MultiBufferRow;
13164
13165 fn len(&self) -> usize {
13166 (self.end.0 - self.start.0) as usize
13167 }
13168
13169 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13170 (self.start.0..self.end.0).map(MultiBufferRow)
13171 }
13172}
13173
13174impl RowRangeExt for Range<DisplayRow> {
13175 type Row = DisplayRow;
13176
13177 fn len(&self) -> usize {
13178 (self.end.0 - self.start.0) as usize
13179 }
13180
13181 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13182 (self.start.0..self.end.0).map(DisplayRow)
13183 }
13184}
13185
13186fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13187 if hunk.diff_base_byte_range.is_empty() {
13188 DiffHunkStatus::Added
13189 } else if hunk.associated_range.is_empty() {
13190 DiffHunkStatus::Removed
13191 } else {
13192 DiffHunkStatus::Modified
13193 }
13194}