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 behaviour.
15pub mod actions;
16mod blame_entry_tooltip;
17mod blink_manager;
18mod debounced_delay;
19pub mod display_map;
20mod editor_settings;
21mod element;
22mod git;
23mod highlight_matching_bracket;
24mod hover_links;
25mod hover_popover;
26mod hunk_diff;
27mod indent_guides;
28mod inlay_hint_cache;
29mod inline_completion_provider;
30pub mod items;
31mod linked_editing_ranges;
32mod mouse_context_menu;
33pub mod movement;
34mod persistence;
35mod rust_analyzer_ext;
36pub mod scroll;
37mod selections_collection;
38pub mod tasks;
39
40#[cfg(test)]
41mod editor_tests;
42mod signature_help;
43#[cfg(any(test, feature = "test-support"))]
44pub mod test;
45
46use ::git::diff::{DiffHunk, DiffHunkStatus};
47use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
48pub(crate) use actions::*;
49use aho_corasick::AhoCorasick;
50use anyhow::{anyhow, Context as _, Result};
51use blink_manager::BlinkManager;
52use client::{Collaborator, ParticipantIndex};
53use clock::ReplicaId;
54use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
55use convert_case::{Case, Casing};
56use debounced_delay::DebouncedDelay;
57use display_map::*;
58pub use display_map::{DisplayPoint, FoldPlaceholder};
59pub use editor_settings::{CurrentLineHighlight, EditorSettings};
60use element::LineWithInvisibles;
61pub use element::{
62 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
63};
64use futures::FutureExt;
65use fuzzy::{StringMatch, StringMatchCandidate};
66use git::blame::GitBlame;
67use git::diff_hunk_to_display;
68use gpui::{
69 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
70 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardItem,
71 Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle, FocusOutEvent,
72 FocusableView, FontId, FontStyle, FontWeight, HighlightStyle, Hsla, InteractiveText,
73 KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
74 SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
75 UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext,
76 WeakFocusHandle, WeakView, WhiteSpace, WindowContext,
77};
78use highlight_matching_bracket::refresh_matching_bracket_highlights;
79use hover_popover::{hide_hover, HoverState};
80use hunk_diff::ExpandedHunks;
81pub(crate) use hunk_diff::HoveredHunk;
82use indent_guides::ActiveIndentGuidesState;
83use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
84pub use inline_completion_provider::*;
85pub use items::MAX_TAB_TITLE_LEN;
86use itertools::Itertools;
87use language::{
88 char_kind,
89 language_settings::{self, all_language_settings, InlayHintSettings},
90 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
91 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
92 Point, Selection, SelectionGoal, TransactionId,
93};
94use language::{point_to_lsp, BufferRow, Runnable, RunnableRange};
95use linked_editing_ranges::refresh_linked_ranges;
96use task::{ResolvedTask, TaskTemplate, TaskVariables};
97
98use hover_links::{HoverLink, HoveredLinkState, InlayHighlight};
99pub use lsp::CompletionContext;
100use lsp::{
101 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
102 LanguageServerId,
103};
104use mouse_context_menu::MouseContextMenu;
105use movement::TextLayoutDetails;
106pub use multi_buffer::{
107 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
108 ToPoint,
109};
110use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
111use ordered_float::OrderedFloat;
112use parking_lot::{Mutex, RwLock};
113use project::project_settings::{GitGutterSetting, ProjectSettings};
114use project::{
115 CodeAction, Completion, FormatTrigger, Item, Location, Project, ProjectPath,
116 ProjectTransaction, TaskSourceKind, WorktreeId,
117};
118use rand::prelude::*;
119use rpc::{proto::*, ErrorExt};
120use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
121use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
122use serde::{Deserialize, Serialize};
123use settings::{update_settings_file, Settings, SettingsStore};
124use smallvec::SmallVec;
125use snippet::Snippet;
126use std::{
127 any::TypeId,
128 borrow::Cow,
129 cell::RefCell,
130 cmp::{self, Ordering, Reverse},
131 mem,
132 num::NonZeroU32,
133 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
134 path::{Path, PathBuf},
135 rc::Rc,
136 sync::Arc,
137 time::{Duration, Instant},
138};
139pub use sum_tree::Bias;
140use sum_tree::TreeMap;
141use text::{BufferId, OffsetUtf16, Rope};
142use theme::{
143 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
144 ThemeColors, ThemeSettings,
145};
146use ui::{
147 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
148 ListItem, Popover, Tooltip,
149};
150use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
151use workspace::item::{ItemHandle, PreviewTabsSettings};
152use workspace::notifications::{DetachAndPromptErr, NotificationId};
153use workspace::{
154 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
155};
156use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
157
158use crate::hover_links::find_url;
159use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
160
161pub const FILE_HEADER_HEIGHT: u8 = 1;
162pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u8 = 1;
163pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u8 = 1;
164pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
165const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
166const MAX_LINE_LEN: usize = 1024;
167const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
168const MAX_SELECTION_HISTORY_LEN: usize = 1024;
169pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
170#[doc(hidden)]
171pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
172#[doc(hidden)]
173pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
174
175pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
176
177pub fn render_parsed_markdown(
178 element_id: impl Into<ElementId>,
179 parsed: &language::ParsedMarkdown,
180 editor_style: &EditorStyle,
181 workspace: Option<WeakView<Workspace>>,
182 cx: &mut WindowContext,
183) -> InteractiveText {
184 let code_span_background_color = cx
185 .theme()
186 .colors()
187 .editor_document_highlight_read_background;
188
189 let highlights = gpui::combine_highlights(
190 parsed.highlights.iter().filter_map(|(range, highlight)| {
191 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
192 Some((range.clone(), highlight))
193 }),
194 parsed
195 .regions
196 .iter()
197 .zip(&parsed.region_ranges)
198 .filter_map(|(region, range)| {
199 if region.code {
200 Some((
201 range.clone(),
202 HighlightStyle {
203 background_color: Some(code_span_background_color),
204 ..Default::default()
205 },
206 ))
207 } else {
208 None
209 }
210 }),
211 );
212
213 let mut links = Vec::new();
214 let mut link_ranges = Vec::new();
215 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
216 if let Some(link) = region.link.clone() {
217 links.push(link);
218 link_ranges.push(range.clone());
219 }
220 }
221
222 InteractiveText::new(
223 element_id,
224 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
225 )
226 .on_click(link_ranges, move |clicked_range_ix, cx| {
227 match &links[clicked_range_ix] {
228 markdown::Link::Web { url } => cx.open_url(url),
229 markdown::Link::Path { path } => {
230 if let Some(workspace) = &workspace {
231 _ = workspace.update(cx, |workspace, cx| {
232 workspace.open_abs_path(path.clone(), false, cx).detach();
233 });
234 }
235 }
236 }
237 })
238}
239
240#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
241pub(crate) enum InlayId {
242 Suggestion(usize),
243 Hint(usize),
244}
245
246impl InlayId {
247 fn id(&self) -> usize {
248 match self {
249 Self::Suggestion(id) => *id,
250 Self::Hint(id) => *id,
251 }
252 }
253}
254
255enum DiffRowHighlight {}
256enum DocumentHighlightRead {}
257enum DocumentHighlightWrite {}
258enum InputComposition {}
259
260#[derive(Copy, Clone, PartialEq, Eq)]
261pub enum Direction {
262 Prev,
263 Next,
264}
265
266pub fn init_settings(cx: &mut AppContext) {
267 EditorSettings::register(cx);
268}
269
270pub fn init(cx: &mut AppContext) {
271 init_settings(cx);
272
273 workspace::register_project_item::<Editor>(cx);
274 workspace::FollowableViewRegistry::register::<Editor>(cx);
275 workspace::register_serializable_item::<Editor>(cx);
276
277 cx.observe_new_views(
278 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
279 workspace.register_action(Editor::new_file);
280 workspace.register_action(Editor::new_file_in_direction);
281 },
282 )
283 .detach();
284
285 cx.on_action(move |_: &workspace::NewFile, cx| {
286 let app_state = workspace::AppState::global(cx);
287 if let Some(app_state) = app_state.upgrade() {
288 workspace::open_new(app_state, cx, |workspace, cx| {
289 Editor::new_file(workspace, &Default::default(), cx)
290 })
291 .detach();
292 }
293 });
294 cx.on_action(move |_: &workspace::NewWindow, cx| {
295 let app_state = workspace::AppState::global(cx);
296 if let Some(app_state) = app_state.upgrade() {
297 workspace::open_new(app_state, cx, |workspace, cx| {
298 Editor::new_file(workspace, &Default::default(), cx)
299 })
300 .detach();
301 }
302 });
303}
304
305pub struct SearchWithinRange;
306
307trait InvalidationRegion {
308 fn ranges(&self) -> &[Range<Anchor>];
309}
310
311#[derive(Clone, Debug, PartialEq)]
312pub enum SelectPhase {
313 Begin {
314 position: DisplayPoint,
315 add: bool,
316 click_count: usize,
317 },
318 BeginColumnar {
319 position: DisplayPoint,
320 reset: bool,
321 goal_column: u32,
322 },
323 Extend {
324 position: DisplayPoint,
325 click_count: usize,
326 },
327 Update {
328 position: DisplayPoint,
329 goal_column: u32,
330 scroll_delta: gpui::Point<f32>,
331 },
332 End,
333}
334
335#[derive(Clone, Debug)]
336pub enum SelectMode {
337 Character,
338 Word(Range<Anchor>),
339 Line(Range<Anchor>),
340 All,
341}
342
343#[derive(Copy, Clone, PartialEq, Eq, Debug)]
344pub enum EditorMode {
345 SingleLine { auto_width: bool },
346 AutoHeight { max_lines: usize },
347 Full,
348}
349
350#[derive(Clone, Debug)]
351pub enum SoftWrap {
352 None,
353 PreferLine,
354 EditorWidth,
355 Column(u32),
356}
357
358#[derive(Clone)]
359pub struct EditorStyle {
360 pub background: Hsla,
361 pub local_player: PlayerColor,
362 pub text: TextStyle,
363 pub scrollbar_width: Pixels,
364 pub syntax: Arc<SyntaxTheme>,
365 pub status: StatusColors,
366 pub inlay_hints_style: HighlightStyle,
367 pub suggestions_style: HighlightStyle,
368}
369
370impl Default for EditorStyle {
371 fn default() -> Self {
372 Self {
373 background: Hsla::default(),
374 local_player: PlayerColor::default(),
375 text: TextStyle::default(),
376 scrollbar_width: Pixels::default(),
377 syntax: Default::default(),
378 // HACK: Status colors don't have a real default.
379 // We should look into removing the status colors from the editor
380 // style and retrieve them directly from the theme.
381 status: StatusColors::dark(),
382 inlay_hints_style: HighlightStyle::default(),
383 suggestions_style: HighlightStyle::default(),
384 }
385 }
386}
387
388type CompletionId = usize;
389
390#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
391struct EditorActionId(usize);
392
393impl EditorActionId {
394 pub fn post_inc(&mut self) -> Self {
395 let answer = self.0;
396
397 *self = Self(answer + 1);
398
399 Self(answer)
400 }
401}
402
403// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
404// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
405
406type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
407type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
408
409struct ScrollbarMarkerState {
410 scrollbar_size: Size<Pixels>,
411 dirty: bool,
412 markers: Arc<[PaintQuad]>,
413 pending_refresh: Option<Task<Result<()>>>,
414}
415
416impl ScrollbarMarkerState {
417 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
418 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
419 }
420}
421
422impl Default for ScrollbarMarkerState {
423 fn default() -> Self {
424 Self {
425 scrollbar_size: Size::default(),
426 dirty: false,
427 markers: Arc::from([]),
428 pending_refresh: None,
429 }
430 }
431}
432
433#[derive(Clone, Debug)]
434struct RunnableTasks {
435 templates: Vec<(TaskSourceKind, TaskTemplate)>,
436 offset: MultiBufferOffset,
437 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
438 column: u32,
439 // Values of all named captures, including those starting with '_'
440 extra_variables: HashMap<String, String>,
441 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
442 context_range: Range<BufferOffset>,
443}
444
445#[derive(Clone)]
446struct ResolvedTasks {
447 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
448 position: Anchor,
449}
450#[derive(Copy, Clone, Debug)]
451struct MultiBufferOffset(usize);
452#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
453struct BufferOffset(usize);
454/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
455///
456/// See the [module level documentation](self) for more information.
457pub struct Editor {
458 focus_handle: FocusHandle,
459 last_focused_descendant: Option<WeakFocusHandle>,
460 /// The text buffer being edited
461 buffer: Model<MultiBuffer>,
462 /// Map of how text in the buffer should be displayed.
463 /// Handles soft wraps, folds, fake inlay text insertions, etc.
464 pub display_map: Model<DisplayMap>,
465 pub selections: SelectionsCollection,
466 pub scroll_manager: ScrollManager,
467 /// When inline assist editors are linked, they all render cursors because
468 /// typing enters text into each of them, even the ones that aren't focused.
469 pub(crate) show_cursor_when_unfocused: bool,
470 columnar_selection_tail: Option<Anchor>,
471 add_selections_state: Option<AddSelectionsState>,
472 select_next_state: Option<SelectNextState>,
473 select_prev_state: Option<SelectNextState>,
474 selection_history: SelectionHistory,
475 autoclose_regions: Vec<AutocloseRegion>,
476 snippet_stack: InvalidationStack<SnippetState>,
477 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
478 ime_transaction: Option<TransactionId>,
479 active_diagnostics: Option<ActiveDiagnosticGroup>,
480 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
481 project: Option<Model<Project>>,
482 completion_provider: Option<Box<dyn CompletionProvider>>,
483 collaboration_hub: Option<Box<dyn CollaborationHub>>,
484 blink_manager: Model<BlinkManager>,
485 show_cursor_names: bool,
486 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
487 pub show_local_selections: bool,
488 mode: EditorMode,
489 show_breadcrumbs: bool,
490 show_gutter: bool,
491 show_line_numbers: Option<bool>,
492 show_git_diff_gutter: Option<bool>,
493 show_code_actions: Option<bool>,
494 show_runnables: Option<bool>,
495 show_wrap_guides: Option<bool>,
496 show_indent_guides: Option<bool>,
497 placeholder_text: Option<Arc<str>>,
498 highlight_order: usize,
499 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
500 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
501 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
502 scrollbar_marker_state: ScrollbarMarkerState,
503 active_indent_guides_state: ActiveIndentGuidesState,
504 nav_history: Option<ItemNavHistory>,
505 context_menu: RwLock<Option<ContextMenu>>,
506 mouse_context_menu: Option<MouseContextMenu>,
507 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
508 signature_help_state: SignatureHelpState,
509 auto_signature_help: Option<bool>,
510 find_all_references_task_sources: Vec<Anchor>,
511 next_completion_id: CompletionId,
512 completion_documentation_pre_resolve_debounce: DebouncedDelay,
513 available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
514 code_actions_task: Option<Task<()>>,
515 document_highlights_task: Option<Task<()>>,
516 linked_editing_range_task: Option<Task<Option<()>>>,
517 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
518 pending_rename: Option<RenameState>,
519 searchable: bool,
520 cursor_shape: CursorShape,
521 current_line_highlight: Option<CurrentLineHighlight>,
522 collapse_matches: bool,
523 autoindent_mode: Option<AutoindentMode>,
524 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
525 keymap_context_layers: BTreeMap<TypeId, KeyContext>,
526 input_enabled: bool,
527 use_modal_editing: bool,
528 read_only: bool,
529 leader_peer_id: Option<PeerId>,
530 remote_id: Option<ViewId>,
531 hover_state: HoverState,
532 gutter_hovered: bool,
533 hovered_link_state: Option<HoveredLinkState>,
534 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
535 active_inline_completion: Option<Inlay>,
536 show_inline_completions: bool,
537 inlay_hint_cache: InlayHintCache,
538 expanded_hunks: ExpandedHunks,
539 next_inlay_id: usize,
540 _subscriptions: Vec<Subscription>,
541 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
542 gutter_dimensions: GutterDimensions,
543 pub vim_replace_map: HashMap<Range<usize>, String>,
544 style: Option<EditorStyle>,
545 next_editor_action_id: EditorActionId,
546 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
547 use_autoclose: bool,
548 use_auto_surround: bool,
549 auto_replace_emoji_shortcode: bool,
550 show_git_blame_gutter: bool,
551 show_git_blame_inline: bool,
552 show_git_blame_inline_delay_task: Option<Task<()>>,
553 git_blame_inline_enabled: bool,
554 serialize_dirty_buffers: bool,
555 show_selection_menu: Option<bool>,
556 blame: Option<Model<GitBlame>>,
557 blame_subscription: Option<Subscription>,
558 custom_context_menu: Option<
559 Box<
560 dyn 'static
561 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
562 >,
563 >,
564 last_bounds: Option<Bounds<Pixels>>,
565 expect_bounds_change: Option<Bounds<Pixels>>,
566 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
567 tasks_update_task: Option<Task<()>>,
568 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
569 file_header_size: u8,
570 breadcrumb_header: Option<String>,
571 focused_block: Option<FocusedBlock>,
572}
573
574#[derive(Clone)]
575pub struct EditorSnapshot {
576 pub mode: EditorMode,
577 show_gutter: bool,
578 show_line_numbers: Option<bool>,
579 show_git_diff_gutter: Option<bool>,
580 show_code_actions: Option<bool>,
581 show_runnables: Option<bool>,
582 render_git_blame_gutter: bool,
583 pub display_snapshot: DisplaySnapshot,
584 pub placeholder_text: Option<Arc<str>>,
585 is_focused: bool,
586 scroll_anchor: ScrollAnchor,
587 ongoing_scroll: OngoingScroll,
588 current_line_highlight: CurrentLineHighlight,
589 gutter_hovered: bool,
590}
591
592const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
593
594#[derive(Debug, Clone, Copy)]
595pub struct GutterDimensions {
596 pub left_padding: Pixels,
597 pub right_padding: Pixels,
598 pub width: Pixels,
599 pub margin: Pixels,
600 pub git_blame_entries_width: Option<Pixels>,
601}
602
603impl GutterDimensions {
604 /// The full width of the space taken up by the gutter.
605 pub fn full_width(&self) -> Pixels {
606 self.margin + self.width
607 }
608
609 /// The width of the space reserved for the fold indicators,
610 /// use alongside 'justify_end' and `gutter_width` to
611 /// right align content with the line numbers
612 pub fn fold_area_width(&self) -> Pixels {
613 self.margin + self.right_padding
614 }
615}
616
617impl Default for GutterDimensions {
618 fn default() -> Self {
619 Self {
620 left_padding: Pixels::ZERO,
621 right_padding: Pixels::ZERO,
622 width: Pixels::ZERO,
623 margin: Pixels::ZERO,
624 git_blame_entries_width: None,
625 }
626 }
627}
628
629#[derive(Debug)]
630pub struct RemoteSelection {
631 pub replica_id: ReplicaId,
632 pub selection: Selection<Anchor>,
633 pub cursor_shape: CursorShape,
634 pub peer_id: PeerId,
635 pub line_mode: bool,
636 pub participant_index: Option<ParticipantIndex>,
637 pub user_name: Option<SharedString>,
638}
639
640#[derive(Clone, Debug)]
641struct SelectionHistoryEntry {
642 selections: Arc<[Selection<Anchor>]>,
643 select_next_state: Option<SelectNextState>,
644 select_prev_state: Option<SelectNextState>,
645 add_selections_state: Option<AddSelectionsState>,
646}
647
648enum SelectionHistoryMode {
649 Normal,
650 Undoing,
651 Redoing,
652}
653
654#[derive(Clone, PartialEq, Eq, Hash)]
655struct HoveredCursor {
656 replica_id: u16,
657 selection_id: usize,
658}
659
660impl Default for SelectionHistoryMode {
661 fn default() -> Self {
662 Self::Normal
663 }
664}
665
666#[derive(Default)]
667struct SelectionHistory {
668 #[allow(clippy::type_complexity)]
669 selections_by_transaction:
670 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
671 mode: SelectionHistoryMode,
672 undo_stack: VecDeque<SelectionHistoryEntry>,
673 redo_stack: VecDeque<SelectionHistoryEntry>,
674}
675
676impl SelectionHistory {
677 fn insert_transaction(
678 &mut self,
679 transaction_id: TransactionId,
680 selections: Arc<[Selection<Anchor>]>,
681 ) {
682 self.selections_by_transaction
683 .insert(transaction_id, (selections, None));
684 }
685
686 #[allow(clippy::type_complexity)]
687 fn transaction(
688 &self,
689 transaction_id: TransactionId,
690 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
691 self.selections_by_transaction.get(&transaction_id)
692 }
693
694 #[allow(clippy::type_complexity)]
695 fn transaction_mut(
696 &mut self,
697 transaction_id: TransactionId,
698 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
699 self.selections_by_transaction.get_mut(&transaction_id)
700 }
701
702 fn push(&mut self, entry: SelectionHistoryEntry) {
703 if !entry.selections.is_empty() {
704 match self.mode {
705 SelectionHistoryMode::Normal => {
706 self.push_undo(entry);
707 self.redo_stack.clear();
708 }
709 SelectionHistoryMode::Undoing => self.push_redo(entry),
710 SelectionHistoryMode::Redoing => self.push_undo(entry),
711 }
712 }
713 }
714
715 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
716 if self
717 .undo_stack
718 .back()
719 .map_or(true, |e| e.selections != entry.selections)
720 {
721 self.undo_stack.push_back(entry);
722 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
723 self.undo_stack.pop_front();
724 }
725 }
726 }
727
728 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
729 if self
730 .redo_stack
731 .back()
732 .map_or(true, |e| e.selections != entry.selections)
733 {
734 self.redo_stack.push_back(entry);
735 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
736 self.redo_stack.pop_front();
737 }
738 }
739 }
740}
741
742struct RowHighlight {
743 index: usize,
744 range: RangeInclusive<Anchor>,
745 color: Option<Hsla>,
746 should_autoscroll: bool,
747}
748
749#[derive(Clone, Debug)]
750struct AddSelectionsState {
751 above: bool,
752 stack: Vec<usize>,
753}
754
755#[derive(Clone)]
756struct SelectNextState {
757 query: AhoCorasick,
758 wordwise: bool,
759 done: bool,
760}
761
762impl std::fmt::Debug for SelectNextState {
763 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
764 f.debug_struct(std::any::type_name::<Self>())
765 .field("wordwise", &self.wordwise)
766 .field("done", &self.done)
767 .finish()
768 }
769}
770
771#[derive(Debug)]
772struct AutocloseRegion {
773 selection_id: usize,
774 range: Range<Anchor>,
775 pair: BracketPair,
776}
777
778#[derive(Debug)]
779struct SnippetState {
780 ranges: Vec<Vec<Range<Anchor>>>,
781 active_index: usize,
782}
783
784#[doc(hidden)]
785pub struct RenameState {
786 pub range: Range<Anchor>,
787 pub old_name: Arc<str>,
788 pub editor: View<Editor>,
789 block_id: CustomBlockId,
790}
791
792struct InvalidationStack<T>(Vec<T>);
793
794struct RegisteredInlineCompletionProvider {
795 provider: Arc<dyn InlineCompletionProviderHandle>,
796 _subscription: Subscription,
797}
798
799enum ContextMenu {
800 Completions(CompletionsMenu),
801 CodeActions(CodeActionsMenu),
802}
803
804impl ContextMenu {
805 fn select_first(
806 &mut self,
807 project: Option<&Model<Project>>,
808 cx: &mut ViewContext<Editor>,
809 ) -> bool {
810 if self.visible() {
811 match self {
812 ContextMenu::Completions(menu) => menu.select_first(project, cx),
813 ContextMenu::CodeActions(menu) => menu.select_first(cx),
814 }
815 true
816 } else {
817 false
818 }
819 }
820
821 fn select_prev(
822 &mut self,
823 project: Option<&Model<Project>>,
824 cx: &mut ViewContext<Editor>,
825 ) -> bool {
826 if self.visible() {
827 match self {
828 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
829 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
830 }
831 true
832 } else {
833 false
834 }
835 }
836
837 fn select_next(
838 &mut self,
839 project: Option<&Model<Project>>,
840 cx: &mut ViewContext<Editor>,
841 ) -> bool {
842 if self.visible() {
843 match self {
844 ContextMenu::Completions(menu) => menu.select_next(project, cx),
845 ContextMenu::CodeActions(menu) => menu.select_next(cx),
846 }
847 true
848 } else {
849 false
850 }
851 }
852
853 fn select_last(
854 &mut self,
855 project: Option<&Model<Project>>,
856 cx: &mut ViewContext<Editor>,
857 ) -> bool {
858 if self.visible() {
859 match self {
860 ContextMenu::Completions(menu) => menu.select_last(project, cx),
861 ContextMenu::CodeActions(menu) => menu.select_last(cx),
862 }
863 true
864 } else {
865 false
866 }
867 }
868
869 fn visible(&self) -> bool {
870 match self {
871 ContextMenu::Completions(menu) => menu.visible(),
872 ContextMenu::CodeActions(menu) => menu.visible(),
873 }
874 }
875
876 fn render(
877 &self,
878 cursor_position: DisplayPoint,
879 style: &EditorStyle,
880 max_height: Pixels,
881 workspace: Option<WeakView<Workspace>>,
882 cx: &mut ViewContext<Editor>,
883 ) -> (ContextMenuOrigin, AnyElement) {
884 match self {
885 ContextMenu::Completions(menu) => (
886 ContextMenuOrigin::EditorPoint(cursor_position),
887 menu.render(style, max_height, workspace, cx),
888 ),
889 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
890 }
891 }
892}
893
894enum ContextMenuOrigin {
895 EditorPoint(DisplayPoint),
896 GutterIndicator(DisplayRow),
897}
898
899#[derive(Clone)]
900struct CompletionsMenu {
901 id: CompletionId,
902 initial_position: Anchor,
903 buffer: Model<Buffer>,
904 completions: Arc<RwLock<Box<[Completion]>>>,
905 match_candidates: Arc<[StringMatchCandidate]>,
906 matches: Arc<[StringMatch]>,
907 selected_item: usize,
908 scroll_handle: UniformListScrollHandle,
909 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
910}
911
912impl CompletionsMenu {
913 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
914 self.selected_item = 0;
915 self.scroll_handle.scroll_to_item(self.selected_item);
916 self.attempt_resolve_selected_completion_documentation(project, cx);
917 cx.notify();
918 }
919
920 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
921 if self.selected_item > 0 {
922 self.selected_item -= 1;
923 } else {
924 self.selected_item = self.matches.len() - 1;
925 }
926 self.scroll_handle.scroll_to_item(self.selected_item);
927 self.attempt_resolve_selected_completion_documentation(project, cx);
928 cx.notify();
929 }
930
931 fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
932 if self.selected_item + 1 < self.matches.len() {
933 self.selected_item += 1;
934 } else {
935 self.selected_item = 0;
936 }
937 self.scroll_handle.scroll_to_item(self.selected_item);
938 self.attempt_resolve_selected_completion_documentation(project, cx);
939 cx.notify();
940 }
941
942 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
943 self.selected_item = self.matches.len() - 1;
944 self.scroll_handle.scroll_to_item(self.selected_item);
945 self.attempt_resolve_selected_completion_documentation(project, cx);
946 cx.notify();
947 }
948
949 fn pre_resolve_completion_documentation(
950 buffer: Model<Buffer>,
951 completions: Arc<RwLock<Box<[Completion]>>>,
952 matches: Arc<[StringMatch]>,
953 editor: &Editor,
954 cx: &mut ViewContext<Editor>,
955 ) -> Task<()> {
956 let settings = EditorSettings::get_global(cx);
957 if !settings.show_completion_documentation {
958 return Task::ready(());
959 }
960
961 let Some(provider) = editor.completion_provider.as_ref() else {
962 return Task::ready(());
963 };
964
965 let resolve_task = provider.resolve_completions(
966 buffer,
967 matches.iter().map(|m| m.candidate_id).collect(),
968 completions.clone(),
969 cx,
970 );
971
972 return cx.spawn(move |this, mut cx| async move {
973 if let Some(true) = resolve_task.await.log_err() {
974 this.update(&mut cx, |_, cx| cx.notify()).ok();
975 }
976 });
977 }
978
979 fn attempt_resolve_selected_completion_documentation(
980 &mut self,
981 project: Option<&Model<Project>>,
982 cx: &mut ViewContext<Editor>,
983 ) {
984 let settings = EditorSettings::get_global(cx);
985 if !settings.show_completion_documentation {
986 return;
987 }
988
989 let completion_index = self.matches[self.selected_item].candidate_id;
990 let Some(project) = project else {
991 return;
992 };
993
994 let resolve_task = project.update(cx, |project, cx| {
995 project.resolve_completions(
996 self.buffer.clone(),
997 vec![completion_index],
998 self.completions.clone(),
999 cx,
1000 )
1001 });
1002
1003 let delay_ms =
1004 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1005 let delay = Duration::from_millis(delay_ms);
1006
1007 self.selected_completion_documentation_resolve_debounce
1008 .lock()
1009 .fire_new(delay, cx, |_, cx| {
1010 cx.spawn(move |this, mut cx| async move {
1011 if let Some(true) = resolve_task.await.log_err() {
1012 this.update(&mut cx, |_, cx| cx.notify()).ok();
1013 }
1014 })
1015 });
1016 }
1017
1018 fn visible(&self) -> bool {
1019 !self.matches.is_empty()
1020 }
1021
1022 fn render(
1023 &self,
1024 style: &EditorStyle,
1025 max_height: Pixels,
1026 workspace: Option<WeakView<Workspace>>,
1027 cx: &mut ViewContext<Editor>,
1028 ) -> AnyElement {
1029 let settings = EditorSettings::get_global(cx);
1030 let show_completion_documentation = settings.show_completion_documentation;
1031
1032 let widest_completion_ix = self
1033 .matches
1034 .iter()
1035 .enumerate()
1036 .max_by_key(|(_, mat)| {
1037 let completions = self.completions.read();
1038 let completion = &completions[mat.candidate_id];
1039 let documentation = &completion.documentation;
1040
1041 let mut len = completion.label.text.chars().count();
1042 if let Some(Documentation::SingleLine(text)) = documentation {
1043 if show_completion_documentation {
1044 len += text.chars().count();
1045 }
1046 }
1047
1048 len
1049 })
1050 .map(|(ix, _)| ix);
1051
1052 let completions = self.completions.clone();
1053 let matches = self.matches.clone();
1054 let selected_item = self.selected_item;
1055 let style = style.clone();
1056
1057 let multiline_docs = if show_completion_documentation {
1058 let mat = &self.matches[selected_item];
1059 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1060 Some(Documentation::MultiLinePlainText(text)) => {
1061 Some(div().child(SharedString::from(text.clone())))
1062 }
1063 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1064 Some(div().child(render_parsed_markdown(
1065 "completions_markdown",
1066 parsed,
1067 &style,
1068 workspace,
1069 cx,
1070 )))
1071 }
1072 _ => None,
1073 };
1074 multiline_docs.map(|div| {
1075 div.id("multiline_docs")
1076 .max_h(max_height)
1077 .flex_1()
1078 .px_1p5()
1079 .py_1()
1080 .min_w(px(260.))
1081 .max_w(px(640.))
1082 .w(px(500.))
1083 .overflow_y_scroll()
1084 .occlude()
1085 })
1086 } else {
1087 None
1088 };
1089
1090 let list = uniform_list(
1091 cx.view().clone(),
1092 "completions",
1093 matches.len(),
1094 move |_editor, range, cx| {
1095 let start_ix = range.start;
1096 let completions_guard = completions.read();
1097
1098 matches[range]
1099 .iter()
1100 .enumerate()
1101 .map(|(ix, mat)| {
1102 let item_ix = start_ix + ix;
1103 let candidate_id = mat.candidate_id;
1104 let completion = &completions_guard[candidate_id];
1105
1106 let documentation = if show_completion_documentation {
1107 &completion.documentation
1108 } else {
1109 &None
1110 };
1111
1112 let highlights = gpui::combine_highlights(
1113 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1114 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1115 |(range, mut highlight)| {
1116 // Ignore font weight for syntax highlighting, as we'll use it
1117 // for fuzzy matches.
1118 highlight.font_weight = None;
1119
1120 if completion.lsp_completion.deprecated.unwrap_or(false) {
1121 highlight.strikethrough = Some(StrikethroughStyle {
1122 thickness: 1.0.into(),
1123 ..Default::default()
1124 });
1125 highlight.color = Some(cx.theme().colors().text_muted);
1126 }
1127
1128 (range, highlight)
1129 },
1130 ),
1131 );
1132 let completion_label = StyledText::new(completion.label.text.clone())
1133 .with_highlights(&style.text, highlights);
1134 let documentation_label =
1135 if let Some(Documentation::SingleLine(text)) = documentation {
1136 if text.trim().is_empty() {
1137 None
1138 } else {
1139 Some(
1140 Label::new(text.clone())
1141 .ml_4()
1142 .size(LabelSize::Small)
1143 .color(Color::Muted),
1144 )
1145 }
1146 } else {
1147 None
1148 };
1149
1150 div().min_w(px(220.)).max_w(px(540.)).child(
1151 ListItem::new(mat.candidate_id)
1152 .inset(true)
1153 .selected(item_ix == selected_item)
1154 .on_click(cx.listener(move |editor, _event, cx| {
1155 cx.stop_propagation();
1156 if let Some(task) = editor.confirm_completion(
1157 &ConfirmCompletion {
1158 item_ix: Some(item_ix),
1159 },
1160 cx,
1161 ) {
1162 task.detach_and_log_err(cx)
1163 }
1164 }))
1165 .child(h_flex().overflow_hidden().child(completion_label))
1166 .end_slot::<Label>(documentation_label),
1167 )
1168 })
1169 .collect()
1170 },
1171 )
1172 .occlude()
1173 .max_h(max_height)
1174 .track_scroll(self.scroll_handle.clone())
1175 .with_width_from_item(widest_completion_ix)
1176 .with_sizing_behavior(ListSizingBehavior::Infer);
1177
1178 Popover::new()
1179 .child(list)
1180 .when_some(multiline_docs, |popover, multiline_docs| {
1181 popover.aside(multiline_docs)
1182 })
1183 .into_any_element()
1184 }
1185
1186 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1187 let mut matches = if let Some(query) = query {
1188 fuzzy::match_strings(
1189 &self.match_candidates,
1190 query,
1191 query.chars().any(|c| c.is_uppercase()),
1192 100,
1193 &Default::default(),
1194 executor,
1195 )
1196 .await
1197 } else {
1198 self.match_candidates
1199 .iter()
1200 .enumerate()
1201 .map(|(candidate_id, candidate)| StringMatch {
1202 candidate_id,
1203 score: Default::default(),
1204 positions: Default::default(),
1205 string: candidate.string.clone(),
1206 })
1207 .collect()
1208 };
1209
1210 // Remove all candidates where the query's start does not match the start of any word in the candidate
1211 if let Some(query) = query {
1212 if let Some(query_start) = query.chars().next() {
1213 matches.retain(|string_match| {
1214 split_words(&string_match.string).any(|word| {
1215 // Check that the first codepoint of the word as lowercase matches the first
1216 // codepoint of the query as lowercase
1217 word.chars()
1218 .flat_map(|codepoint| codepoint.to_lowercase())
1219 .zip(query_start.to_lowercase())
1220 .all(|(word_cp, query_cp)| word_cp == query_cp)
1221 })
1222 });
1223 }
1224 }
1225
1226 let completions = self.completions.read();
1227 matches.sort_unstable_by_key(|mat| {
1228 // We do want to strike a balance here between what the language server tells us
1229 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1230 // `Creat` and there is a local variable called `CreateComponent`).
1231 // So what we do is: we bucket all matches into two buckets
1232 // - Strong matches
1233 // - Weak matches
1234 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1235 // and the Weak matches are the rest.
1236 //
1237 // For the strong matches, we sort by the language-servers score first and for the weak
1238 // matches, we prefer our fuzzy finder first.
1239 //
1240 // The thinking behind that: it's useless to take the sort_text the language-server gives
1241 // us into account when it's obviously a bad match.
1242
1243 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1244 enum MatchScore<'a> {
1245 Strong {
1246 sort_text: Option<&'a str>,
1247 score: Reverse<OrderedFloat<f64>>,
1248 sort_key: (usize, &'a str),
1249 },
1250 Weak {
1251 score: Reverse<OrderedFloat<f64>>,
1252 sort_text: Option<&'a str>,
1253 sort_key: (usize, &'a str),
1254 },
1255 }
1256
1257 let completion = &completions[mat.candidate_id];
1258 let sort_key = completion.sort_key();
1259 let sort_text = completion.lsp_completion.sort_text.as_deref();
1260 let score = Reverse(OrderedFloat(mat.score));
1261
1262 if mat.score >= 0.2 {
1263 MatchScore::Strong {
1264 sort_text,
1265 score,
1266 sort_key,
1267 }
1268 } else {
1269 MatchScore::Weak {
1270 score,
1271 sort_text,
1272 sort_key,
1273 }
1274 }
1275 });
1276
1277 for mat in &mut matches {
1278 let completion = &completions[mat.candidate_id];
1279 mat.string.clone_from(&completion.label.text);
1280 for position in &mut mat.positions {
1281 *position += completion.label.filter_range.start;
1282 }
1283 }
1284 drop(completions);
1285
1286 self.matches = matches.into();
1287 self.selected_item = 0;
1288 }
1289}
1290
1291#[derive(Clone)]
1292struct CodeActionContents {
1293 tasks: Option<Arc<ResolvedTasks>>,
1294 actions: Option<Arc<[CodeAction]>>,
1295}
1296
1297impl CodeActionContents {
1298 fn len(&self) -> usize {
1299 match (&self.tasks, &self.actions) {
1300 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1301 (Some(tasks), None) => tasks.templates.len(),
1302 (None, Some(actions)) => actions.len(),
1303 (None, None) => 0,
1304 }
1305 }
1306
1307 fn is_empty(&self) -> bool {
1308 match (&self.tasks, &self.actions) {
1309 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1310 (Some(tasks), None) => tasks.templates.is_empty(),
1311 (None, Some(actions)) => actions.is_empty(),
1312 (None, None) => true,
1313 }
1314 }
1315
1316 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1317 self.tasks
1318 .iter()
1319 .flat_map(|tasks| {
1320 tasks
1321 .templates
1322 .iter()
1323 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1324 })
1325 .chain(self.actions.iter().flat_map(|actions| {
1326 actions
1327 .iter()
1328 .map(|action| CodeActionsItem::CodeAction(action.clone()))
1329 }))
1330 }
1331 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1332 match (&self.tasks, &self.actions) {
1333 (Some(tasks), Some(actions)) => {
1334 if index < tasks.templates.len() {
1335 tasks
1336 .templates
1337 .get(index)
1338 .cloned()
1339 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1340 } else {
1341 actions
1342 .get(index - tasks.templates.len())
1343 .cloned()
1344 .map(CodeActionsItem::CodeAction)
1345 }
1346 }
1347 (Some(tasks), None) => tasks
1348 .templates
1349 .get(index)
1350 .cloned()
1351 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1352 (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
1353 (None, None) => None,
1354 }
1355 }
1356}
1357
1358#[allow(clippy::large_enum_variant)]
1359#[derive(Clone)]
1360enum CodeActionsItem {
1361 Task(TaskSourceKind, ResolvedTask),
1362 CodeAction(CodeAction),
1363}
1364
1365impl CodeActionsItem {
1366 fn as_task(&self) -> Option<&ResolvedTask> {
1367 let Self::Task(_, task) = self else {
1368 return None;
1369 };
1370 Some(task)
1371 }
1372 fn as_code_action(&self) -> Option<&CodeAction> {
1373 let Self::CodeAction(action) = self else {
1374 return None;
1375 };
1376 Some(action)
1377 }
1378 fn label(&self) -> String {
1379 match self {
1380 Self::CodeAction(action) => action.lsp_action.title.clone(),
1381 Self::Task(_, task) => task.resolved_label.clone(),
1382 }
1383 }
1384}
1385
1386struct CodeActionsMenu {
1387 actions: CodeActionContents,
1388 buffer: Model<Buffer>,
1389 selected_item: usize,
1390 scroll_handle: UniformListScrollHandle,
1391 deployed_from_indicator: Option<DisplayRow>,
1392}
1393
1394impl CodeActionsMenu {
1395 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1396 self.selected_item = 0;
1397 self.scroll_handle.scroll_to_item(self.selected_item);
1398 cx.notify()
1399 }
1400
1401 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1402 if self.selected_item > 0 {
1403 self.selected_item -= 1;
1404 } else {
1405 self.selected_item = self.actions.len() - 1;
1406 }
1407 self.scroll_handle.scroll_to_item(self.selected_item);
1408 cx.notify();
1409 }
1410
1411 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1412 if self.selected_item + 1 < self.actions.len() {
1413 self.selected_item += 1;
1414 } else {
1415 self.selected_item = 0;
1416 }
1417 self.scroll_handle.scroll_to_item(self.selected_item);
1418 cx.notify();
1419 }
1420
1421 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1422 self.selected_item = self.actions.len() - 1;
1423 self.scroll_handle.scroll_to_item(self.selected_item);
1424 cx.notify()
1425 }
1426
1427 fn visible(&self) -> bool {
1428 !self.actions.is_empty()
1429 }
1430
1431 fn render(
1432 &self,
1433 cursor_position: DisplayPoint,
1434 _style: &EditorStyle,
1435 max_height: Pixels,
1436 cx: &mut ViewContext<Editor>,
1437 ) -> (ContextMenuOrigin, AnyElement) {
1438 let actions = self.actions.clone();
1439 let selected_item = self.selected_item;
1440 let element = uniform_list(
1441 cx.view().clone(),
1442 "code_actions_menu",
1443 self.actions.len(),
1444 move |_this, range, cx| {
1445 actions
1446 .iter()
1447 .skip(range.start)
1448 .take(range.end - range.start)
1449 .enumerate()
1450 .map(|(ix, action)| {
1451 let item_ix = range.start + ix;
1452 let selected = selected_item == item_ix;
1453 let colors = cx.theme().colors();
1454 div()
1455 .px_2()
1456 .text_color(colors.text)
1457 .when(selected, |style| {
1458 style
1459 .bg(colors.element_active)
1460 .text_color(colors.text_accent)
1461 })
1462 .hover(|style| {
1463 style
1464 .bg(colors.element_hover)
1465 .text_color(colors.text_accent)
1466 })
1467 .whitespace_nowrap()
1468 .when_some(action.as_code_action(), |this, action| {
1469 this.on_mouse_down(
1470 MouseButton::Left,
1471 cx.listener(move |editor, _, cx| {
1472 cx.stop_propagation();
1473 if let Some(task) = editor.confirm_code_action(
1474 &ConfirmCodeAction {
1475 item_ix: Some(item_ix),
1476 },
1477 cx,
1478 ) {
1479 task.detach_and_log_err(cx)
1480 }
1481 }),
1482 )
1483 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1484 .child(SharedString::from(action.lsp_action.title.clone()))
1485 })
1486 .when_some(action.as_task(), |this, task| {
1487 this.on_mouse_down(
1488 MouseButton::Left,
1489 cx.listener(move |editor, _, cx| {
1490 cx.stop_propagation();
1491 if let Some(task) = editor.confirm_code_action(
1492 &ConfirmCodeAction {
1493 item_ix: Some(item_ix),
1494 },
1495 cx,
1496 ) {
1497 task.detach_and_log_err(cx)
1498 }
1499 }),
1500 )
1501 .child(SharedString::from(task.resolved_label.clone()))
1502 })
1503 })
1504 .collect()
1505 },
1506 )
1507 .elevation_1(cx)
1508 .px_2()
1509 .py_1()
1510 .max_h(max_height)
1511 .occlude()
1512 .track_scroll(self.scroll_handle.clone())
1513 .with_width_from_item(
1514 self.actions
1515 .iter()
1516 .enumerate()
1517 .max_by_key(|(_, action)| match action {
1518 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1519 CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
1520 })
1521 .map(|(ix, _)| ix),
1522 )
1523 .with_sizing_behavior(ListSizingBehavior::Infer)
1524 .into_any_element();
1525
1526 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1527 ContextMenuOrigin::GutterIndicator(row)
1528 } else {
1529 ContextMenuOrigin::EditorPoint(cursor_position)
1530 };
1531
1532 (cursor_position, element)
1533 }
1534}
1535
1536#[derive(Debug)]
1537struct ActiveDiagnosticGroup {
1538 primary_range: Range<Anchor>,
1539 primary_message: String,
1540 group_id: usize,
1541 blocks: HashMap<CustomBlockId, Diagnostic>,
1542 is_valid: bool,
1543}
1544
1545#[derive(Serialize, Deserialize, Clone, Debug)]
1546pub struct ClipboardSelection {
1547 pub len: usize,
1548 pub is_entire_line: bool,
1549 pub first_line_indent: u32,
1550}
1551
1552#[derive(Debug)]
1553pub(crate) struct NavigationData {
1554 cursor_anchor: Anchor,
1555 cursor_position: Point,
1556 scroll_anchor: ScrollAnchor,
1557 scroll_top_row: u32,
1558}
1559
1560enum GotoDefinitionKind {
1561 Symbol,
1562 Type,
1563 Implementation,
1564}
1565
1566#[derive(Debug, Clone)]
1567enum InlayHintRefreshReason {
1568 Toggle(bool),
1569 SettingsChange(InlayHintSettings),
1570 NewLinesShown,
1571 BufferEdited(HashSet<Arc<Language>>),
1572 RefreshRequested,
1573 ExcerptsRemoved(Vec<ExcerptId>),
1574}
1575
1576impl InlayHintRefreshReason {
1577 fn description(&self) -> &'static str {
1578 match self {
1579 Self::Toggle(_) => "toggle",
1580 Self::SettingsChange(_) => "settings change",
1581 Self::NewLinesShown => "new lines shown",
1582 Self::BufferEdited(_) => "buffer edited",
1583 Self::RefreshRequested => "refresh requested",
1584 Self::ExcerptsRemoved(_) => "excerpts removed",
1585 }
1586 }
1587}
1588
1589pub(crate) struct FocusedBlock {
1590 id: BlockId,
1591 focus_handle: WeakFocusHandle,
1592}
1593
1594impl Editor {
1595 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1596 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1597 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1598 Self::new(
1599 EditorMode::SingleLine { auto_width: false },
1600 buffer,
1601 None,
1602 false,
1603 cx,
1604 )
1605 }
1606
1607 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1608 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1609 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1610 Self::new(EditorMode::Full, buffer, None, false, cx)
1611 }
1612
1613 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1614 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1615 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1616 Self::new(
1617 EditorMode::SingleLine { auto_width: true },
1618 buffer,
1619 None,
1620 false,
1621 cx,
1622 )
1623 }
1624
1625 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1626 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1627 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1628 Self::new(
1629 EditorMode::AutoHeight { max_lines },
1630 buffer,
1631 None,
1632 false,
1633 cx,
1634 )
1635 }
1636
1637 pub fn for_buffer(
1638 buffer: Model<Buffer>,
1639 project: Option<Model<Project>>,
1640 cx: &mut ViewContext<Self>,
1641 ) -> Self {
1642 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1643 Self::new(EditorMode::Full, buffer, project, false, cx)
1644 }
1645
1646 pub fn for_multibuffer(
1647 buffer: Model<MultiBuffer>,
1648 project: Option<Model<Project>>,
1649 show_excerpt_controls: bool,
1650 cx: &mut ViewContext<Self>,
1651 ) -> Self {
1652 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1653 }
1654
1655 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1656 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1657 let mut clone = Self::new(
1658 self.mode,
1659 self.buffer.clone(),
1660 self.project.clone(),
1661 show_excerpt_controls,
1662 cx,
1663 );
1664 self.display_map.update(cx, |display_map, cx| {
1665 let snapshot = display_map.snapshot(cx);
1666 clone.display_map.update(cx, |display_map, cx| {
1667 display_map.set_state(&snapshot, cx);
1668 });
1669 });
1670 clone.selections.clone_state(&self.selections);
1671 clone.scroll_manager.clone_state(&self.scroll_manager);
1672 clone.searchable = self.searchable;
1673 clone
1674 }
1675
1676 pub fn new(
1677 mode: EditorMode,
1678 buffer: Model<MultiBuffer>,
1679 project: Option<Model<Project>>,
1680 show_excerpt_controls: bool,
1681 cx: &mut ViewContext<Self>,
1682 ) -> Self {
1683 let style = cx.text_style();
1684 let font_size = style.font_size.to_pixels(cx.rem_size());
1685 let editor = cx.view().downgrade();
1686 let fold_placeholder = FoldPlaceholder {
1687 constrain_width: true,
1688 render: Arc::new(move |fold_id, fold_range, cx| {
1689 let editor = editor.clone();
1690 div()
1691 .id(fold_id)
1692 .bg(cx.theme().colors().ghost_element_background)
1693 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1694 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1695 .rounded_sm()
1696 .size_full()
1697 .cursor_pointer()
1698 .child("⋯")
1699 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1700 .on_click(move |_, cx| {
1701 editor
1702 .update(cx, |editor, cx| {
1703 editor.unfold_ranges(
1704 [fold_range.start..fold_range.end],
1705 true,
1706 false,
1707 cx,
1708 );
1709 cx.stop_propagation();
1710 })
1711 .ok();
1712 })
1713 .into_any()
1714 }),
1715 merge_adjacent: true,
1716 };
1717 let file_header_size = if show_excerpt_controls { 3 } else { 2 };
1718 let display_map = cx.new_model(|cx| {
1719 DisplayMap::new(
1720 buffer.clone(),
1721 style.font(),
1722 font_size,
1723 None,
1724 show_excerpt_controls,
1725 file_header_size,
1726 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1727 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1728 fold_placeholder,
1729 cx,
1730 )
1731 });
1732
1733 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1734
1735 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1736
1737 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1738 .then(|| language_settings::SoftWrap::PreferLine);
1739
1740 let mut project_subscriptions = Vec::new();
1741 if mode == EditorMode::Full {
1742 if let Some(project) = project.as_ref() {
1743 if buffer.read(cx).is_singleton() {
1744 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1745 cx.emit(EditorEvent::TitleChanged);
1746 }));
1747 }
1748 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1749 if let project::Event::RefreshInlayHints = event {
1750 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1751 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1752 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1753 let focus_handle = editor.focus_handle(cx);
1754 if focus_handle.is_focused(cx) {
1755 let snapshot = buffer.read(cx).snapshot();
1756 for (range, snippet) in snippet_edits {
1757 let editor_range =
1758 language::range_from_lsp(*range).to_offset(&snapshot);
1759 editor
1760 .insert_snippet(&[editor_range], snippet.clone(), cx)
1761 .ok();
1762 }
1763 }
1764 }
1765 }
1766 }));
1767 let task_inventory = project.read(cx).task_inventory().clone();
1768 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1769 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1770 }));
1771 }
1772 }
1773
1774 let inlay_hint_settings = inlay_hint_settings(
1775 selections.newest_anchor().head(),
1776 &buffer.read(cx).snapshot(cx),
1777 cx,
1778 );
1779 let focus_handle = cx.focus_handle();
1780 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1781 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1782 .detach();
1783 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1784 .detach();
1785 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1786
1787 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1788 Some(false)
1789 } else {
1790 None
1791 };
1792
1793 let mut this = Self {
1794 focus_handle,
1795 show_cursor_when_unfocused: false,
1796 last_focused_descendant: None,
1797 buffer: buffer.clone(),
1798 display_map: display_map.clone(),
1799 selections,
1800 scroll_manager: ScrollManager::new(cx),
1801 columnar_selection_tail: None,
1802 add_selections_state: None,
1803 select_next_state: None,
1804 select_prev_state: None,
1805 selection_history: Default::default(),
1806 autoclose_regions: Default::default(),
1807 snippet_stack: Default::default(),
1808 select_larger_syntax_node_stack: Vec::new(),
1809 ime_transaction: Default::default(),
1810 active_diagnostics: None,
1811 soft_wrap_mode_override,
1812 completion_provider: project.clone().map(|project| Box::new(project) as _),
1813 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1814 project,
1815 blink_manager: blink_manager.clone(),
1816 show_local_selections: true,
1817 mode,
1818 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1819 show_gutter: mode == EditorMode::Full,
1820 show_line_numbers: None,
1821 show_git_diff_gutter: None,
1822 show_code_actions: None,
1823 show_runnables: None,
1824 show_wrap_guides: None,
1825 show_indent_guides,
1826 placeholder_text: None,
1827 highlight_order: 0,
1828 highlighted_rows: HashMap::default(),
1829 background_highlights: Default::default(),
1830 gutter_highlights: TreeMap::default(),
1831 scrollbar_marker_state: ScrollbarMarkerState::default(),
1832 active_indent_guides_state: ActiveIndentGuidesState::default(),
1833 nav_history: None,
1834 context_menu: RwLock::new(None),
1835 mouse_context_menu: None,
1836 completion_tasks: Default::default(),
1837 signature_help_state: SignatureHelpState::default(),
1838 auto_signature_help: None,
1839 find_all_references_task_sources: Vec::new(),
1840 next_completion_id: 0,
1841 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1842 next_inlay_id: 0,
1843 available_code_actions: Default::default(),
1844 code_actions_task: Default::default(),
1845 document_highlights_task: Default::default(),
1846 linked_editing_range_task: Default::default(),
1847 pending_rename: Default::default(),
1848 searchable: true,
1849 cursor_shape: Default::default(),
1850 current_line_highlight: None,
1851 autoindent_mode: Some(AutoindentMode::EachLine),
1852 collapse_matches: false,
1853 workspace: None,
1854 keymap_context_layers: Default::default(),
1855 input_enabled: true,
1856 use_modal_editing: mode == EditorMode::Full,
1857 read_only: false,
1858 use_autoclose: true,
1859 use_auto_surround: true,
1860 auto_replace_emoji_shortcode: false,
1861 leader_peer_id: None,
1862 remote_id: None,
1863 hover_state: Default::default(),
1864 hovered_link_state: Default::default(),
1865 inline_completion_provider: None,
1866 active_inline_completion: None,
1867 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1868 expanded_hunks: ExpandedHunks::default(),
1869 gutter_hovered: false,
1870 pixel_position_of_newest_cursor: None,
1871 last_bounds: None,
1872 expect_bounds_change: None,
1873 gutter_dimensions: GutterDimensions::default(),
1874 style: None,
1875 show_cursor_names: false,
1876 hovered_cursors: Default::default(),
1877 next_editor_action_id: EditorActionId::default(),
1878 editor_actions: Rc::default(),
1879 vim_replace_map: Default::default(),
1880 show_inline_completions: mode == EditorMode::Full,
1881 custom_context_menu: None,
1882 show_git_blame_gutter: false,
1883 show_git_blame_inline: false,
1884 show_selection_menu: None,
1885 show_git_blame_inline_delay_task: None,
1886 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1887 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1888 .session
1889 .restore_unsaved_buffers,
1890 blame: None,
1891 blame_subscription: None,
1892 file_header_size,
1893 tasks: Default::default(),
1894 _subscriptions: vec![
1895 cx.observe(&buffer, Self::on_buffer_changed),
1896 cx.subscribe(&buffer, Self::on_buffer_event),
1897 cx.observe(&display_map, Self::on_display_map_changed),
1898 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1899 cx.observe_global::<SettingsStore>(Self::settings_changed),
1900 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1901 cx.observe_window_activation(|editor, cx| {
1902 let active = cx.is_window_active();
1903 editor.blink_manager.update(cx, |blink_manager, cx| {
1904 if active {
1905 blink_manager.enable(cx);
1906 } else {
1907 blink_manager.show_cursor(cx);
1908 blink_manager.disable(cx);
1909 }
1910 });
1911 }),
1912 ],
1913 tasks_update_task: None,
1914 linked_edit_ranges: Default::default(),
1915 previous_search_ranges: None,
1916 breadcrumb_header: None,
1917 focused_block: None,
1918 };
1919 this.tasks_update_task = Some(this.refresh_runnables(cx));
1920 this._subscriptions.extend(project_subscriptions);
1921
1922 this.end_selection(cx);
1923 this.scroll_manager.show_scrollbar(cx);
1924
1925 if mode == EditorMode::Full {
1926 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1927 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1928
1929 if this.git_blame_inline_enabled {
1930 this.git_blame_inline_enabled = true;
1931 this.start_git_blame_inline(false, cx);
1932 }
1933 }
1934
1935 this.report_editor_event("open", None, cx);
1936 this
1937 }
1938
1939 pub fn mouse_menu_is_focused(&self, cx: &mut WindowContext) -> bool {
1940 self.mouse_context_menu
1941 .as_ref()
1942 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1943 }
1944
1945 fn key_context(&self, cx: &AppContext) -> KeyContext {
1946 let mut key_context = KeyContext::new_with_defaults();
1947 key_context.add("Editor");
1948 let mode = match self.mode {
1949 EditorMode::SingleLine { .. } => "single_line",
1950 EditorMode::AutoHeight { .. } => "auto_height",
1951 EditorMode::Full => "full",
1952 };
1953
1954 if EditorSettings::get_global(cx).jupyter.enabled {
1955 key_context.add("jupyter");
1956 }
1957
1958 key_context.set("mode", mode);
1959 if self.pending_rename.is_some() {
1960 key_context.add("renaming");
1961 }
1962 if self.context_menu_visible() {
1963 match self.context_menu.read().as_ref() {
1964 Some(ContextMenu::Completions(_)) => {
1965 key_context.add("menu");
1966 key_context.add("showing_completions")
1967 }
1968 Some(ContextMenu::CodeActions(_)) => {
1969 key_context.add("menu");
1970 key_context.add("showing_code_actions")
1971 }
1972 None => {}
1973 }
1974 }
1975
1976 for layer in self.keymap_context_layers.values() {
1977 key_context.extend(layer);
1978 }
1979
1980 if let Some(extension) = self
1981 .buffer
1982 .read(cx)
1983 .as_singleton()
1984 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1985 {
1986 key_context.set("extension", extension.to_string());
1987 }
1988
1989 if self.has_active_inline_completion(cx) {
1990 key_context.add("copilot_suggestion");
1991 key_context.add("inline_completion");
1992 }
1993
1994 key_context
1995 }
1996
1997 pub fn new_file(
1998 workspace: &mut Workspace,
1999 _: &workspace::NewFile,
2000 cx: &mut ViewContext<Workspace>,
2001 ) {
2002 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2003 "Failed to create buffer",
2004 cx,
2005 |e, _| match e.error_code() {
2006 ErrorCode::RemoteUpgradeRequired => Some(format!(
2007 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2008 e.error_tag("required").unwrap_or("the latest version")
2009 )),
2010 _ => None,
2011 },
2012 );
2013 }
2014
2015 pub fn new_in_workspace(
2016 workspace: &mut Workspace,
2017 cx: &mut ViewContext<Workspace>,
2018 ) -> Task<Result<View<Editor>>> {
2019 let project = workspace.project().clone();
2020 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2021
2022 cx.spawn(|workspace, mut cx| async move {
2023 let buffer = create.await?;
2024 workspace.update(&mut cx, |workspace, cx| {
2025 let editor =
2026 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2027 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2028 editor
2029 })
2030 })
2031 }
2032
2033 pub fn new_file_in_direction(
2034 workspace: &mut Workspace,
2035 action: &workspace::NewFileInDirection,
2036 cx: &mut ViewContext<Workspace>,
2037 ) {
2038 let project = workspace.project().clone();
2039 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2040 let direction = action.0;
2041
2042 cx.spawn(|workspace, mut cx| async move {
2043 let buffer = create.await?;
2044 workspace.update(&mut cx, move |workspace, cx| {
2045 workspace.split_item(
2046 direction,
2047 Box::new(
2048 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2049 ),
2050 cx,
2051 )
2052 })?;
2053 anyhow::Ok(())
2054 })
2055 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2056 ErrorCode::RemoteUpgradeRequired => Some(format!(
2057 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2058 e.error_tag("required").unwrap_or("the latest version")
2059 )),
2060 _ => None,
2061 });
2062 }
2063
2064 pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
2065 self.buffer.read(cx).replica_id()
2066 }
2067
2068 pub fn leader_peer_id(&self) -> Option<PeerId> {
2069 self.leader_peer_id
2070 }
2071
2072 pub fn buffer(&self) -> &Model<MultiBuffer> {
2073 &self.buffer
2074 }
2075
2076 pub fn workspace(&self) -> Option<View<Workspace>> {
2077 self.workspace.as_ref()?.0.upgrade()
2078 }
2079
2080 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2081 self.buffer().read(cx).title(cx)
2082 }
2083
2084 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2085 EditorSnapshot {
2086 mode: self.mode,
2087 show_gutter: self.show_gutter,
2088 show_line_numbers: self.show_line_numbers,
2089 show_git_diff_gutter: self.show_git_diff_gutter,
2090 show_code_actions: self.show_code_actions,
2091 show_runnables: self.show_runnables,
2092 render_git_blame_gutter: self.render_git_blame_gutter(cx),
2093 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2094 scroll_anchor: self.scroll_manager.anchor(),
2095 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2096 placeholder_text: self.placeholder_text.clone(),
2097 is_focused: self.focus_handle.is_focused(cx),
2098 current_line_highlight: self
2099 .current_line_highlight
2100 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2101 gutter_hovered: self.gutter_hovered,
2102 }
2103 }
2104
2105 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2106 self.buffer.read(cx).language_at(point, cx)
2107 }
2108
2109 pub fn file_at<T: ToOffset>(
2110 &self,
2111 point: T,
2112 cx: &AppContext,
2113 ) -> Option<Arc<dyn language::File>> {
2114 self.buffer.read(cx).read(cx).file_at(point).cloned()
2115 }
2116
2117 pub fn active_excerpt(
2118 &self,
2119 cx: &AppContext,
2120 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2121 self.buffer
2122 .read(cx)
2123 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2124 }
2125
2126 pub fn mode(&self) -> EditorMode {
2127 self.mode
2128 }
2129
2130 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2131 self.collaboration_hub.as_deref()
2132 }
2133
2134 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2135 self.collaboration_hub = Some(hub);
2136 }
2137
2138 pub fn set_custom_context_menu(
2139 &mut self,
2140 f: impl 'static
2141 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2142 ) {
2143 self.custom_context_menu = Some(Box::new(f))
2144 }
2145
2146 pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
2147 self.completion_provider = Some(provider);
2148 }
2149
2150 pub fn set_inline_completion_provider<T>(
2151 &mut self,
2152 provider: Option<Model<T>>,
2153 cx: &mut ViewContext<Self>,
2154 ) where
2155 T: InlineCompletionProvider,
2156 {
2157 self.inline_completion_provider =
2158 provider.map(|provider| RegisteredInlineCompletionProvider {
2159 _subscription: cx.observe(&provider, |this, _, cx| {
2160 if this.focus_handle.is_focused(cx) {
2161 this.update_visible_inline_completion(cx);
2162 }
2163 }),
2164 provider: Arc::new(provider),
2165 });
2166 self.refresh_inline_completion(false, cx);
2167 }
2168
2169 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2170 self.placeholder_text.as_deref()
2171 }
2172
2173 pub fn set_placeholder_text(
2174 &mut self,
2175 placeholder_text: impl Into<Arc<str>>,
2176 cx: &mut ViewContext<Self>,
2177 ) {
2178 let placeholder_text = Some(placeholder_text.into());
2179 if self.placeholder_text != placeholder_text {
2180 self.placeholder_text = placeholder_text;
2181 cx.notify();
2182 }
2183 }
2184
2185 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2186 self.cursor_shape = cursor_shape;
2187
2188 // Disrupt blink for immediate user feedback that the cursor shape has changed
2189 self.blink_manager.update(cx, BlinkManager::show_cursor);
2190
2191 cx.notify();
2192 }
2193
2194 pub fn set_current_line_highlight(
2195 &mut self,
2196 current_line_highlight: Option<CurrentLineHighlight>,
2197 ) {
2198 self.current_line_highlight = current_line_highlight;
2199 }
2200
2201 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2202 self.collapse_matches = collapse_matches;
2203 }
2204
2205 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2206 if self.collapse_matches {
2207 return range.start..range.start;
2208 }
2209 range.clone()
2210 }
2211
2212 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2213 if self.display_map.read(cx).clip_at_line_ends != clip {
2214 self.display_map
2215 .update(cx, |map, _| map.clip_at_line_ends = clip);
2216 }
2217 }
2218
2219 pub fn set_keymap_context_layer<Tag: 'static>(
2220 &mut self,
2221 context: KeyContext,
2222 cx: &mut ViewContext<Self>,
2223 ) {
2224 self.keymap_context_layers
2225 .insert(TypeId::of::<Tag>(), context);
2226 cx.notify();
2227 }
2228
2229 pub fn remove_keymap_context_layer<Tag: 'static>(&mut self, cx: &mut ViewContext<Self>) {
2230 self.keymap_context_layers.remove(&TypeId::of::<Tag>());
2231 cx.notify();
2232 }
2233
2234 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2235 self.input_enabled = input_enabled;
2236 }
2237
2238 pub fn set_autoindent(&mut self, autoindent: bool) {
2239 if autoindent {
2240 self.autoindent_mode = Some(AutoindentMode::EachLine);
2241 } else {
2242 self.autoindent_mode = None;
2243 }
2244 }
2245
2246 pub fn read_only(&self, cx: &AppContext) -> bool {
2247 self.read_only || self.buffer.read(cx).read_only()
2248 }
2249
2250 pub fn set_read_only(&mut self, read_only: bool) {
2251 self.read_only = read_only;
2252 }
2253
2254 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2255 self.use_autoclose = autoclose;
2256 }
2257
2258 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2259 self.use_auto_surround = auto_surround;
2260 }
2261
2262 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2263 self.auto_replace_emoji_shortcode = auto_replace;
2264 }
2265
2266 pub fn set_show_inline_completions(&mut self, show_inline_completions: bool) {
2267 self.show_inline_completions = show_inline_completions;
2268 }
2269
2270 pub fn set_use_modal_editing(&mut self, to: bool) {
2271 self.use_modal_editing = to;
2272 }
2273
2274 pub fn use_modal_editing(&self) -> bool {
2275 self.use_modal_editing
2276 }
2277
2278 fn selections_did_change(
2279 &mut self,
2280 local: bool,
2281 old_cursor_position: &Anchor,
2282 show_completions: bool,
2283 cx: &mut ViewContext<Self>,
2284 ) {
2285 // Copy selections to primary selection buffer
2286 #[cfg(target_os = "linux")]
2287 if local {
2288 let selections = self.selections.all::<usize>(cx);
2289 let buffer_handle = self.buffer.read(cx).read(cx);
2290
2291 let mut text = String::new();
2292 for (index, selection) in selections.iter().enumerate() {
2293 let text_for_selection = buffer_handle
2294 .text_for_range(selection.start..selection.end)
2295 .collect::<String>();
2296
2297 text.push_str(&text_for_selection);
2298 if index != selections.len() - 1 {
2299 text.push('\n');
2300 }
2301 }
2302
2303 if !text.is_empty() {
2304 cx.write_to_primary(ClipboardItem::new(text));
2305 }
2306 }
2307
2308 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2309 self.buffer.update(cx, |buffer, cx| {
2310 buffer.set_active_selections(
2311 &self.selections.disjoint_anchors(),
2312 self.selections.line_mode,
2313 self.cursor_shape,
2314 cx,
2315 )
2316 });
2317 }
2318 let display_map = self
2319 .display_map
2320 .update(cx, |display_map, cx| display_map.snapshot(cx));
2321 let buffer = &display_map.buffer_snapshot;
2322 self.add_selections_state = None;
2323 self.select_next_state = None;
2324 self.select_prev_state = None;
2325 self.select_larger_syntax_node_stack.clear();
2326 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2327 self.snippet_stack
2328 .invalidate(&self.selections.disjoint_anchors(), buffer);
2329 self.take_rename(false, cx);
2330
2331 let new_cursor_position = self.selections.newest_anchor().head();
2332
2333 self.push_to_nav_history(
2334 *old_cursor_position,
2335 Some(new_cursor_position.to_point(buffer)),
2336 cx,
2337 );
2338
2339 if local {
2340 let new_cursor_position = self.selections.newest_anchor().head();
2341 let mut context_menu = self.context_menu.write();
2342 let completion_menu = match context_menu.as_ref() {
2343 Some(ContextMenu::Completions(menu)) => Some(menu),
2344
2345 _ => {
2346 *context_menu = None;
2347 None
2348 }
2349 };
2350
2351 if let Some(completion_menu) = completion_menu {
2352 let cursor_position = new_cursor_position.to_offset(buffer);
2353 let (word_range, kind) = buffer.surrounding_word(completion_menu.initial_position);
2354 if kind == Some(CharKind::Word)
2355 && word_range.to_inclusive().contains(&cursor_position)
2356 {
2357 let mut completion_menu = completion_menu.clone();
2358 drop(context_menu);
2359
2360 let query = Self::completion_query(buffer, cursor_position);
2361 cx.spawn(move |this, mut cx| async move {
2362 completion_menu
2363 .filter(query.as_deref(), cx.background_executor().clone())
2364 .await;
2365
2366 this.update(&mut cx, |this, cx| {
2367 let mut context_menu = this.context_menu.write();
2368 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2369 return;
2370 };
2371
2372 if menu.id > completion_menu.id {
2373 return;
2374 }
2375
2376 *context_menu = Some(ContextMenu::Completions(completion_menu));
2377 drop(context_menu);
2378 cx.notify();
2379 })
2380 })
2381 .detach();
2382
2383 if show_completions {
2384 self.show_completions(&ShowCompletions { trigger: None }, cx);
2385 }
2386 } else {
2387 drop(context_menu);
2388 self.hide_context_menu(cx);
2389 }
2390 } else {
2391 drop(context_menu);
2392 }
2393
2394 hide_hover(self, cx);
2395
2396 if old_cursor_position.to_display_point(&display_map).row()
2397 != new_cursor_position.to_display_point(&display_map).row()
2398 {
2399 self.available_code_actions.take();
2400 }
2401 self.refresh_code_actions(cx);
2402 self.refresh_document_highlights(cx);
2403 refresh_matching_bracket_highlights(self, cx);
2404 self.discard_inline_completion(false, cx);
2405 linked_editing_ranges::refresh_linked_ranges(self, cx);
2406 if self.git_blame_inline_enabled {
2407 self.start_inline_blame_timer(cx);
2408 }
2409 }
2410
2411 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2412 cx.emit(EditorEvent::SelectionsChanged { local });
2413
2414 if self.selections.disjoint_anchors().len() == 1 {
2415 cx.emit(SearchEvent::ActiveMatchChanged)
2416 }
2417 cx.notify();
2418 }
2419
2420 pub fn change_selections<R>(
2421 &mut self,
2422 autoscroll: Option<Autoscroll>,
2423 cx: &mut ViewContext<Self>,
2424 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2425 ) -> R {
2426 self.change_selections_inner(autoscroll, true, cx, change)
2427 }
2428
2429 pub fn change_selections_inner<R>(
2430 &mut self,
2431 autoscroll: Option<Autoscroll>,
2432 request_completions: bool,
2433 cx: &mut ViewContext<Self>,
2434 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2435 ) -> R {
2436 let old_cursor_position = self.selections.newest_anchor().head();
2437 self.push_to_selection_history();
2438
2439 let (changed, result) = self.selections.change_with(cx, change);
2440
2441 if changed {
2442 if let Some(autoscroll) = autoscroll {
2443 self.request_autoscroll(autoscroll, cx);
2444 }
2445 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2446
2447 if self.should_open_signature_help_automatically(
2448 &old_cursor_position,
2449 self.signature_help_state.backspace_pressed(),
2450 cx,
2451 ) {
2452 self.show_signature_help(&ShowSignatureHelp, cx);
2453 }
2454 self.signature_help_state.set_backspace_pressed(false);
2455 }
2456
2457 result
2458 }
2459
2460 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2461 where
2462 I: IntoIterator<Item = (Range<S>, T)>,
2463 S: ToOffset,
2464 T: Into<Arc<str>>,
2465 {
2466 if self.read_only(cx) {
2467 return;
2468 }
2469
2470 self.buffer
2471 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2472 }
2473
2474 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2475 where
2476 I: IntoIterator<Item = (Range<S>, T)>,
2477 S: ToOffset,
2478 T: Into<Arc<str>>,
2479 {
2480 if self.read_only(cx) {
2481 return;
2482 }
2483
2484 self.buffer.update(cx, |buffer, cx| {
2485 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2486 });
2487 }
2488
2489 pub fn edit_with_block_indent<I, S, T>(
2490 &mut self,
2491 edits: I,
2492 original_indent_columns: Vec<u32>,
2493 cx: &mut ViewContext<Self>,
2494 ) where
2495 I: IntoIterator<Item = (Range<S>, T)>,
2496 S: ToOffset,
2497 T: Into<Arc<str>>,
2498 {
2499 if self.read_only(cx) {
2500 return;
2501 }
2502
2503 self.buffer.update(cx, |buffer, cx| {
2504 buffer.edit(
2505 edits,
2506 Some(AutoindentMode::Block {
2507 original_indent_columns,
2508 }),
2509 cx,
2510 )
2511 });
2512 }
2513
2514 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2515 self.hide_context_menu(cx);
2516
2517 match phase {
2518 SelectPhase::Begin {
2519 position,
2520 add,
2521 click_count,
2522 } => self.begin_selection(position, add, click_count, cx),
2523 SelectPhase::BeginColumnar {
2524 position,
2525 goal_column,
2526 reset,
2527 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2528 SelectPhase::Extend {
2529 position,
2530 click_count,
2531 } => self.extend_selection(position, click_count, cx),
2532 SelectPhase::Update {
2533 position,
2534 goal_column,
2535 scroll_delta,
2536 } => self.update_selection(position, goal_column, scroll_delta, cx),
2537 SelectPhase::End => self.end_selection(cx),
2538 }
2539 }
2540
2541 fn extend_selection(
2542 &mut self,
2543 position: DisplayPoint,
2544 click_count: usize,
2545 cx: &mut ViewContext<Self>,
2546 ) {
2547 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2548 let tail = self.selections.newest::<usize>(cx).tail();
2549 self.begin_selection(position, false, click_count, cx);
2550
2551 let position = position.to_offset(&display_map, Bias::Left);
2552 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2553
2554 let mut pending_selection = self
2555 .selections
2556 .pending_anchor()
2557 .expect("extend_selection not called with pending selection");
2558 if position >= tail {
2559 pending_selection.start = tail_anchor;
2560 } else {
2561 pending_selection.end = tail_anchor;
2562 pending_selection.reversed = true;
2563 }
2564
2565 let mut pending_mode = self.selections.pending_mode().unwrap();
2566 match &mut pending_mode {
2567 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2568 _ => {}
2569 }
2570
2571 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2572 s.set_pending(pending_selection, pending_mode)
2573 });
2574 }
2575
2576 fn begin_selection(
2577 &mut self,
2578 position: DisplayPoint,
2579 add: bool,
2580 click_count: usize,
2581 cx: &mut ViewContext<Self>,
2582 ) {
2583 if !self.focus_handle.is_focused(cx) {
2584 self.last_focused_descendant = None;
2585 cx.focus(&self.focus_handle);
2586 }
2587
2588 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2589 let buffer = &display_map.buffer_snapshot;
2590 let newest_selection = self.selections.newest_anchor().clone();
2591 let position = display_map.clip_point(position, Bias::Left);
2592
2593 let start;
2594 let end;
2595 let mode;
2596 let auto_scroll;
2597 match click_count {
2598 1 => {
2599 start = buffer.anchor_before(position.to_point(&display_map));
2600 end = start;
2601 mode = SelectMode::Character;
2602 auto_scroll = true;
2603 }
2604 2 => {
2605 let range = movement::surrounding_word(&display_map, position);
2606 start = buffer.anchor_before(range.start.to_point(&display_map));
2607 end = buffer.anchor_before(range.end.to_point(&display_map));
2608 mode = SelectMode::Word(start..end);
2609 auto_scroll = true;
2610 }
2611 3 => {
2612 let position = display_map
2613 .clip_point(position, Bias::Left)
2614 .to_point(&display_map);
2615 let line_start = display_map.prev_line_boundary(position).0;
2616 let next_line_start = buffer.clip_point(
2617 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2618 Bias::Left,
2619 );
2620 start = buffer.anchor_before(line_start);
2621 end = buffer.anchor_before(next_line_start);
2622 mode = SelectMode::Line(start..end);
2623 auto_scroll = true;
2624 }
2625 _ => {
2626 start = buffer.anchor_before(0);
2627 end = buffer.anchor_before(buffer.len());
2628 mode = SelectMode::All;
2629 auto_scroll = false;
2630 }
2631 }
2632
2633 let point_to_delete: Option<usize> = {
2634 let selected_points: Vec<Selection<Point>> =
2635 self.selections.disjoint_in_range(start..end, cx);
2636
2637 if !add || click_count > 1 {
2638 None
2639 } else if selected_points.len() > 0 {
2640 Some(selected_points[0].id)
2641 } else {
2642 let clicked_point_already_selected =
2643 self.selections.disjoint.iter().find(|selection| {
2644 selection.start.to_point(buffer) == start.to_point(buffer)
2645 || selection.end.to_point(buffer) == end.to_point(buffer)
2646 });
2647
2648 if let Some(selection) = clicked_point_already_selected {
2649 Some(selection.id)
2650 } else {
2651 None
2652 }
2653 }
2654 };
2655
2656 let selections_count = self.selections.count();
2657
2658 self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
2659 if let Some(point_to_delete) = point_to_delete {
2660 s.delete(point_to_delete);
2661
2662 if selections_count == 1 {
2663 s.set_pending_anchor_range(start..end, mode);
2664 }
2665 } else {
2666 if !add {
2667 s.clear_disjoint();
2668 } else if click_count > 1 {
2669 s.delete(newest_selection.id)
2670 }
2671
2672 s.set_pending_anchor_range(start..end, mode);
2673 }
2674 });
2675 }
2676
2677 fn begin_columnar_selection(
2678 &mut self,
2679 position: DisplayPoint,
2680 goal_column: u32,
2681 reset: bool,
2682 cx: &mut ViewContext<Self>,
2683 ) {
2684 if !self.focus_handle.is_focused(cx) {
2685 self.last_focused_descendant = None;
2686 cx.focus(&self.focus_handle);
2687 }
2688
2689 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2690
2691 if reset {
2692 let pointer_position = display_map
2693 .buffer_snapshot
2694 .anchor_before(position.to_point(&display_map));
2695
2696 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2697 s.clear_disjoint();
2698 s.set_pending_anchor_range(
2699 pointer_position..pointer_position,
2700 SelectMode::Character,
2701 );
2702 });
2703 }
2704
2705 let tail = self.selections.newest::<Point>(cx).tail();
2706 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2707
2708 if !reset {
2709 self.select_columns(
2710 tail.to_display_point(&display_map),
2711 position,
2712 goal_column,
2713 &display_map,
2714 cx,
2715 );
2716 }
2717 }
2718
2719 fn update_selection(
2720 &mut self,
2721 position: DisplayPoint,
2722 goal_column: u32,
2723 scroll_delta: gpui::Point<f32>,
2724 cx: &mut ViewContext<Self>,
2725 ) {
2726 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2727
2728 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2729 let tail = tail.to_display_point(&display_map);
2730 self.select_columns(tail, position, goal_column, &display_map, cx);
2731 } else if let Some(mut pending) = self.selections.pending_anchor() {
2732 let buffer = self.buffer.read(cx).snapshot(cx);
2733 let head;
2734 let tail;
2735 let mode = self.selections.pending_mode().unwrap();
2736 match &mode {
2737 SelectMode::Character => {
2738 head = position.to_point(&display_map);
2739 tail = pending.tail().to_point(&buffer);
2740 }
2741 SelectMode::Word(original_range) => {
2742 let original_display_range = original_range.start.to_display_point(&display_map)
2743 ..original_range.end.to_display_point(&display_map);
2744 let original_buffer_range = original_display_range.start.to_point(&display_map)
2745 ..original_display_range.end.to_point(&display_map);
2746 if movement::is_inside_word(&display_map, position)
2747 || original_display_range.contains(&position)
2748 {
2749 let word_range = movement::surrounding_word(&display_map, position);
2750 if word_range.start < original_display_range.start {
2751 head = word_range.start.to_point(&display_map);
2752 } else {
2753 head = word_range.end.to_point(&display_map);
2754 }
2755 } else {
2756 head = position.to_point(&display_map);
2757 }
2758
2759 if head <= original_buffer_range.start {
2760 tail = original_buffer_range.end;
2761 } else {
2762 tail = original_buffer_range.start;
2763 }
2764 }
2765 SelectMode::Line(original_range) => {
2766 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2767
2768 let position = display_map
2769 .clip_point(position, Bias::Left)
2770 .to_point(&display_map);
2771 let line_start = display_map.prev_line_boundary(position).0;
2772 let next_line_start = buffer.clip_point(
2773 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2774 Bias::Left,
2775 );
2776
2777 if line_start < original_range.start {
2778 head = line_start
2779 } else {
2780 head = next_line_start
2781 }
2782
2783 if head <= original_range.start {
2784 tail = original_range.end;
2785 } else {
2786 tail = original_range.start;
2787 }
2788 }
2789 SelectMode::All => {
2790 return;
2791 }
2792 };
2793
2794 if head < tail {
2795 pending.start = buffer.anchor_before(head);
2796 pending.end = buffer.anchor_before(tail);
2797 pending.reversed = true;
2798 } else {
2799 pending.start = buffer.anchor_before(tail);
2800 pending.end = buffer.anchor_before(head);
2801 pending.reversed = false;
2802 }
2803
2804 self.change_selections(None, cx, |s| {
2805 s.set_pending(pending, mode);
2806 });
2807 } else {
2808 log::error!("update_selection dispatched with no pending selection");
2809 return;
2810 }
2811
2812 self.apply_scroll_delta(scroll_delta, cx);
2813 cx.notify();
2814 }
2815
2816 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2817 self.columnar_selection_tail.take();
2818 if self.selections.pending_anchor().is_some() {
2819 let selections = self.selections.all::<usize>(cx);
2820 self.change_selections(None, cx, |s| {
2821 s.select(selections);
2822 s.clear_pending();
2823 });
2824 }
2825 }
2826
2827 fn select_columns(
2828 &mut self,
2829 tail: DisplayPoint,
2830 head: DisplayPoint,
2831 goal_column: u32,
2832 display_map: &DisplaySnapshot,
2833 cx: &mut ViewContext<Self>,
2834 ) {
2835 let start_row = cmp::min(tail.row(), head.row());
2836 let end_row = cmp::max(tail.row(), head.row());
2837 let start_column = cmp::min(tail.column(), goal_column);
2838 let end_column = cmp::max(tail.column(), goal_column);
2839 let reversed = start_column < tail.column();
2840
2841 let selection_ranges = (start_row.0..=end_row.0)
2842 .map(DisplayRow)
2843 .filter_map(|row| {
2844 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2845 let start = display_map
2846 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2847 .to_point(display_map);
2848 let end = display_map
2849 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2850 .to_point(display_map);
2851 if reversed {
2852 Some(end..start)
2853 } else {
2854 Some(start..end)
2855 }
2856 } else {
2857 None
2858 }
2859 })
2860 .collect::<Vec<_>>();
2861
2862 self.change_selections(None, cx, |s| {
2863 s.select_ranges(selection_ranges);
2864 });
2865 cx.notify();
2866 }
2867
2868 pub fn has_pending_nonempty_selection(&self) -> bool {
2869 let pending_nonempty_selection = match self.selections.pending_anchor() {
2870 Some(Selection { start, end, .. }) => start != end,
2871 None => false,
2872 };
2873
2874 pending_nonempty_selection
2875 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2876 }
2877
2878 pub fn has_pending_selection(&self) -> bool {
2879 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2880 }
2881
2882 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2883 if self.clear_clicked_diff_hunks(cx) {
2884 cx.notify();
2885 return;
2886 }
2887 if self.dismiss_menus_and_popups(true, cx) {
2888 return;
2889 }
2890
2891 if self.mode == EditorMode::Full {
2892 if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
2893 return;
2894 }
2895 }
2896
2897 cx.propagate();
2898 }
2899
2900 pub fn dismiss_menus_and_popups(
2901 &mut self,
2902 should_report_inline_completion_event: bool,
2903 cx: &mut ViewContext<Self>,
2904 ) -> bool {
2905 if self.take_rename(false, cx).is_some() {
2906 return true;
2907 }
2908
2909 if hide_hover(self, cx) {
2910 return true;
2911 }
2912
2913 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2914 return true;
2915 }
2916
2917 if self.hide_context_menu(cx).is_some() {
2918 return true;
2919 }
2920
2921 if self.mouse_context_menu.take().is_some() {
2922 return true;
2923 }
2924
2925 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2926 return true;
2927 }
2928
2929 if self.snippet_stack.pop().is_some() {
2930 return true;
2931 }
2932
2933 if self.mode == EditorMode::Full {
2934 if self.active_diagnostics.is_some() {
2935 self.dismiss_diagnostics(cx);
2936 return true;
2937 }
2938 }
2939
2940 false
2941 }
2942
2943 fn linked_editing_ranges_for(
2944 &self,
2945 selection: Range<text::Anchor>,
2946 cx: &AppContext,
2947 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2948 if self.linked_edit_ranges.is_empty() {
2949 return None;
2950 }
2951 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2952 selection.end.buffer_id.and_then(|end_buffer_id| {
2953 if selection.start.buffer_id != Some(end_buffer_id) {
2954 return None;
2955 }
2956 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2957 let snapshot = buffer.read(cx).snapshot();
2958 self.linked_edit_ranges
2959 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2960 .map(|ranges| (ranges, snapshot, buffer))
2961 })?;
2962 use text::ToOffset as TO;
2963 // find offset from the start of current range to current cursor position
2964 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2965
2966 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2967 let start_difference = start_offset - start_byte_offset;
2968 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2969 let end_difference = end_offset - start_byte_offset;
2970 // Current range has associated linked ranges.
2971 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2972 for range in linked_ranges.iter() {
2973 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2974 let end_offset = start_offset + end_difference;
2975 let start_offset = start_offset + start_difference;
2976 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2977 continue;
2978 }
2979 let start = buffer_snapshot.anchor_after(start_offset);
2980 let end = buffer_snapshot.anchor_after(end_offset);
2981 linked_edits
2982 .entry(buffer.clone())
2983 .or_default()
2984 .push(start..end);
2985 }
2986 Some(linked_edits)
2987 }
2988
2989 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2990 let text: Arc<str> = text.into();
2991
2992 if self.read_only(cx) {
2993 return;
2994 }
2995
2996 let selections = self.selections.all_adjusted(cx);
2997 let mut bracket_inserted = false;
2998 let mut edits = Vec::new();
2999 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3000 let mut new_selections = Vec::with_capacity(selections.len());
3001 let mut new_autoclose_regions = Vec::new();
3002 let snapshot = self.buffer.read(cx).read(cx);
3003
3004 for (selection, autoclose_region) in
3005 self.selections_with_autoclose_regions(selections, &snapshot)
3006 {
3007 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3008 // Determine if the inserted text matches the opening or closing
3009 // bracket of any of this language's bracket pairs.
3010 let mut bracket_pair = None;
3011 let mut is_bracket_pair_start = false;
3012 let mut is_bracket_pair_end = false;
3013 if !text.is_empty() {
3014 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3015 // and they are removing the character that triggered IME popup.
3016 for (pair, enabled) in scope.brackets() {
3017 if !pair.close && !pair.surround {
3018 continue;
3019 }
3020
3021 if enabled && pair.start.ends_with(text.as_ref()) {
3022 bracket_pair = Some(pair.clone());
3023 is_bracket_pair_start = true;
3024 break;
3025 }
3026 if pair.end.as_str() == text.as_ref() {
3027 bracket_pair = Some(pair.clone());
3028 is_bracket_pair_end = true;
3029 break;
3030 }
3031 }
3032 }
3033
3034 if let Some(bracket_pair) = bracket_pair {
3035 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3036 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3037 let auto_surround =
3038 self.use_auto_surround && snapshot_settings.use_auto_surround;
3039 if selection.is_empty() {
3040 if is_bracket_pair_start {
3041 let prefix_len = bracket_pair.start.len() - text.len();
3042
3043 // If the inserted text is a suffix of an opening bracket and the
3044 // selection is preceded by the rest of the opening bracket, then
3045 // insert the closing bracket.
3046 let following_text_allows_autoclose = snapshot
3047 .chars_at(selection.start)
3048 .next()
3049 .map_or(true, |c| scope.should_autoclose_before(c));
3050 let preceding_text_matches_prefix = prefix_len == 0
3051 || (selection.start.column >= (prefix_len as u32)
3052 && snapshot.contains_str_at(
3053 Point::new(
3054 selection.start.row,
3055 selection.start.column - (prefix_len as u32),
3056 ),
3057 &bracket_pair.start[..prefix_len],
3058 ));
3059
3060 if autoclose
3061 && bracket_pair.close
3062 && following_text_allows_autoclose
3063 && preceding_text_matches_prefix
3064 {
3065 let anchor = snapshot.anchor_before(selection.end);
3066 new_selections.push((selection.map(|_| anchor), text.len()));
3067 new_autoclose_regions.push((
3068 anchor,
3069 text.len(),
3070 selection.id,
3071 bracket_pair.clone(),
3072 ));
3073 edits.push((
3074 selection.range(),
3075 format!("{}{}", text, bracket_pair.end).into(),
3076 ));
3077 bracket_inserted = true;
3078 continue;
3079 }
3080 }
3081
3082 if let Some(region) = autoclose_region {
3083 // If the selection is followed by an auto-inserted closing bracket,
3084 // then don't insert that closing bracket again; just move the selection
3085 // past the closing bracket.
3086 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3087 && text.as_ref() == region.pair.end.as_str();
3088 if should_skip {
3089 let anchor = snapshot.anchor_after(selection.end);
3090 new_selections
3091 .push((selection.map(|_| anchor), region.pair.end.len()));
3092 continue;
3093 }
3094 }
3095
3096 let always_treat_brackets_as_autoclosed = snapshot
3097 .settings_at(selection.start, cx)
3098 .always_treat_brackets_as_autoclosed;
3099 if always_treat_brackets_as_autoclosed
3100 && is_bracket_pair_end
3101 && snapshot.contains_str_at(selection.end, text.as_ref())
3102 {
3103 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3104 // and the inserted text is a closing bracket and the selection is followed
3105 // by the closing bracket then move the selection past the closing bracket.
3106 let anchor = snapshot.anchor_after(selection.end);
3107 new_selections.push((selection.map(|_| anchor), text.len()));
3108 continue;
3109 }
3110 }
3111 // If an opening bracket is 1 character long and is typed while
3112 // text is selected, then surround that text with the bracket pair.
3113 else if auto_surround
3114 && bracket_pair.surround
3115 && is_bracket_pair_start
3116 && bracket_pair.start.chars().count() == 1
3117 {
3118 edits.push((selection.start..selection.start, text.clone()));
3119 edits.push((
3120 selection.end..selection.end,
3121 bracket_pair.end.as_str().into(),
3122 ));
3123 bracket_inserted = true;
3124 new_selections.push((
3125 Selection {
3126 id: selection.id,
3127 start: snapshot.anchor_after(selection.start),
3128 end: snapshot.anchor_before(selection.end),
3129 reversed: selection.reversed,
3130 goal: selection.goal,
3131 },
3132 0,
3133 ));
3134 continue;
3135 }
3136 }
3137 }
3138
3139 if self.auto_replace_emoji_shortcode
3140 && selection.is_empty()
3141 && text.as_ref().ends_with(':')
3142 {
3143 if let Some(possible_emoji_short_code) =
3144 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3145 {
3146 if !possible_emoji_short_code.is_empty() {
3147 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3148 let emoji_shortcode_start = Point::new(
3149 selection.start.row,
3150 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3151 );
3152
3153 // Remove shortcode from buffer
3154 edits.push((
3155 emoji_shortcode_start..selection.start,
3156 "".to_string().into(),
3157 ));
3158 new_selections.push((
3159 Selection {
3160 id: selection.id,
3161 start: snapshot.anchor_after(emoji_shortcode_start),
3162 end: snapshot.anchor_before(selection.start),
3163 reversed: selection.reversed,
3164 goal: selection.goal,
3165 },
3166 0,
3167 ));
3168
3169 // Insert emoji
3170 let selection_start_anchor = snapshot.anchor_after(selection.start);
3171 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3172 edits.push((selection.start..selection.end, emoji.to_string().into()));
3173
3174 continue;
3175 }
3176 }
3177 }
3178 }
3179
3180 // If not handling any auto-close operation, then just replace the selected
3181 // text with the given input and move the selection to the end of the
3182 // newly inserted text.
3183 let anchor = snapshot.anchor_after(selection.end);
3184 if !self.linked_edit_ranges.is_empty() {
3185 let start_anchor = snapshot.anchor_before(selection.start);
3186
3187 let is_word_char = text.chars().next().map_or(true, |char| {
3188 let scope = snapshot.language_scope_at(start_anchor.to_offset(&snapshot));
3189 let kind = char_kind(&scope, char);
3190
3191 kind == CharKind::Word
3192 });
3193
3194 if is_word_char {
3195 if let Some(ranges) = self
3196 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3197 {
3198 for (buffer, edits) in ranges {
3199 linked_edits
3200 .entry(buffer.clone())
3201 .or_default()
3202 .extend(edits.into_iter().map(|range| (range, text.clone())));
3203 }
3204 }
3205 }
3206 }
3207
3208 new_selections.push((selection.map(|_| anchor), 0));
3209 edits.push((selection.start..selection.end, text.clone()));
3210 }
3211
3212 drop(snapshot);
3213
3214 self.transact(cx, |this, cx| {
3215 this.buffer.update(cx, |buffer, cx| {
3216 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3217 });
3218 for (buffer, edits) in linked_edits {
3219 buffer.update(cx, |buffer, cx| {
3220 let snapshot = buffer.snapshot();
3221 let edits = edits
3222 .into_iter()
3223 .map(|(range, text)| {
3224 use text::ToPoint as TP;
3225 let end_point = TP::to_point(&range.end, &snapshot);
3226 let start_point = TP::to_point(&range.start, &snapshot);
3227 (start_point..end_point, text)
3228 })
3229 .sorted_by_key(|(range, _)| range.start)
3230 .collect::<Vec<_>>();
3231 buffer.edit(edits, None, cx);
3232 })
3233 }
3234 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3235 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3236 let snapshot = this.buffer.read(cx).read(cx);
3237 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3238 .zip(new_selection_deltas)
3239 .map(|(selection, delta)| Selection {
3240 id: selection.id,
3241 start: selection.start + delta,
3242 end: selection.end + delta,
3243 reversed: selection.reversed,
3244 goal: SelectionGoal::None,
3245 })
3246 .collect::<Vec<_>>();
3247
3248 let mut i = 0;
3249 for (position, delta, selection_id, pair) in new_autoclose_regions {
3250 let position = position.to_offset(&snapshot) + delta;
3251 let start = snapshot.anchor_before(position);
3252 let end = snapshot.anchor_after(position);
3253 while let Some(existing_state) = this.autoclose_regions.get(i) {
3254 match existing_state.range.start.cmp(&start, &snapshot) {
3255 Ordering::Less => i += 1,
3256 Ordering::Greater => break,
3257 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3258 Ordering::Less => i += 1,
3259 Ordering::Equal => break,
3260 Ordering::Greater => break,
3261 },
3262 }
3263 }
3264 this.autoclose_regions.insert(
3265 i,
3266 AutocloseRegion {
3267 selection_id,
3268 range: start..end,
3269 pair,
3270 },
3271 );
3272 }
3273
3274 drop(snapshot);
3275 let had_active_inline_completion = this.has_active_inline_completion(cx);
3276 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3277 s.select(new_selections)
3278 });
3279
3280 if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
3281 if let Some(on_type_format_task) =
3282 this.trigger_on_type_formatting(text.to_string(), cx)
3283 {
3284 on_type_format_task.detach_and_log_err(cx);
3285 }
3286 }
3287
3288 let editor_settings = EditorSettings::get_global(cx);
3289 if bracket_inserted
3290 && (editor_settings.auto_signature_help
3291 || editor_settings.show_signature_help_after_edits)
3292 {
3293 this.show_signature_help(&ShowSignatureHelp, cx);
3294 }
3295
3296 let trigger_in_words = !had_active_inline_completion;
3297 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3298 linked_editing_ranges::refresh_linked_ranges(this, cx);
3299 this.refresh_inline_completion(true, cx);
3300 });
3301 }
3302
3303 fn find_possible_emoji_shortcode_at_position(
3304 snapshot: &MultiBufferSnapshot,
3305 position: Point,
3306 ) -> Option<String> {
3307 let mut chars = Vec::new();
3308 let mut found_colon = false;
3309 for char in snapshot.reversed_chars_at(position).take(100) {
3310 // Found a possible emoji shortcode in the middle of the buffer
3311 if found_colon {
3312 if char.is_whitespace() {
3313 chars.reverse();
3314 return Some(chars.iter().collect());
3315 }
3316 // If the previous character is not a whitespace, we are in the middle of a word
3317 // and we only want to complete the shortcode if the word is made up of other emojis
3318 let mut containing_word = String::new();
3319 for ch in snapshot
3320 .reversed_chars_at(position)
3321 .skip(chars.len() + 1)
3322 .take(100)
3323 {
3324 if ch.is_whitespace() {
3325 break;
3326 }
3327 containing_word.push(ch);
3328 }
3329 let containing_word = containing_word.chars().rev().collect::<String>();
3330 if util::word_consists_of_emojis(containing_word.as_str()) {
3331 chars.reverse();
3332 return Some(chars.iter().collect());
3333 }
3334 }
3335
3336 if char.is_whitespace() || !char.is_ascii() {
3337 return None;
3338 }
3339 if char == ':' {
3340 found_colon = true;
3341 } else {
3342 chars.push(char);
3343 }
3344 }
3345 // Found a possible emoji shortcode at the beginning of the buffer
3346 chars.reverse();
3347 Some(chars.iter().collect())
3348 }
3349
3350 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3351 self.transact(cx, |this, cx| {
3352 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3353 let selections = this.selections.all::<usize>(cx);
3354 let multi_buffer = this.buffer.read(cx);
3355 let buffer = multi_buffer.snapshot(cx);
3356 selections
3357 .iter()
3358 .map(|selection| {
3359 let start_point = selection.start.to_point(&buffer);
3360 let mut indent =
3361 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3362 indent.len = cmp::min(indent.len, start_point.column);
3363 let start = selection.start;
3364 let end = selection.end;
3365 let selection_is_empty = start == end;
3366 let language_scope = buffer.language_scope_at(start);
3367 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3368 &language_scope
3369 {
3370 let leading_whitespace_len = buffer
3371 .reversed_chars_at(start)
3372 .take_while(|c| c.is_whitespace() && *c != '\n')
3373 .map(|c| c.len_utf8())
3374 .sum::<usize>();
3375
3376 let trailing_whitespace_len = buffer
3377 .chars_at(end)
3378 .take_while(|c| c.is_whitespace() && *c != '\n')
3379 .map(|c| c.len_utf8())
3380 .sum::<usize>();
3381
3382 let insert_extra_newline =
3383 language.brackets().any(|(pair, enabled)| {
3384 let pair_start = pair.start.trim_end();
3385 let pair_end = pair.end.trim_start();
3386
3387 enabled
3388 && pair.newline
3389 && buffer.contains_str_at(
3390 end + trailing_whitespace_len,
3391 pair_end,
3392 )
3393 && buffer.contains_str_at(
3394 (start - leading_whitespace_len)
3395 .saturating_sub(pair_start.len()),
3396 pair_start,
3397 )
3398 });
3399
3400 // Comment extension on newline is allowed only for cursor selections
3401 let comment_delimiter = maybe!({
3402 if !selection_is_empty {
3403 return None;
3404 }
3405
3406 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3407 return None;
3408 }
3409
3410 let delimiters = language.line_comment_prefixes();
3411 let max_len_of_delimiter =
3412 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3413 let (snapshot, range) =
3414 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3415
3416 let mut index_of_first_non_whitespace = 0;
3417 let comment_candidate = snapshot
3418 .chars_for_range(range)
3419 .skip_while(|c| {
3420 let should_skip = c.is_whitespace();
3421 if should_skip {
3422 index_of_first_non_whitespace += 1;
3423 }
3424 should_skip
3425 })
3426 .take(max_len_of_delimiter)
3427 .collect::<String>();
3428 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3429 comment_candidate.starts_with(comment_prefix.as_ref())
3430 })?;
3431 let cursor_is_placed_after_comment_marker =
3432 index_of_first_non_whitespace + comment_prefix.len()
3433 <= start_point.column as usize;
3434 if cursor_is_placed_after_comment_marker {
3435 Some(comment_prefix.clone())
3436 } else {
3437 None
3438 }
3439 });
3440 (comment_delimiter, insert_extra_newline)
3441 } else {
3442 (None, false)
3443 };
3444
3445 let capacity_for_delimiter = comment_delimiter
3446 .as_deref()
3447 .map(str::len)
3448 .unwrap_or_default();
3449 let mut new_text =
3450 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3451 new_text.push_str("\n");
3452 new_text.extend(indent.chars());
3453 if let Some(delimiter) = &comment_delimiter {
3454 new_text.push_str(&delimiter);
3455 }
3456 if insert_extra_newline {
3457 new_text = new_text.repeat(2);
3458 }
3459
3460 let anchor = buffer.anchor_after(end);
3461 let new_selection = selection.map(|_| anchor);
3462 (
3463 (start..end, new_text),
3464 (insert_extra_newline, new_selection),
3465 )
3466 })
3467 .unzip()
3468 };
3469
3470 this.edit_with_autoindent(edits, cx);
3471 let buffer = this.buffer.read(cx).snapshot(cx);
3472 let new_selections = selection_fixup_info
3473 .into_iter()
3474 .map(|(extra_newline_inserted, new_selection)| {
3475 let mut cursor = new_selection.end.to_point(&buffer);
3476 if extra_newline_inserted {
3477 cursor.row -= 1;
3478 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3479 }
3480 new_selection.map(|_| cursor)
3481 })
3482 .collect();
3483
3484 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3485 this.refresh_inline_completion(true, cx);
3486 });
3487 }
3488
3489 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3490 let buffer = self.buffer.read(cx);
3491 let snapshot = buffer.snapshot(cx);
3492
3493 let mut edits = Vec::new();
3494 let mut rows = Vec::new();
3495
3496 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3497 let cursor = selection.head();
3498 let row = cursor.row;
3499
3500 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3501
3502 let newline = "\n".to_string();
3503 edits.push((start_of_line..start_of_line, newline));
3504
3505 rows.push(row + rows_inserted as u32);
3506 }
3507
3508 self.transact(cx, |editor, cx| {
3509 editor.edit(edits, cx);
3510
3511 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3512 let mut index = 0;
3513 s.move_cursors_with(|map, _, _| {
3514 let row = rows[index];
3515 index += 1;
3516
3517 let point = Point::new(row, 0);
3518 let boundary = map.next_line_boundary(point).1;
3519 let clipped = map.clip_point(boundary, Bias::Left);
3520
3521 (clipped, SelectionGoal::None)
3522 });
3523 });
3524
3525 let mut indent_edits = Vec::new();
3526 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3527 for row in rows {
3528 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3529 for (row, indent) in indents {
3530 if indent.len == 0 {
3531 continue;
3532 }
3533
3534 let text = match indent.kind {
3535 IndentKind::Space => " ".repeat(indent.len as usize),
3536 IndentKind::Tab => "\t".repeat(indent.len as usize),
3537 };
3538 let point = Point::new(row.0, 0);
3539 indent_edits.push((point..point, text));
3540 }
3541 }
3542 editor.edit(indent_edits, cx);
3543 });
3544 }
3545
3546 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3547 let buffer = self.buffer.read(cx);
3548 let snapshot = buffer.snapshot(cx);
3549
3550 let mut edits = Vec::new();
3551 let mut rows = Vec::new();
3552 let mut rows_inserted = 0;
3553
3554 for selection in self.selections.all_adjusted(cx) {
3555 let cursor = selection.head();
3556 let row = cursor.row;
3557
3558 let point = Point::new(row + 1, 0);
3559 let start_of_line = snapshot.clip_point(point, Bias::Left);
3560
3561 let newline = "\n".to_string();
3562 edits.push((start_of_line..start_of_line, newline));
3563
3564 rows_inserted += 1;
3565 rows.push(row + rows_inserted);
3566 }
3567
3568 self.transact(cx, |editor, cx| {
3569 editor.edit(edits, cx);
3570
3571 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3572 let mut index = 0;
3573 s.move_cursors_with(|map, _, _| {
3574 let row = rows[index];
3575 index += 1;
3576
3577 let point = Point::new(row, 0);
3578 let boundary = map.next_line_boundary(point).1;
3579 let clipped = map.clip_point(boundary, Bias::Left);
3580
3581 (clipped, SelectionGoal::None)
3582 });
3583 });
3584
3585 let mut indent_edits = Vec::new();
3586 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3587 for row in rows {
3588 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3589 for (row, indent) in indents {
3590 if indent.len == 0 {
3591 continue;
3592 }
3593
3594 let text = match indent.kind {
3595 IndentKind::Space => " ".repeat(indent.len as usize),
3596 IndentKind::Tab => "\t".repeat(indent.len as usize),
3597 };
3598 let point = Point::new(row.0, 0);
3599 indent_edits.push((point..point, text));
3600 }
3601 }
3602 editor.edit(indent_edits, cx);
3603 });
3604 }
3605
3606 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3607 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3608 original_indent_columns: Vec::new(),
3609 });
3610 self.insert_with_autoindent_mode(text, autoindent, cx);
3611 }
3612
3613 fn insert_with_autoindent_mode(
3614 &mut self,
3615 text: &str,
3616 autoindent_mode: Option<AutoindentMode>,
3617 cx: &mut ViewContext<Self>,
3618 ) {
3619 if self.read_only(cx) {
3620 return;
3621 }
3622
3623 let text: Arc<str> = text.into();
3624 self.transact(cx, |this, cx| {
3625 let old_selections = this.selections.all_adjusted(cx);
3626 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3627 let anchors = {
3628 let snapshot = buffer.read(cx);
3629 old_selections
3630 .iter()
3631 .map(|s| {
3632 let anchor = snapshot.anchor_after(s.head());
3633 s.map(|_| anchor)
3634 })
3635 .collect::<Vec<_>>()
3636 };
3637 buffer.edit(
3638 old_selections
3639 .iter()
3640 .map(|s| (s.start..s.end, text.clone())),
3641 autoindent_mode,
3642 cx,
3643 );
3644 anchors
3645 });
3646
3647 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3648 s.select_anchors(selection_anchors);
3649 })
3650 });
3651 }
3652
3653 fn trigger_completion_on_input(
3654 &mut self,
3655 text: &str,
3656 trigger_in_words: bool,
3657 cx: &mut ViewContext<Self>,
3658 ) {
3659 if self.is_completion_trigger(text, trigger_in_words, cx) {
3660 self.show_completions(
3661 &ShowCompletions {
3662 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3663 },
3664 cx,
3665 );
3666 } else {
3667 self.hide_context_menu(cx);
3668 }
3669 }
3670
3671 fn is_completion_trigger(
3672 &self,
3673 text: &str,
3674 trigger_in_words: bool,
3675 cx: &mut ViewContext<Self>,
3676 ) -> bool {
3677 let position = self.selections.newest_anchor().head();
3678 let multibuffer = self.buffer.read(cx);
3679 let Some(buffer) = position
3680 .buffer_id
3681 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3682 else {
3683 return false;
3684 };
3685
3686 if let Some(completion_provider) = &self.completion_provider {
3687 completion_provider.is_completion_trigger(
3688 &buffer,
3689 position.text_anchor,
3690 text,
3691 trigger_in_words,
3692 cx,
3693 )
3694 } else {
3695 false
3696 }
3697 }
3698
3699 /// If any empty selections is touching the start of its innermost containing autoclose
3700 /// region, expand it to select the brackets.
3701 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3702 let selections = self.selections.all::<usize>(cx);
3703 let buffer = self.buffer.read(cx).read(cx);
3704 let new_selections = self
3705 .selections_with_autoclose_regions(selections, &buffer)
3706 .map(|(mut selection, region)| {
3707 if !selection.is_empty() {
3708 return selection;
3709 }
3710
3711 if let Some(region) = region {
3712 let mut range = region.range.to_offset(&buffer);
3713 if selection.start == range.start && range.start >= region.pair.start.len() {
3714 range.start -= region.pair.start.len();
3715 if buffer.contains_str_at(range.start, ®ion.pair.start)
3716 && buffer.contains_str_at(range.end, ®ion.pair.end)
3717 {
3718 range.end += region.pair.end.len();
3719 selection.start = range.start;
3720 selection.end = range.end;
3721
3722 return selection;
3723 }
3724 }
3725 }
3726
3727 let always_treat_brackets_as_autoclosed = buffer
3728 .settings_at(selection.start, cx)
3729 .always_treat_brackets_as_autoclosed;
3730
3731 if !always_treat_brackets_as_autoclosed {
3732 return selection;
3733 }
3734
3735 if let Some(scope) = buffer.language_scope_at(selection.start) {
3736 for (pair, enabled) in scope.brackets() {
3737 if !enabled || !pair.close {
3738 continue;
3739 }
3740
3741 if buffer.contains_str_at(selection.start, &pair.end) {
3742 let pair_start_len = pair.start.len();
3743 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3744 {
3745 selection.start -= pair_start_len;
3746 selection.end += pair.end.len();
3747
3748 return selection;
3749 }
3750 }
3751 }
3752 }
3753
3754 selection
3755 })
3756 .collect();
3757
3758 drop(buffer);
3759 self.change_selections(None, cx, |selections| selections.select(new_selections));
3760 }
3761
3762 /// Iterate the given selections, and for each one, find the smallest surrounding
3763 /// autoclose region. This uses the ordering of the selections and the autoclose
3764 /// regions to avoid repeated comparisons.
3765 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3766 &'a self,
3767 selections: impl IntoIterator<Item = Selection<D>>,
3768 buffer: &'a MultiBufferSnapshot,
3769 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3770 let mut i = 0;
3771 let mut regions = self.autoclose_regions.as_slice();
3772 selections.into_iter().map(move |selection| {
3773 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3774
3775 let mut enclosing = None;
3776 while let Some(pair_state) = regions.get(i) {
3777 if pair_state.range.end.to_offset(buffer) < range.start {
3778 regions = ®ions[i + 1..];
3779 i = 0;
3780 } else if pair_state.range.start.to_offset(buffer) > range.end {
3781 break;
3782 } else {
3783 if pair_state.selection_id == selection.id {
3784 enclosing = Some(pair_state);
3785 }
3786 i += 1;
3787 }
3788 }
3789
3790 (selection.clone(), enclosing)
3791 })
3792 }
3793
3794 /// Remove any autoclose regions that no longer contain their selection.
3795 fn invalidate_autoclose_regions(
3796 &mut self,
3797 mut selections: &[Selection<Anchor>],
3798 buffer: &MultiBufferSnapshot,
3799 ) {
3800 self.autoclose_regions.retain(|state| {
3801 let mut i = 0;
3802 while let Some(selection) = selections.get(i) {
3803 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3804 selections = &selections[1..];
3805 continue;
3806 }
3807 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3808 break;
3809 }
3810 if selection.id == state.selection_id {
3811 return true;
3812 } else {
3813 i += 1;
3814 }
3815 }
3816 false
3817 });
3818 }
3819
3820 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3821 let offset = position.to_offset(buffer);
3822 let (word_range, kind) = buffer.surrounding_word(offset);
3823 if offset > word_range.start && kind == Some(CharKind::Word) {
3824 Some(
3825 buffer
3826 .text_for_range(word_range.start..offset)
3827 .collect::<String>(),
3828 )
3829 } else {
3830 None
3831 }
3832 }
3833
3834 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3835 self.refresh_inlay_hints(
3836 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3837 cx,
3838 );
3839 }
3840
3841 pub fn inlay_hints_enabled(&self) -> bool {
3842 self.inlay_hint_cache.enabled
3843 }
3844
3845 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3846 if self.project.is_none() || self.mode != EditorMode::Full {
3847 return;
3848 }
3849
3850 let reason_description = reason.description();
3851 let ignore_debounce = matches!(
3852 reason,
3853 InlayHintRefreshReason::SettingsChange(_)
3854 | InlayHintRefreshReason::Toggle(_)
3855 | InlayHintRefreshReason::ExcerptsRemoved(_)
3856 );
3857 let (invalidate_cache, required_languages) = match reason {
3858 InlayHintRefreshReason::Toggle(enabled) => {
3859 self.inlay_hint_cache.enabled = enabled;
3860 if enabled {
3861 (InvalidationStrategy::RefreshRequested, None)
3862 } else {
3863 self.inlay_hint_cache.clear();
3864 self.splice_inlays(
3865 self.visible_inlay_hints(cx)
3866 .iter()
3867 .map(|inlay| inlay.id)
3868 .collect(),
3869 Vec::new(),
3870 cx,
3871 );
3872 return;
3873 }
3874 }
3875 InlayHintRefreshReason::SettingsChange(new_settings) => {
3876 match self.inlay_hint_cache.update_settings(
3877 &self.buffer,
3878 new_settings,
3879 self.visible_inlay_hints(cx),
3880 cx,
3881 ) {
3882 ControlFlow::Break(Some(InlaySplice {
3883 to_remove,
3884 to_insert,
3885 })) => {
3886 self.splice_inlays(to_remove, to_insert, cx);
3887 return;
3888 }
3889 ControlFlow::Break(None) => return,
3890 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3891 }
3892 }
3893 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3894 if let Some(InlaySplice {
3895 to_remove,
3896 to_insert,
3897 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3898 {
3899 self.splice_inlays(to_remove, to_insert, cx);
3900 }
3901 return;
3902 }
3903 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3904 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3905 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3906 }
3907 InlayHintRefreshReason::RefreshRequested => {
3908 (InvalidationStrategy::RefreshRequested, None)
3909 }
3910 };
3911
3912 if let Some(InlaySplice {
3913 to_remove,
3914 to_insert,
3915 }) = self.inlay_hint_cache.spawn_hint_refresh(
3916 reason_description,
3917 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3918 invalidate_cache,
3919 ignore_debounce,
3920 cx,
3921 ) {
3922 self.splice_inlays(to_remove, to_insert, cx);
3923 }
3924 }
3925
3926 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
3927 self.display_map
3928 .read(cx)
3929 .current_inlays()
3930 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3931 .cloned()
3932 .collect()
3933 }
3934
3935 pub fn excerpts_for_inlay_hints_query(
3936 &self,
3937 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3938 cx: &mut ViewContext<Editor>,
3939 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3940 let Some(project) = self.project.as_ref() else {
3941 return HashMap::default();
3942 };
3943 let project = project.read(cx);
3944 let multi_buffer = self.buffer().read(cx);
3945 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3946 let multi_buffer_visible_start = self
3947 .scroll_manager
3948 .anchor()
3949 .anchor
3950 .to_point(&multi_buffer_snapshot);
3951 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3952 multi_buffer_visible_start
3953 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3954 Bias::Left,
3955 );
3956 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3957 multi_buffer
3958 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
3959 .into_iter()
3960 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3961 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
3962 let buffer = buffer_handle.read(cx);
3963 let buffer_file = project::File::from_dyn(buffer.file())?;
3964 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3965 let worktree_entry = buffer_worktree
3966 .read(cx)
3967 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3968 if worktree_entry.is_ignored {
3969 return None;
3970 }
3971
3972 let language = buffer.language()?;
3973 if let Some(restrict_to_languages) = restrict_to_languages {
3974 if !restrict_to_languages.contains(language) {
3975 return None;
3976 }
3977 }
3978 Some((
3979 excerpt_id,
3980 (
3981 buffer_handle,
3982 buffer.version().clone(),
3983 excerpt_visible_range,
3984 ),
3985 ))
3986 })
3987 .collect()
3988 }
3989
3990 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3991 TextLayoutDetails {
3992 text_system: cx.text_system().clone(),
3993 editor_style: self.style.clone().unwrap(),
3994 rem_size: cx.rem_size(),
3995 scroll_anchor: self.scroll_manager.anchor(),
3996 visible_rows: self.visible_line_count(),
3997 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3998 }
3999 }
4000
4001 fn splice_inlays(
4002 &self,
4003 to_remove: Vec<InlayId>,
4004 to_insert: Vec<Inlay>,
4005 cx: &mut ViewContext<Self>,
4006 ) {
4007 self.display_map.update(cx, |display_map, cx| {
4008 display_map.splice_inlays(to_remove, to_insert, cx);
4009 });
4010 cx.notify();
4011 }
4012
4013 fn trigger_on_type_formatting(
4014 &self,
4015 input: String,
4016 cx: &mut ViewContext<Self>,
4017 ) -> Option<Task<Result<()>>> {
4018 if input.len() != 1 {
4019 return None;
4020 }
4021
4022 let project = self.project.as_ref()?;
4023 let position = self.selections.newest_anchor().head();
4024 let (buffer, buffer_position) = self
4025 .buffer
4026 .read(cx)
4027 .text_anchor_for_position(position, cx)?;
4028
4029 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4030 // hence we do LSP request & edit on host side only — add formats to host's history.
4031 let push_to_lsp_host_history = true;
4032 // If this is not the host, append its history with new edits.
4033 let push_to_client_history = project.read(cx).is_remote();
4034
4035 let on_type_formatting = project.update(cx, |project, cx| {
4036 project.on_type_format(
4037 buffer.clone(),
4038 buffer_position,
4039 input,
4040 push_to_lsp_host_history,
4041 cx,
4042 )
4043 });
4044 Some(cx.spawn(|editor, mut cx| async move {
4045 if let Some(transaction) = on_type_formatting.await? {
4046 if push_to_client_history {
4047 buffer
4048 .update(&mut cx, |buffer, _| {
4049 buffer.push_transaction(transaction, Instant::now());
4050 })
4051 .ok();
4052 }
4053 editor.update(&mut cx, |editor, cx| {
4054 editor.refresh_document_highlights(cx);
4055 })?;
4056 }
4057 Ok(())
4058 }))
4059 }
4060
4061 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4062 if self.pending_rename.is_some() {
4063 return;
4064 }
4065
4066 let Some(provider) = self.completion_provider.as_ref() else {
4067 return;
4068 };
4069
4070 let position = self.selections.newest_anchor().head();
4071 let (buffer, buffer_position) =
4072 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4073 output
4074 } else {
4075 return;
4076 };
4077
4078 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4079 let is_followup_invoke = {
4080 let context_menu_state = self.context_menu.read();
4081 matches!(
4082 context_menu_state.deref(),
4083 Some(ContextMenu::Completions(_))
4084 )
4085 };
4086 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4087 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4088 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(&trigger) => {
4089 CompletionTriggerKind::TRIGGER_CHARACTER
4090 }
4091
4092 _ => CompletionTriggerKind::INVOKED,
4093 };
4094 let completion_context = CompletionContext {
4095 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4096 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4097 Some(String::from(trigger))
4098 } else {
4099 None
4100 }
4101 }),
4102 trigger_kind,
4103 };
4104 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4105
4106 let id = post_inc(&mut self.next_completion_id);
4107 let task = cx.spawn(|this, mut cx| {
4108 async move {
4109 this.update(&mut cx, |this, _| {
4110 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4111 })?;
4112 let completions = completions.await.log_err();
4113 let menu = if let Some(completions) = completions {
4114 let mut menu = CompletionsMenu {
4115 id,
4116 initial_position: position,
4117 match_candidates: completions
4118 .iter()
4119 .enumerate()
4120 .map(|(id, completion)| {
4121 StringMatchCandidate::new(
4122 id,
4123 completion.label.text[completion.label.filter_range.clone()]
4124 .into(),
4125 )
4126 })
4127 .collect(),
4128 buffer: buffer.clone(),
4129 completions: Arc::new(RwLock::new(completions.into())),
4130 matches: Vec::new().into(),
4131 selected_item: 0,
4132 scroll_handle: UniformListScrollHandle::new(),
4133 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4134 DebouncedDelay::new(),
4135 )),
4136 };
4137 menu.filter(query.as_deref(), cx.background_executor().clone())
4138 .await;
4139
4140 if menu.matches.is_empty() {
4141 None
4142 } else {
4143 this.update(&mut cx, |editor, cx| {
4144 let completions = menu.completions.clone();
4145 let matches = menu.matches.clone();
4146
4147 let delay_ms = EditorSettings::get_global(cx)
4148 .completion_documentation_secondary_query_debounce;
4149 let delay = Duration::from_millis(delay_ms);
4150 editor
4151 .completion_documentation_pre_resolve_debounce
4152 .fire_new(delay, cx, |editor, cx| {
4153 CompletionsMenu::pre_resolve_completion_documentation(
4154 buffer,
4155 completions,
4156 matches,
4157 editor,
4158 cx,
4159 )
4160 });
4161 })
4162 .ok();
4163 Some(menu)
4164 }
4165 } else {
4166 None
4167 };
4168
4169 this.update(&mut cx, |this, cx| {
4170 let mut context_menu = this.context_menu.write();
4171 match context_menu.as_ref() {
4172 None => {}
4173
4174 Some(ContextMenu::Completions(prev_menu)) => {
4175 if prev_menu.id > id {
4176 return;
4177 }
4178 }
4179
4180 _ => return,
4181 }
4182
4183 if this.focus_handle.is_focused(cx) && menu.is_some() {
4184 let menu = menu.unwrap();
4185 *context_menu = Some(ContextMenu::Completions(menu));
4186 drop(context_menu);
4187 this.discard_inline_completion(false, cx);
4188 cx.notify();
4189 } else if this.completion_tasks.len() <= 1 {
4190 // If there are no more completion tasks and the last menu was
4191 // empty, we should hide it. If it was already hidden, we should
4192 // also show the copilot completion when available.
4193 drop(context_menu);
4194 if this.hide_context_menu(cx).is_none() {
4195 this.update_visible_inline_completion(cx);
4196 }
4197 }
4198 })?;
4199
4200 Ok::<_, anyhow::Error>(())
4201 }
4202 .log_err()
4203 });
4204
4205 self.completion_tasks.push((id, task));
4206 }
4207
4208 pub fn confirm_completion(
4209 &mut self,
4210 action: &ConfirmCompletion,
4211 cx: &mut ViewContext<Self>,
4212 ) -> Option<Task<Result<()>>> {
4213 use language::ToOffset as _;
4214
4215 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4216 menu
4217 } else {
4218 return None;
4219 };
4220
4221 let mat = completions_menu
4222 .matches
4223 .get(action.item_ix.unwrap_or(completions_menu.selected_item))?;
4224 let buffer_handle = completions_menu.buffer;
4225 let completions = completions_menu.completions.read();
4226 let completion = completions.get(mat.candidate_id)?;
4227 cx.stop_propagation();
4228
4229 let snippet;
4230 let text;
4231
4232 if completion.is_snippet() {
4233 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4234 text = snippet.as_ref().unwrap().text.clone();
4235 } else {
4236 snippet = None;
4237 text = completion.new_text.clone();
4238 };
4239 let selections = self.selections.all::<usize>(cx);
4240 let buffer = buffer_handle.read(cx);
4241 let old_range = completion.old_range.to_offset(buffer);
4242 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4243
4244 let newest_selection = self.selections.newest_anchor();
4245 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4246 return None;
4247 }
4248
4249 let lookbehind = newest_selection
4250 .start
4251 .text_anchor
4252 .to_offset(buffer)
4253 .saturating_sub(old_range.start);
4254 let lookahead = old_range
4255 .end
4256 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4257 let mut common_prefix_len = old_text
4258 .bytes()
4259 .zip(text.bytes())
4260 .take_while(|(a, b)| a == b)
4261 .count();
4262
4263 let snapshot = self.buffer.read(cx).snapshot(cx);
4264 let mut range_to_replace: Option<Range<isize>> = None;
4265 let mut ranges = Vec::new();
4266 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4267 for selection in &selections {
4268 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4269 let start = selection.start.saturating_sub(lookbehind);
4270 let end = selection.end + lookahead;
4271 if selection.id == newest_selection.id {
4272 range_to_replace = Some(
4273 ((start + common_prefix_len) as isize - selection.start as isize)
4274 ..(end as isize - selection.start as isize),
4275 );
4276 }
4277 ranges.push(start + common_prefix_len..end);
4278 } else {
4279 common_prefix_len = 0;
4280 ranges.clear();
4281 ranges.extend(selections.iter().map(|s| {
4282 if s.id == newest_selection.id {
4283 range_to_replace = Some(
4284 old_range.start.to_offset_utf16(&snapshot).0 as isize
4285 - selection.start as isize
4286 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4287 - selection.start as isize,
4288 );
4289 old_range.clone()
4290 } else {
4291 s.start..s.end
4292 }
4293 }));
4294 break;
4295 }
4296 if !self.linked_edit_ranges.is_empty() {
4297 let start_anchor = snapshot.anchor_before(selection.head());
4298 let end_anchor = snapshot.anchor_after(selection.tail());
4299 if let Some(ranges) = self
4300 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4301 {
4302 for (buffer, edits) in ranges {
4303 linked_edits.entry(buffer.clone()).or_default().extend(
4304 edits
4305 .into_iter()
4306 .map(|range| (range, text[common_prefix_len..].to_owned())),
4307 );
4308 }
4309 }
4310 }
4311 }
4312 let text = &text[common_prefix_len..];
4313
4314 cx.emit(EditorEvent::InputHandled {
4315 utf16_range_to_replace: range_to_replace,
4316 text: text.into(),
4317 });
4318
4319 self.transact(cx, |this, cx| {
4320 if let Some(mut snippet) = snippet {
4321 snippet.text = text.to_string();
4322 for tabstop in snippet.tabstops.iter_mut().flatten() {
4323 tabstop.start -= common_prefix_len as isize;
4324 tabstop.end -= common_prefix_len as isize;
4325 }
4326
4327 this.insert_snippet(&ranges, snippet, cx).log_err();
4328 } else {
4329 this.buffer.update(cx, |buffer, cx| {
4330 buffer.edit(
4331 ranges.iter().map(|range| (range.clone(), text)),
4332 this.autoindent_mode.clone(),
4333 cx,
4334 );
4335 });
4336 }
4337 for (buffer, edits) in linked_edits {
4338 buffer.update(cx, |buffer, cx| {
4339 let snapshot = buffer.snapshot();
4340 let edits = edits
4341 .into_iter()
4342 .map(|(range, text)| {
4343 use text::ToPoint as TP;
4344 let end_point = TP::to_point(&range.end, &snapshot);
4345 let start_point = TP::to_point(&range.start, &snapshot);
4346 (start_point..end_point, text)
4347 })
4348 .sorted_by_key(|(range, _)| range.start)
4349 .collect::<Vec<_>>();
4350 buffer.edit(edits, None, cx);
4351 })
4352 }
4353
4354 this.refresh_inline_completion(true, cx);
4355 });
4356
4357 if let Some(confirm) = completion.confirm.as_ref() {
4358 (confirm)(cx);
4359 }
4360
4361 if completion.show_new_completions_on_confirm {
4362 self.show_completions(&ShowCompletions { trigger: None }, cx);
4363 }
4364
4365 let provider = self.completion_provider.as_ref()?;
4366 let apply_edits = provider.apply_additional_edits_for_completion(
4367 buffer_handle,
4368 completion.clone(),
4369 true,
4370 cx,
4371 );
4372
4373 let editor_settings = EditorSettings::get_global(cx);
4374 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4375 // After the code completion is finished, users often want to know what signatures are needed.
4376 // so we should automatically call signature_help
4377 self.show_signature_help(&ShowSignatureHelp, cx);
4378 }
4379
4380 Some(cx.foreground_executor().spawn(async move {
4381 apply_edits.await?;
4382 Ok(())
4383 }))
4384 }
4385
4386 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4387 let mut context_menu = self.context_menu.write();
4388 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4389 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4390 // Toggle if we're selecting the same one
4391 *context_menu = None;
4392 cx.notify();
4393 return;
4394 } else {
4395 // Otherwise, clear it and start a new one
4396 *context_menu = None;
4397 cx.notify();
4398 }
4399 }
4400 drop(context_menu);
4401 let snapshot = self.snapshot(cx);
4402 let deployed_from_indicator = action.deployed_from_indicator;
4403 let mut task = self.code_actions_task.take();
4404 let action = action.clone();
4405 cx.spawn(|editor, mut cx| async move {
4406 while let Some(prev_task) = task {
4407 prev_task.await;
4408 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4409 }
4410
4411 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4412 if editor.focus_handle.is_focused(cx) {
4413 let multibuffer_point = action
4414 .deployed_from_indicator
4415 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4416 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4417 let (buffer, buffer_row) = snapshot
4418 .buffer_snapshot
4419 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4420 .and_then(|(buffer_snapshot, range)| {
4421 editor
4422 .buffer
4423 .read(cx)
4424 .buffer(buffer_snapshot.remote_id())
4425 .map(|buffer| (buffer, range.start.row))
4426 })?;
4427 let (_, code_actions) = editor
4428 .available_code_actions
4429 .clone()
4430 .and_then(|(location, code_actions)| {
4431 let snapshot = location.buffer.read(cx).snapshot();
4432 let point_range = location.range.to_point(&snapshot);
4433 let point_range = point_range.start.row..=point_range.end.row;
4434 if point_range.contains(&buffer_row) {
4435 Some((location, code_actions))
4436 } else {
4437 None
4438 }
4439 })
4440 .unzip();
4441 let buffer_id = buffer.read(cx).remote_id();
4442 let tasks = editor
4443 .tasks
4444 .get(&(buffer_id, buffer_row))
4445 .map(|t| Arc::new(t.to_owned()));
4446 if tasks.is_none() && code_actions.is_none() {
4447 return None;
4448 }
4449
4450 editor.completion_tasks.clear();
4451 editor.discard_inline_completion(false, cx);
4452 let task_context =
4453 tasks
4454 .as_ref()
4455 .zip(editor.project.clone())
4456 .map(|(tasks, project)| {
4457 let position = Point::new(buffer_row, tasks.column);
4458 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4459 let location = Location {
4460 buffer: buffer.clone(),
4461 range: range_start..range_start,
4462 };
4463 // Fill in the environmental variables from the tree-sitter captures
4464 let mut captured_task_variables = TaskVariables::default();
4465 for (capture_name, value) in tasks.extra_variables.clone() {
4466 captured_task_variables.insert(
4467 task::VariableName::Custom(capture_name.into()),
4468 value.clone(),
4469 );
4470 }
4471 project.update(cx, |project, cx| {
4472 project.task_context_for_location(
4473 captured_task_variables,
4474 location,
4475 cx,
4476 )
4477 })
4478 });
4479
4480 Some(cx.spawn(|editor, mut cx| async move {
4481 let task_context = match task_context {
4482 Some(task_context) => task_context.await,
4483 None => None,
4484 };
4485 let resolved_tasks =
4486 tasks.zip(task_context).map(|(tasks, task_context)| {
4487 Arc::new(ResolvedTasks {
4488 templates: tasks
4489 .templates
4490 .iter()
4491 .filter_map(|(kind, template)| {
4492 template
4493 .resolve_task(&kind.to_id_base(), &task_context)
4494 .map(|task| (kind.clone(), task))
4495 })
4496 .collect(),
4497 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4498 multibuffer_point.row,
4499 tasks.column,
4500 )),
4501 })
4502 });
4503 let spawn_straight_away = resolved_tasks
4504 .as_ref()
4505 .map_or(false, |tasks| tasks.templates.len() == 1)
4506 && code_actions
4507 .as_ref()
4508 .map_or(true, |actions| actions.is_empty());
4509 if let Some(task) = editor
4510 .update(&mut cx, |editor, cx| {
4511 *editor.context_menu.write() =
4512 Some(ContextMenu::CodeActions(CodeActionsMenu {
4513 buffer,
4514 actions: CodeActionContents {
4515 tasks: resolved_tasks,
4516 actions: code_actions,
4517 },
4518 selected_item: Default::default(),
4519 scroll_handle: UniformListScrollHandle::default(),
4520 deployed_from_indicator,
4521 }));
4522 if spawn_straight_away {
4523 if let Some(task) = editor.confirm_code_action(
4524 &ConfirmCodeAction { item_ix: Some(0) },
4525 cx,
4526 ) {
4527 cx.notify();
4528 return task;
4529 }
4530 }
4531 cx.notify();
4532 Task::ready(Ok(()))
4533 })
4534 .ok()
4535 {
4536 task.await
4537 } else {
4538 Ok(())
4539 }
4540 }))
4541 } else {
4542 Some(Task::ready(Ok(())))
4543 }
4544 })?;
4545 if let Some(task) = spawned_test_task {
4546 task.await?;
4547 }
4548
4549 Ok::<_, anyhow::Error>(())
4550 })
4551 .detach_and_log_err(cx);
4552 }
4553
4554 pub fn confirm_code_action(
4555 &mut self,
4556 action: &ConfirmCodeAction,
4557 cx: &mut ViewContext<Self>,
4558 ) -> Option<Task<Result<()>>> {
4559 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4560 menu
4561 } else {
4562 return None;
4563 };
4564 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4565 let action = actions_menu.actions.get(action_ix)?;
4566 let title = action.label();
4567 let buffer = actions_menu.buffer;
4568 let workspace = self.workspace()?;
4569
4570 match action {
4571 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4572 workspace.update(cx, |workspace, cx| {
4573 workspace::tasks::schedule_resolved_task(
4574 workspace,
4575 task_source_kind,
4576 resolved_task,
4577 false,
4578 cx,
4579 );
4580
4581 Some(Task::ready(Ok(())))
4582 })
4583 }
4584 CodeActionsItem::CodeAction(action) => {
4585 let apply_code_actions = workspace
4586 .read(cx)
4587 .project()
4588 .clone()
4589 .update(cx, |project, cx| {
4590 project.apply_code_action(buffer, action, true, cx)
4591 });
4592 let workspace = workspace.downgrade();
4593 Some(cx.spawn(|editor, cx| async move {
4594 let project_transaction = apply_code_actions.await?;
4595 Self::open_project_transaction(
4596 &editor,
4597 workspace,
4598 project_transaction,
4599 title,
4600 cx,
4601 )
4602 .await
4603 }))
4604 }
4605 }
4606 }
4607
4608 pub async fn open_project_transaction(
4609 this: &WeakView<Editor>,
4610 workspace: WeakView<Workspace>,
4611 transaction: ProjectTransaction,
4612 title: String,
4613 mut cx: AsyncWindowContext,
4614 ) -> Result<()> {
4615 let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
4616
4617 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4618 cx.update(|cx| {
4619 entries.sort_unstable_by_key(|(buffer, _)| {
4620 buffer.read(cx).file().map(|f| f.path().clone())
4621 });
4622 })?;
4623
4624 // If the project transaction's edits are all contained within this editor, then
4625 // avoid opening a new editor to display them.
4626
4627 if let Some((buffer, transaction)) = entries.first() {
4628 if entries.len() == 1 {
4629 let excerpt = this.update(&mut cx, |editor, cx| {
4630 editor
4631 .buffer()
4632 .read(cx)
4633 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4634 })?;
4635 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4636 if excerpted_buffer == *buffer {
4637 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4638 let excerpt_range = excerpt_range.to_offset(buffer);
4639 buffer
4640 .edited_ranges_for_transaction::<usize>(transaction)
4641 .all(|range| {
4642 excerpt_range.start <= range.start
4643 && excerpt_range.end >= range.end
4644 })
4645 })?;
4646
4647 if all_edits_within_excerpt {
4648 return Ok(());
4649 }
4650 }
4651 }
4652 }
4653 } else {
4654 return Ok(());
4655 }
4656
4657 let mut ranges_to_highlight = Vec::new();
4658 let excerpt_buffer = cx.new_model(|cx| {
4659 let mut multibuffer =
4660 MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
4661 for (buffer_handle, transaction) in &entries {
4662 let buffer = buffer_handle.read(cx);
4663 ranges_to_highlight.extend(
4664 multibuffer.push_excerpts_with_context_lines(
4665 buffer_handle.clone(),
4666 buffer
4667 .edited_ranges_for_transaction::<usize>(transaction)
4668 .collect(),
4669 DEFAULT_MULTIBUFFER_CONTEXT,
4670 cx,
4671 ),
4672 );
4673 }
4674 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4675 multibuffer
4676 })?;
4677
4678 workspace.update(&mut cx, |workspace, cx| {
4679 let project = workspace.project().clone();
4680 let editor =
4681 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4682 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4683 editor.update(cx, |editor, cx| {
4684 editor.highlight_background::<Self>(
4685 &ranges_to_highlight,
4686 |theme| theme.editor_highlighted_line_background,
4687 cx,
4688 );
4689 });
4690 })?;
4691
4692 Ok(())
4693 }
4694
4695 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4696 let project = self.project.clone()?;
4697 let buffer = self.buffer.read(cx);
4698 let newest_selection = self.selections.newest_anchor().clone();
4699 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4700 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4701 if start_buffer != end_buffer {
4702 return None;
4703 }
4704
4705 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4706 cx.background_executor()
4707 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4708 .await;
4709
4710 let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
4711 project.code_actions(&start_buffer, start..end, cx)
4712 }) {
4713 code_actions.await
4714 } else {
4715 Vec::new()
4716 };
4717
4718 this.update(&mut cx, |this, cx| {
4719 this.available_code_actions = if actions.is_empty() {
4720 None
4721 } else {
4722 Some((
4723 Location {
4724 buffer: start_buffer,
4725 range: start..end,
4726 },
4727 actions.into(),
4728 ))
4729 };
4730 cx.notify();
4731 })
4732 .log_err();
4733 }));
4734 None
4735 }
4736
4737 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4738 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4739 self.show_git_blame_inline = false;
4740
4741 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4742 cx.background_executor().timer(delay).await;
4743
4744 this.update(&mut cx, |this, cx| {
4745 this.show_git_blame_inline = true;
4746 cx.notify();
4747 })
4748 .log_err();
4749 }));
4750 }
4751 }
4752
4753 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4754 if self.pending_rename.is_some() {
4755 return None;
4756 }
4757
4758 let project = self.project.clone()?;
4759 let buffer = self.buffer.read(cx);
4760 let newest_selection = self.selections.newest_anchor().clone();
4761 let cursor_position = newest_selection.head();
4762 let (cursor_buffer, cursor_buffer_position) =
4763 buffer.text_anchor_for_position(cursor_position, cx)?;
4764 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4765 if cursor_buffer != tail_buffer {
4766 return None;
4767 }
4768
4769 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4770 cx.background_executor()
4771 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
4772 .await;
4773
4774 let highlights = if let Some(highlights) = project
4775 .update(&mut cx, |project, cx| {
4776 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4777 })
4778 .log_err()
4779 {
4780 highlights.await.log_err()
4781 } else {
4782 None
4783 };
4784
4785 if let Some(highlights) = highlights {
4786 this.update(&mut cx, |this, cx| {
4787 if this.pending_rename.is_some() {
4788 return;
4789 }
4790
4791 let buffer_id = cursor_position.buffer_id;
4792 let buffer = this.buffer.read(cx);
4793 if !buffer
4794 .text_anchor_for_position(cursor_position, cx)
4795 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4796 {
4797 return;
4798 }
4799
4800 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4801 let mut write_ranges = Vec::new();
4802 let mut read_ranges = Vec::new();
4803 for highlight in highlights {
4804 for (excerpt_id, excerpt_range) in
4805 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4806 {
4807 let start = highlight
4808 .range
4809 .start
4810 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4811 let end = highlight
4812 .range
4813 .end
4814 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4815 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4816 continue;
4817 }
4818
4819 let range = Anchor {
4820 buffer_id,
4821 excerpt_id: excerpt_id,
4822 text_anchor: start,
4823 }..Anchor {
4824 buffer_id,
4825 excerpt_id,
4826 text_anchor: end,
4827 };
4828 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4829 write_ranges.push(range);
4830 } else {
4831 read_ranges.push(range);
4832 }
4833 }
4834 }
4835
4836 this.highlight_background::<DocumentHighlightRead>(
4837 &read_ranges,
4838 |theme| theme.editor_document_highlight_read_background,
4839 cx,
4840 );
4841 this.highlight_background::<DocumentHighlightWrite>(
4842 &write_ranges,
4843 |theme| theme.editor_document_highlight_write_background,
4844 cx,
4845 );
4846 cx.notify();
4847 })
4848 .log_err();
4849 }
4850 }));
4851 None
4852 }
4853
4854 fn refresh_inline_completion(
4855 &mut self,
4856 debounce: bool,
4857 cx: &mut ViewContext<Self>,
4858 ) -> Option<()> {
4859 let provider = self.inline_completion_provider()?;
4860 let cursor = self.selections.newest_anchor().head();
4861 let (buffer, cursor_buffer_position) =
4862 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4863 if !self.show_inline_completions
4864 || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
4865 {
4866 self.discard_inline_completion(false, cx);
4867 return None;
4868 }
4869
4870 self.update_visible_inline_completion(cx);
4871 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4872 Some(())
4873 }
4874
4875 fn cycle_inline_completion(
4876 &mut self,
4877 direction: Direction,
4878 cx: &mut ViewContext<Self>,
4879 ) -> Option<()> {
4880 let provider = self.inline_completion_provider()?;
4881 let cursor = self.selections.newest_anchor().head();
4882 let (buffer, cursor_buffer_position) =
4883 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4884 if !self.show_inline_completions
4885 || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
4886 {
4887 return None;
4888 }
4889
4890 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4891 self.update_visible_inline_completion(cx);
4892
4893 Some(())
4894 }
4895
4896 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4897 if !self.has_active_inline_completion(cx) {
4898 self.refresh_inline_completion(false, cx);
4899 return;
4900 }
4901
4902 self.update_visible_inline_completion(cx);
4903 }
4904
4905 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4906 self.show_cursor_names(cx);
4907 }
4908
4909 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4910 self.show_cursor_names = true;
4911 cx.notify();
4912 cx.spawn(|this, mut cx| async move {
4913 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4914 this.update(&mut cx, |this, cx| {
4915 this.show_cursor_names = false;
4916 cx.notify()
4917 })
4918 .ok()
4919 })
4920 .detach();
4921 }
4922
4923 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4924 if self.has_active_inline_completion(cx) {
4925 self.cycle_inline_completion(Direction::Next, cx);
4926 } else {
4927 let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
4928 if is_copilot_disabled {
4929 cx.propagate();
4930 }
4931 }
4932 }
4933
4934 pub fn previous_inline_completion(
4935 &mut self,
4936 _: &PreviousInlineCompletion,
4937 cx: &mut ViewContext<Self>,
4938 ) {
4939 if self.has_active_inline_completion(cx) {
4940 self.cycle_inline_completion(Direction::Prev, cx);
4941 } else {
4942 let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
4943 if is_copilot_disabled {
4944 cx.propagate();
4945 }
4946 }
4947 }
4948
4949 pub fn accept_inline_completion(
4950 &mut self,
4951 _: &AcceptInlineCompletion,
4952 cx: &mut ViewContext<Self>,
4953 ) {
4954 let Some(completion) = self.take_active_inline_completion(cx) else {
4955 return;
4956 };
4957 if let Some(provider) = self.inline_completion_provider() {
4958 provider.accept(cx);
4959 }
4960
4961 cx.emit(EditorEvent::InputHandled {
4962 utf16_range_to_replace: None,
4963 text: completion.text.to_string().into(),
4964 });
4965 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
4966 self.refresh_inline_completion(true, cx);
4967 cx.notify();
4968 }
4969
4970 pub fn accept_partial_inline_completion(
4971 &mut self,
4972 _: &AcceptPartialInlineCompletion,
4973 cx: &mut ViewContext<Self>,
4974 ) {
4975 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
4976 if let Some(completion) = self.take_active_inline_completion(cx) {
4977 let mut partial_completion = completion
4978 .text
4979 .chars()
4980 .by_ref()
4981 .take_while(|c| c.is_alphabetic())
4982 .collect::<String>();
4983 if partial_completion.is_empty() {
4984 partial_completion = completion
4985 .text
4986 .chars()
4987 .by_ref()
4988 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4989 .collect::<String>();
4990 }
4991
4992 cx.emit(EditorEvent::InputHandled {
4993 utf16_range_to_replace: None,
4994 text: partial_completion.clone().into(),
4995 });
4996 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4997 self.refresh_inline_completion(true, cx);
4998 cx.notify();
4999 }
5000 }
5001 }
5002
5003 fn discard_inline_completion(
5004 &mut self,
5005 should_report_inline_completion_event: bool,
5006 cx: &mut ViewContext<Self>,
5007 ) -> bool {
5008 if let Some(provider) = self.inline_completion_provider() {
5009 provider.discard(should_report_inline_completion_event, cx);
5010 }
5011
5012 self.take_active_inline_completion(cx).is_some()
5013 }
5014
5015 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5016 if let Some(completion) = self.active_inline_completion.as_ref() {
5017 let buffer = self.buffer.read(cx).read(cx);
5018 completion.position.is_valid(&buffer)
5019 } else {
5020 false
5021 }
5022 }
5023
5024 fn take_active_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<Inlay> {
5025 let completion = self.active_inline_completion.take()?;
5026 self.display_map.update(cx, |map, cx| {
5027 map.splice_inlays(vec![completion.id], Default::default(), cx);
5028 });
5029 let buffer = self.buffer.read(cx).read(cx);
5030
5031 if completion.position.is_valid(&buffer) {
5032 Some(completion)
5033 } else {
5034 None
5035 }
5036 }
5037
5038 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5039 let selection = self.selections.newest_anchor();
5040 let cursor = selection.head();
5041
5042 if self.context_menu.read().is_none()
5043 && self.completion_tasks.is_empty()
5044 && selection.start == selection.end
5045 {
5046 if let Some(provider) = self.inline_completion_provider() {
5047 if let Some((buffer, cursor_buffer_position)) =
5048 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5049 {
5050 if let Some(text) =
5051 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5052 {
5053 let text = Rope::from(text);
5054 let mut to_remove = Vec::new();
5055 if let Some(completion) = self.active_inline_completion.take() {
5056 to_remove.push(completion.id);
5057 }
5058
5059 let completion_inlay =
5060 Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
5061 self.active_inline_completion = Some(completion_inlay.clone());
5062 self.display_map.update(cx, move |map, cx| {
5063 map.splice_inlays(to_remove, vec![completion_inlay], cx)
5064 });
5065 cx.notify();
5066 return;
5067 }
5068 }
5069 }
5070 }
5071
5072 self.discard_inline_completion(false, cx);
5073 }
5074
5075 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5076 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5077 }
5078
5079 fn render_code_actions_indicator(
5080 &self,
5081 _style: &EditorStyle,
5082 row: DisplayRow,
5083 is_active: bool,
5084 cx: &mut ViewContext<Self>,
5085 ) -> Option<IconButton> {
5086 if self.available_code_actions.is_some() {
5087 Some(
5088 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5089 .shape(ui::IconButtonShape::Square)
5090 .icon_size(IconSize::XSmall)
5091 .icon_color(Color::Muted)
5092 .selected(is_active)
5093 .on_click(cx.listener(move |editor, _e, cx| {
5094 editor.focus(cx);
5095 editor.toggle_code_actions(
5096 &ToggleCodeActions {
5097 deployed_from_indicator: Some(row),
5098 },
5099 cx,
5100 );
5101 })),
5102 )
5103 } else {
5104 None
5105 }
5106 }
5107
5108 fn clear_tasks(&mut self) {
5109 self.tasks.clear()
5110 }
5111
5112 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5113 if let Some(_) = self.tasks.insert(key, value) {
5114 // This case should hopefully be rare, but just in case...
5115 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5116 }
5117 }
5118
5119 fn render_run_indicator(
5120 &self,
5121 _style: &EditorStyle,
5122 is_active: bool,
5123 row: DisplayRow,
5124 cx: &mut ViewContext<Self>,
5125 ) -> IconButton {
5126 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5127 .shape(ui::IconButtonShape::Square)
5128 .icon_size(IconSize::XSmall)
5129 .icon_color(Color::Muted)
5130 .selected(is_active)
5131 .on_click(cx.listener(move |editor, _e, cx| {
5132 editor.focus(cx);
5133 editor.toggle_code_actions(
5134 &ToggleCodeActions {
5135 deployed_from_indicator: Some(row),
5136 },
5137 cx,
5138 );
5139 }))
5140 }
5141
5142 fn render_close_hunk_diff_button(
5143 &self,
5144 hunk: HoveredHunk,
5145 row: DisplayRow,
5146 cx: &mut ViewContext<Self>,
5147 ) -> IconButton {
5148 IconButton::new(
5149 ("close_hunk_diff_indicator", row.0 as usize),
5150 ui::IconName::Close,
5151 )
5152 .shape(ui::IconButtonShape::Square)
5153 .icon_size(IconSize::XSmall)
5154 .icon_color(Color::Muted)
5155 .tooltip(|cx| Tooltip::for_action("Close hunk diff", &ToggleHunkDiff, cx))
5156 .on_click(cx.listener(move |editor, _e, cx| editor.toggle_hovered_hunk(&hunk, cx)))
5157 }
5158
5159 pub fn context_menu_visible(&self) -> bool {
5160 self.context_menu
5161 .read()
5162 .as_ref()
5163 .map_or(false, |menu| menu.visible())
5164 }
5165
5166 fn render_context_menu(
5167 &self,
5168 cursor_position: DisplayPoint,
5169 style: &EditorStyle,
5170 max_height: Pixels,
5171 cx: &mut ViewContext<Editor>,
5172 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5173 self.context_menu.read().as_ref().map(|menu| {
5174 menu.render(
5175 cursor_position,
5176 style,
5177 max_height,
5178 self.workspace.as_ref().map(|(w, _)| w.clone()),
5179 cx,
5180 )
5181 })
5182 }
5183
5184 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5185 cx.notify();
5186 self.completion_tasks.clear();
5187 let context_menu = self.context_menu.write().take();
5188 if context_menu.is_some() {
5189 self.update_visible_inline_completion(cx);
5190 }
5191 context_menu
5192 }
5193
5194 pub fn insert_snippet(
5195 &mut self,
5196 insertion_ranges: &[Range<usize>],
5197 snippet: Snippet,
5198 cx: &mut ViewContext<Self>,
5199 ) -> Result<()> {
5200 struct Tabstop<T> {
5201 is_end_tabstop: bool,
5202 ranges: Vec<Range<T>>,
5203 }
5204
5205 let tabstops = self.buffer.update(cx, |buffer, cx| {
5206 let snippet_text: Arc<str> = snippet.text.clone().into();
5207 buffer.edit(
5208 insertion_ranges
5209 .iter()
5210 .cloned()
5211 .map(|range| (range, snippet_text.clone())),
5212 Some(AutoindentMode::EachLine),
5213 cx,
5214 );
5215
5216 let snapshot = &*buffer.read(cx);
5217 let snippet = &snippet;
5218 snippet
5219 .tabstops
5220 .iter()
5221 .map(|tabstop| {
5222 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5223 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5224 });
5225 let mut tabstop_ranges = tabstop
5226 .iter()
5227 .flat_map(|tabstop_range| {
5228 let mut delta = 0_isize;
5229 insertion_ranges.iter().map(move |insertion_range| {
5230 let insertion_start = insertion_range.start as isize + delta;
5231 delta +=
5232 snippet.text.len() as isize - insertion_range.len() as isize;
5233
5234 let start = ((insertion_start + tabstop_range.start) as usize)
5235 .min(snapshot.len());
5236 let end = ((insertion_start + tabstop_range.end) as usize)
5237 .min(snapshot.len());
5238 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5239 })
5240 })
5241 .collect::<Vec<_>>();
5242 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5243
5244 Tabstop {
5245 is_end_tabstop,
5246 ranges: tabstop_ranges,
5247 }
5248 })
5249 .collect::<Vec<_>>()
5250 });
5251 if let Some(tabstop) = tabstops.first() {
5252 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5253 s.select_ranges(tabstop.ranges.iter().cloned());
5254 });
5255
5256 // If we're already at the last tabstop and it's at the end of the snippet,
5257 // we're done, we don't need to keep the state around.
5258 if !tabstop.is_end_tabstop {
5259 let ranges = tabstops
5260 .into_iter()
5261 .map(|tabstop| tabstop.ranges)
5262 .collect::<Vec<_>>();
5263 self.snippet_stack.push(SnippetState {
5264 active_index: 0,
5265 ranges,
5266 });
5267 }
5268
5269 // Check whether the just-entered snippet ends with an auto-closable bracket.
5270 if self.autoclose_regions.is_empty() {
5271 let snapshot = self.buffer.read(cx).snapshot(cx);
5272 for selection in &mut self.selections.all::<Point>(cx) {
5273 let selection_head = selection.head();
5274 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5275 continue;
5276 };
5277
5278 let mut bracket_pair = None;
5279 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5280 let prev_chars = snapshot
5281 .reversed_chars_at(selection_head)
5282 .collect::<String>();
5283 for (pair, enabled) in scope.brackets() {
5284 if enabled
5285 && pair.close
5286 && prev_chars.starts_with(pair.start.as_str())
5287 && next_chars.starts_with(pair.end.as_str())
5288 {
5289 bracket_pair = Some(pair.clone());
5290 break;
5291 }
5292 }
5293 if let Some(pair) = bracket_pair {
5294 let start = snapshot.anchor_after(selection_head);
5295 let end = snapshot.anchor_after(selection_head);
5296 self.autoclose_regions.push(AutocloseRegion {
5297 selection_id: selection.id,
5298 range: start..end,
5299 pair,
5300 });
5301 }
5302 }
5303 }
5304 }
5305 Ok(())
5306 }
5307
5308 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5309 self.move_to_snippet_tabstop(Bias::Right, cx)
5310 }
5311
5312 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5313 self.move_to_snippet_tabstop(Bias::Left, cx)
5314 }
5315
5316 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5317 if let Some(mut snippet) = self.snippet_stack.pop() {
5318 match bias {
5319 Bias::Left => {
5320 if snippet.active_index > 0 {
5321 snippet.active_index -= 1;
5322 } else {
5323 self.snippet_stack.push(snippet);
5324 return false;
5325 }
5326 }
5327 Bias::Right => {
5328 if snippet.active_index + 1 < snippet.ranges.len() {
5329 snippet.active_index += 1;
5330 } else {
5331 self.snippet_stack.push(snippet);
5332 return false;
5333 }
5334 }
5335 }
5336 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5337 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5338 s.select_anchor_ranges(current_ranges.iter().cloned())
5339 });
5340 // If snippet state is not at the last tabstop, push it back on the stack
5341 if snippet.active_index + 1 < snippet.ranges.len() {
5342 self.snippet_stack.push(snippet);
5343 }
5344 return true;
5345 }
5346 }
5347
5348 false
5349 }
5350
5351 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5352 self.transact(cx, |this, cx| {
5353 this.select_all(&SelectAll, cx);
5354 this.insert("", cx);
5355 });
5356 }
5357
5358 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5359 self.transact(cx, |this, cx| {
5360 this.select_autoclose_pair(cx);
5361 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5362 if !this.linked_edit_ranges.is_empty() {
5363 let selections = this.selections.all::<MultiBufferPoint>(cx);
5364 let snapshot = this.buffer.read(cx).snapshot(cx);
5365
5366 for selection in selections.iter() {
5367 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5368 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5369 if selection_start.buffer_id != selection_end.buffer_id {
5370 continue;
5371 }
5372 if let Some(ranges) =
5373 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5374 {
5375 for (buffer, entries) in ranges {
5376 linked_ranges.entry(buffer).or_default().extend(entries);
5377 }
5378 }
5379 }
5380 }
5381
5382 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5383 if !this.selections.line_mode {
5384 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5385 for selection in &mut selections {
5386 if selection.is_empty() {
5387 let old_head = selection.head();
5388 let mut new_head =
5389 movement::left(&display_map, old_head.to_display_point(&display_map))
5390 .to_point(&display_map);
5391 if let Some((buffer, line_buffer_range)) = display_map
5392 .buffer_snapshot
5393 .buffer_line_for_row(MultiBufferRow(old_head.row))
5394 {
5395 let indent_size =
5396 buffer.indent_size_for_line(line_buffer_range.start.row);
5397 let indent_len = match indent_size.kind {
5398 IndentKind::Space => {
5399 buffer.settings_at(line_buffer_range.start, cx).tab_size
5400 }
5401 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5402 };
5403 if old_head.column <= indent_size.len && old_head.column > 0 {
5404 let indent_len = indent_len.get();
5405 new_head = cmp::min(
5406 new_head,
5407 MultiBufferPoint::new(
5408 old_head.row,
5409 ((old_head.column - 1) / indent_len) * indent_len,
5410 ),
5411 );
5412 }
5413 }
5414
5415 selection.set_head(new_head, SelectionGoal::None);
5416 }
5417 }
5418 }
5419
5420 this.signature_help_state.set_backspace_pressed(true);
5421 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5422 this.insert("", cx);
5423 let empty_str: Arc<str> = Arc::from("");
5424 for (buffer, edits) in linked_ranges {
5425 let snapshot = buffer.read(cx).snapshot();
5426 use text::ToPoint as TP;
5427
5428 let edits = edits
5429 .into_iter()
5430 .map(|range| {
5431 let end_point = TP::to_point(&range.end, &snapshot);
5432 let mut start_point = TP::to_point(&range.start, &snapshot);
5433
5434 if end_point == start_point {
5435 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5436 .saturating_sub(1);
5437 start_point = TP::to_point(&offset, &snapshot);
5438 };
5439
5440 (start_point..end_point, empty_str.clone())
5441 })
5442 .sorted_by_key(|(range, _)| range.start)
5443 .collect::<Vec<_>>();
5444 buffer.update(cx, |this, cx| {
5445 this.edit(edits, None, cx);
5446 })
5447 }
5448 this.refresh_inline_completion(true, cx);
5449 linked_editing_ranges::refresh_linked_ranges(this, cx);
5450 });
5451 }
5452
5453 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5454 self.transact(cx, |this, cx| {
5455 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5456 let line_mode = s.line_mode;
5457 s.move_with(|map, selection| {
5458 if selection.is_empty() && !line_mode {
5459 let cursor = movement::right(map, selection.head());
5460 selection.end = cursor;
5461 selection.reversed = true;
5462 selection.goal = SelectionGoal::None;
5463 }
5464 })
5465 });
5466 this.insert("", cx);
5467 this.refresh_inline_completion(true, cx);
5468 });
5469 }
5470
5471 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5472 if self.move_to_prev_snippet_tabstop(cx) {
5473 return;
5474 }
5475
5476 self.outdent(&Outdent, cx);
5477 }
5478
5479 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5480 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5481 return;
5482 }
5483
5484 let mut selections = self.selections.all_adjusted(cx);
5485 let buffer = self.buffer.read(cx);
5486 let snapshot = buffer.snapshot(cx);
5487 let rows_iter = selections.iter().map(|s| s.head().row);
5488 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5489
5490 let mut edits = Vec::new();
5491 let mut prev_edited_row = 0;
5492 let mut row_delta = 0;
5493 for selection in &mut selections {
5494 if selection.start.row != prev_edited_row {
5495 row_delta = 0;
5496 }
5497 prev_edited_row = selection.end.row;
5498
5499 // If the selection is non-empty, then increase the indentation of the selected lines.
5500 if !selection.is_empty() {
5501 row_delta =
5502 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5503 continue;
5504 }
5505
5506 // If the selection is empty and the cursor is in the leading whitespace before the
5507 // suggested indentation, then auto-indent the line.
5508 let cursor = selection.head();
5509 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5510 if let Some(suggested_indent) =
5511 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5512 {
5513 if cursor.column < suggested_indent.len
5514 && cursor.column <= current_indent.len
5515 && current_indent.len <= suggested_indent.len
5516 {
5517 selection.start = Point::new(cursor.row, suggested_indent.len);
5518 selection.end = selection.start;
5519 if row_delta == 0 {
5520 edits.extend(Buffer::edit_for_indent_size_adjustment(
5521 cursor.row,
5522 current_indent,
5523 suggested_indent,
5524 ));
5525 row_delta = suggested_indent.len - current_indent.len;
5526 }
5527 continue;
5528 }
5529 }
5530
5531 // Otherwise, insert a hard or soft tab.
5532 let settings = buffer.settings_at(cursor, cx);
5533 let tab_size = if settings.hard_tabs {
5534 IndentSize::tab()
5535 } else {
5536 let tab_size = settings.tab_size.get();
5537 let char_column = snapshot
5538 .text_for_range(Point::new(cursor.row, 0)..cursor)
5539 .flat_map(str::chars)
5540 .count()
5541 + row_delta as usize;
5542 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5543 IndentSize::spaces(chars_to_next_tab_stop)
5544 };
5545 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5546 selection.end = selection.start;
5547 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5548 row_delta += tab_size.len;
5549 }
5550
5551 self.transact(cx, |this, cx| {
5552 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5553 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5554 this.refresh_inline_completion(true, cx);
5555 });
5556 }
5557
5558 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5559 if self.read_only(cx) {
5560 return;
5561 }
5562 let mut selections = self.selections.all::<Point>(cx);
5563 let mut prev_edited_row = 0;
5564 let mut row_delta = 0;
5565 let mut edits = Vec::new();
5566 let buffer = self.buffer.read(cx);
5567 let snapshot = buffer.snapshot(cx);
5568 for selection in &mut selections {
5569 if selection.start.row != prev_edited_row {
5570 row_delta = 0;
5571 }
5572 prev_edited_row = selection.end.row;
5573
5574 row_delta =
5575 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5576 }
5577
5578 self.transact(cx, |this, cx| {
5579 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5580 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5581 });
5582 }
5583
5584 fn indent_selection(
5585 buffer: &MultiBuffer,
5586 snapshot: &MultiBufferSnapshot,
5587 selection: &mut Selection<Point>,
5588 edits: &mut Vec<(Range<Point>, String)>,
5589 delta_for_start_row: u32,
5590 cx: &AppContext,
5591 ) -> u32 {
5592 let settings = buffer.settings_at(selection.start, cx);
5593 let tab_size = settings.tab_size.get();
5594 let indent_kind = if settings.hard_tabs {
5595 IndentKind::Tab
5596 } else {
5597 IndentKind::Space
5598 };
5599 let mut start_row = selection.start.row;
5600 let mut end_row = selection.end.row + 1;
5601
5602 // If a selection ends at the beginning of a line, don't indent
5603 // that last line.
5604 if selection.end.column == 0 && selection.end.row > selection.start.row {
5605 end_row -= 1;
5606 }
5607
5608 // Avoid re-indenting a row that has already been indented by a
5609 // previous selection, but still update this selection's column
5610 // to reflect that indentation.
5611 if delta_for_start_row > 0 {
5612 start_row += 1;
5613 selection.start.column += delta_for_start_row;
5614 if selection.end.row == selection.start.row {
5615 selection.end.column += delta_for_start_row;
5616 }
5617 }
5618
5619 let mut delta_for_end_row = 0;
5620 let has_multiple_rows = start_row + 1 != end_row;
5621 for row in start_row..end_row {
5622 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5623 let indent_delta = match (current_indent.kind, indent_kind) {
5624 (IndentKind::Space, IndentKind::Space) => {
5625 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5626 IndentSize::spaces(columns_to_next_tab_stop)
5627 }
5628 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5629 (_, IndentKind::Tab) => IndentSize::tab(),
5630 };
5631
5632 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5633 0
5634 } else {
5635 selection.start.column
5636 };
5637 let row_start = Point::new(row, start);
5638 edits.push((
5639 row_start..row_start,
5640 indent_delta.chars().collect::<String>(),
5641 ));
5642
5643 // Update this selection's endpoints to reflect the indentation.
5644 if row == selection.start.row {
5645 selection.start.column += indent_delta.len;
5646 }
5647 if row == selection.end.row {
5648 selection.end.column += indent_delta.len;
5649 delta_for_end_row = indent_delta.len;
5650 }
5651 }
5652
5653 if selection.start.row == selection.end.row {
5654 delta_for_start_row + delta_for_end_row
5655 } else {
5656 delta_for_end_row
5657 }
5658 }
5659
5660 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5661 if self.read_only(cx) {
5662 return;
5663 }
5664 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5665 let selections = self.selections.all::<Point>(cx);
5666 let mut deletion_ranges = Vec::new();
5667 let mut last_outdent = None;
5668 {
5669 let buffer = self.buffer.read(cx);
5670 let snapshot = buffer.snapshot(cx);
5671 for selection in &selections {
5672 let settings = buffer.settings_at(selection.start, cx);
5673 let tab_size = settings.tab_size.get();
5674 let mut rows = selection.spanned_rows(false, &display_map);
5675
5676 // Avoid re-outdenting a row that has already been outdented by a
5677 // previous selection.
5678 if let Some(last_row) = last_outdent {
5679 if last_row == rows.start {
5680 rows.start = rows.start.next_row();
5681 }
5682 }
5683 let has_multiple_rows = rows.len() > 1;
5684 for row in rows.iter_rows() {
5685 let indent_size = snapshot.indent_size_for_line(row);
5686 if indent_size.len > 0 {
5687 let deletion_len = match indent_size.kind {
5688 IndentKind::Space => {
5689 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5690 if columns_to_prev_tab_stop == 0 {
5691 tab_size
5692 } else {
5693 columns_to_prev_tab_stop
5694 }
5695 }
5696 IndentKind::Tab => 1,
5697 };
5698 let start = if has_multiple_rows
5699 || deletion_len > selection.start.column
5700 || indent_size.len < selection.start.column
5701 {
5702 0
5703 } else {
5704 selection.start.column - deletion_len
5705 };
5706 deletion_ranges.push(
5707 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5708 );
5709 last_outdent = Some(row);
5710 }
5711 }
5712 }
5713 }
5714
5715 self.transact(cx, |this, cx| {
5716 this.buffer.update(cx, |buffer, cx| {
5717 let empty_str: Arc<str> = "".into();
5718 buffer.edit(
5719 deletion_ranges
5720 .into_iter()
5721 .map(|range| (range, empty_str.clone())),
5722 None,
5723 cx,
5724 );
5725 });
5726 let selections = this.selections.all::<usize>(cx);
5727 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5728 });
5729 }
5730
5731 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5732 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5733 let selections = self.selections.all::<Point>(cx);
5734
5735 let mut new_cursors = Vec::new();
5736 let mut edit_ranges = Vec::new();
5737 let mut selections = selections.iter().peekable();
5738 while let Some(selection) = selections.next() {
5739 let mut rows = selection.spanned_rows(false, &display_map);
5740 let goal_display_column = selection.head().to_display_point(&display_map).column();
5741
5742 // Accumulate contiguous regions of rows that we want to delete.
5743 while let Some(next_selection) = selections.peek() {
5744 let next_rows = next_selection.spanned_rows(false, &display_map);
5745 if next_rows.start <= rows.end {
5746 rows.end = next_rows.end;
5747 selections.next().unwrap();
5748 } else {
5749 break;
5750 }
5751 }
5752
5753 let buffer = &display_map.buffer_snapshot;
5754 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5755 let edit_end;
5756 let cursor_buffer_row;
5757 if buffer.max_point().row >= rows.end.0 {
5758 // If there's a line after the range, delete the \n from the end of the row range
5759 // and position the cursor on the next line.
5760 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5761 cursor_buffer_row = rows.end;
5762 } else {
5763 // If there isn't a line after the range, delete the \n from the line before the
5764 // start of the row range and position the cursor there.
5765 edit_start = edit_start.saturating_sub(1);
5766 edit_end = buffer.len();
5767 cursor_buffer_row = rows.start.previous_row();
5768 }
5769
5770 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5771 *cursor.column_mut() =
5772 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5773
5774 new_cursors.push((
5775 selection.id,
5776 buffer.anchor_after(cursor.to_point(&display_map)),
5777 ));
5778 edit_ranges.push(edit_start..edit_end);
5779 }
5780
5781 self.transact(cx, |this, cx| {
5782 let buffer = this.buffer.update(cx, |buffer, cx| {
5783 let empty_str: Arc<str> = "".into();
5784 buffer.edit(
5785 edit_ranges
5786 .into_iter()
5787 .map(|range| (range, empty_str.clone())),
5788 None,
5789 cx,
5790 );
5791 buffer.snapshot(cx)
5792 });
5793 let new_selections = new_cursors
5794 .into_iter()
5795 .map(|(id, cursor)| {
5796 let cursor = cursor.to_point(&buffer);
5797 Selection {
5798 id,
5799 start: cursor,
5800 end: cursor,
5801 reversed: false,
5802 goal: SelectionGoal::None,
5803 }
5804 })
5805 .collect();
5806
5807 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5808 s.select(new_selections);
5809 });
5810 });
5811 }
5812
5813 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5814 if self.read_only(cx) {
5815 return;
5816 }
5817 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5818 for selection in self.selections.all::<Point>(cx) {
5819 let start = MultiBufferRow(selection.start.row);
5820 let end = if selection.start.row == selection.end.row {
5821 MultiBufferRow(selection.start.row + 1)
5822 } else {
5823 MultiBufferRow(selection.end.row)
5824 };
5825
5826 if let Some(last_row_range) = row_ranges.last_mut() {
5827 if start <= last_row_range.end {
5828 last_row_range.end = end;
5829 continue;
5830 }
5831 }
5832 row_ranges.push(start..end);
5833 }
5834
5835 let snapshot = self.buffer.read(cx).snapshot(cx);
5836 let mut cursor_positions = Vec::new();
5837 for row_range in &row_ranges {
5838 let anchor = snapshot.anchor_before(Point::new(
5839 row_range.end.previous_row().0,
5840 snapshot.line_len(row_range.end.previous_row()),
5841 ));
5842 cursor_positions.push(anchor..anchor);
5843 }
5844
5845 self.transact(cx, |this, cx| {
5846 for row_range in row_ranges.into_iter().rev() {
5847 for row in row_range.iter_rows().rev() {
5848 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5849 let next_line_row = row.next_row();
5850 let indent = snapshot.indent_size_for_line(next_line_row);
5851 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5852
5853 let replace = if snapshot.line_len(next_line_row) > indent.len {
5854 " "
5855 } else {
5856 ""
5857 };
5858
5859 this.buffer.update(cx, |buffer, cx| {
5860 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5861 });
5862 }
5863 }
5864
5865 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5866 s.select_anchor_ranges(cursor_positions)
5867 });
5868 });
5869 }
5870
5871 pub fn sort_lines_case_sensitive(
5872 &mut self,
5873 _: &SortLinesCaseSensitive,
5874 cx: &mut ViewContext<Self>,
5875 ) {
5876 self.manipulate_lines(cx, |lines| lines.sort())
5877 }
5878
5879 pub fn sort_lines_case_insensitive(
5880 &mut self,
5881 _: &SortLinesCaseInsensitive,
5882 cx: &mut ViewContext<Self>,
5883 ) {
5884 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5885 }
5886
5887 pub fn unique_lines_case_insensitive(
5888 &mut self,
5889 _: &UniqueLinesCaseInsensitive,
5890 cx: &mut ViewContext<Self>,
5891 ) {
5892 self.manipulate_lines(cx, |lines| {
5893 let mut seen = HashSet::default();
5894 lines.retain(|line| seen.insert(line.to_lowercase()));
5895 })
5896 }
5897
5898 pub fn unique_lines_case_sensitive(
5899 &mut self,
5900 _: &UniqueLinesCaseSensitive,
5901 cx: &mut ViewContext<Self>,
5902 ) {
5903 self.manipulate_lines(cx, |lines| {
5904 let mut seen = HashSet::default();
5905 lines.retain(|line| seen.insert(*line));
5906 })
5907 }
5908
5909 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
5910 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
5911 if !revert_changes.is_empty() {
5912 self.transact(cx, |editor, cx| {
5913 editor.revert(revert_changes, cx);
5914 });
5915 }
5916 }
5917
5918 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
5919 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
5920 let project_path = buffer.read(cx).project_path(cx)?;
5921 let project = self.project.as_ref()?.read(cx);
5922 let entry = project.entry_for_path(&project_path, cx)?;
5923 let abs_path = project.absolute_path(&project_path, cx)?;
5924 let parent = if entry.is_symlink {
5925 abs_path.canonicalize().ok()?
5926 } else {
5927 abs_path
5928 }
5929 .parent()?
5930 .to_path_buf();
5931 Some(parent)
5932 }) {
5933 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
5934 }
5935 }
5936
5937 fn gather_revert_changes(
5938 &mut self,
5939 selections: &[Selection<Anchor>],
5940 cx: &mut ViewContext<'_, Editor>,
5941 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
5942 let mut revert_changes = HashMap::default();
5943 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
5944 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
5945 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
5946 }
5947 revert_changes
5948 }
5949
5950 pub fn prepare_revert_change(
5951 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
5952 multi_buffer: &Model<MultiBuffer>,
5953 hunk: &DiffHunk<MultiBufferRow>,
5954 cx: &AppContext,
5955 ) -> Option<()> {
5956 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
5957 let buffer = buffer.read(cx);
5958 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
5959 let buffer_snapshot = buffer.snapshot();
5960 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
5961 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
5962 probe
5963 .0
5964 .start
5965 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
5966 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
5967 }) {
5968 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
5969 Some(())
5970 } else {
5971 None
5972 }
5973 }
5974
5975 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
5976 self.manipulate_lines(cx, |lines| lines.reverse())
5977 }
5978
5979 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
5980 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
5981 }
5982
5983 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
5984 where
5985 Fn: FnMut(&mut Vec<&str>),
5986 {
5987 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5988 let buffer = self.buffer.read(cx).snapshot(cx);
5989
5990 let mut edits = Vec::new();
5991
5992 let selections = self.selections.all::<Point>(cx);
5993 let mut selections = selections.iter().peekable();
5994 let mut contiguous_row_selections = Vec::new();
5995 let mut new_selections = Vec::new();
5996 let mut added_lines = 0;
5997 let mut removed_lines = 0;
5998
5999 while let Some(selection) = selections.next() {
6000 let (start_row, end_row) = consume_contiguous_rows(
6001 &mut contiguous_row_selections,
6002 selection,
6003 &display_map,
6004 &mut selections,
6005 );
6006
6007 let start_point = Point::new(start_row.0, 0);
6008 let end_point = Point::new(
6009 end_row.previous_row().0,
6010 buffer.line_len(end_row.previous_row()),
6011 );
6012 let text = buffer
6013 .text_for_range(start_point..end_point)
6014 .collect::<String>();
6015
6016 let mut lines = text.split('\n').collect_vec();
6017
6018 let lines_before = lines.len();
6019 callback(&mut lines);
6020 let lines_after = lines.len();
6021
6022 edits.push((start_point..end_point, lines.join("\n")));
6023
6024 // Selections must change based on added and removed line count
6025 let start_row =
6026 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6027 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6028 new_selections.push(Selection {
6029 id: selection.id,
6030 start: start_row,
6031 end: end_row,
6032 goal: SelectionGoal::None,
6033 reversed: selection.reversed,
6034 });
6035
6036 if lines_after > lines_before {
6037 added_lines += lines_after - lines_before;
6038 } else if lines_before > lines_after {
6039 removed_lines += lines_before - lines_after;
6040 }
6041 }
6042
6043 self.transact(cx, |this, cx| {
6044 let buffer = this.buffer.update(cx, |buffer, cx| {
6045 buffer.edit(edits, None, cx);
6046 buffer.snapshot(cx)
6047 });
6048
6049 // Recalculate offsets on newly edited buffer
6050 let new_selections = new_selections
6051 .iter()
6052 .map(|s| {
6053 let start_point = Point::new(s.start.0, 0);
6054 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6055 Selection {
6056 id: s.id,
6057 start: buffer.point_to_offset(start_point),
6058 end: buffer.point_to_offset(end_point),
6059 goal: s.goal,
6060 reversed: s.reversed,
6061 }
6062 })
6063 .collect();
6064
6065 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6066 s.select(new_selections);
6067 });
6068
6069 this.request_autoscroll(Autoscroll::fit(), cx);
6070 });
6071 }
6072
6073 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6074 self.manipulate_text(cx, |text| text.to_uppercase())
6075 }
6076
6077 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6078 self.manipulate_text(cx, |text| text.to_lowercase())
6079 }
6080
6081 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6082 self.manipulate_text(cx, |text| {
6083 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6084 // https://github.com/rutrum/convert-case/issues/16
6085 text.split('\n')
6086 .map(|line| line.to_case(Case::Title))
6087 .join("\n")
6088 })
6089 }
6090
6091 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6092 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6093 }
6094
6095 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6096 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6097 }
6098
6099 pub fn convert_to_upper_camel_case(
6100 &mut self,
6101 _: &ConvertToUpperCamelCase,
6102 cx: &mut ViewContext<Self>,
6103 ) {
6104 self.manipulate_text(cx, |text| {
6105 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6106 // https://github.com/rutrum/convert-case/issues/16
6107 text.split('\n')
6108 .map(|line| line.to_case(Case::UpperCamel))
6109 .join("\n")
6110 })
6111 }
6112
6113 pub fn convert_to_lower_camel_case(
6114 &mut self,
6115 _: &ConvertToLowerCamelCase,
6116 cx: &mut ViewContext<Self>,
6117 ) {
6118 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6119 }
6120
6121 pub fn convert_to_opposite_case(
6122 &mut self,
6123 _: &ConvertToOppositeCase,
6124 cx: &mut ViewContext<Self>,
6125 ) {
6126 self.manipulate_text(cx, |text| {
6127 text.chars()
6128 .fold(String::with_capacity(text.len()), |mut t, c| {
6129 if c.is_uppercase() {
6130 t.extend(c.to_lowercase());
6131 } else {
6132 t.extend(c.to_uppercase());
6133 }
6134 t
6135 })
6136 })
6137 }
6138
6139 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6140 where
6141 Fn: FnMut(&str) -> String,
6142 {
6143 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6144 let buffer = self.buffer.read(cx).snapshot(cx);
6145
6146 let mut new_selections = Vec::new();
6147 let mut edits = Vec::new();
6148 let mut selection_adjustment = 0i32;
6149
6150 for selection in self.selections.all::<usize>(cx) {
6151 let selection_is_empty = selection.is_empty();
6152
6153 let (start, end) = if selection_is_empty {
6154 let word_range = movement::surrounding_word(
6155 &display_map,
6156 selection.start.to_display_point(&display_map),
6157 );
6158 let start = word_range.start.to_offset(&display_map, Bias::Left);
6159 let end = word_range.end.to_offset(&display_map, Bias::Left);
6160 (start, end)
6161 } else {
6162 (selection.start, selection.end)
6163 };
6164
6165 let text = buffer.text_for_range(start..end).collect::<String>();
6166 let old_length = text.len() as i32;
6167 let text = callback(&text);
6168
6169 new_selections.push(Selection {
6170 start: (start as i32 - selection_adjustment) as usize,
6171 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6172 goal: SelectionGoal::None,
6173 ..selection
6174 });
6175
6176 selection_adjustment += old_length - text.len() as i32;
6177
6178 edits.push((start..end, text));
6179 }
6180
6181 self.transact(cx, |this, cx| {
6182 this.buffer.update(cx, |buffer, cx| {
6183 buffer.edit(edits, None, cx);
6184 });
6185
6186 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6187 s.select(new_selections);
6188 });
6189
6190 this.request_autoscroll(Autoscroll::fit(), cx);
6191 });
6192 }
6193
6194 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6195 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6196 let buffer = &display_map.buffer_snapshot;
6197 let selections = self.selections.all::<Point>(cx);
6198
6199 let mut edits = Vec::new();
6200 let mut selections_iter = selections.iter().peekable();
6201 while let Some(selection) = selections_iter.next() {
6202 // Avoid duplicating the same lines twice.
6203 let mut rows = selection.spanned_rows(false, &display_map);
6204
6205 while let Some(next_selection) = selections_iter.peek() {
6206 let next_rows = next_selection.spanned_rows(false, &display_map);
6207 if next_rows.start < rows.end {
6208 rows.end = next_rows.end;
6209 selections_iter.next().unwrap();
6210 } else {
6211 break;
6212 }
6213 }
6214
6215 // Copy the text from the selected row region and splice it either at the start
6216 // or end of the region.
6217 let start = Point::new(rows.start.0, 0);
6218 let end = Point::new(
6219 rows.end.previous_row().0,
6220 buffer.line_len(rows.end.previous_row()),
6221 );
6222 let text = buffer
6223 .text_for_range(start..end)
6224 .chain(Some("\n"))
6225 .collect::<String>();
6226 let insert_location = if upwards {
6227 Point::new(rows.end.0, 0)
6228 } else {
6229 start
6230 };
6231 edits.push((insert_location..insert_location, text));
6232 }
6233
6234 self.transact(cx, |this, cx| {
6235 this.buffer.update(cx, |buffer, cx| {
6236 buffer.edit(edits, None, cx);
6237 });
6238
6239 this.request_autoscroll(Autoscroll::fit(), cx);
6240 });
6241 }
6242
6243 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6244 self.duplicate_line(true, cx);
6245 }
6246
6247 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6248 self.duplicate_line(false, cx);
6249 }
6250
6251 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6252 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6253 let buffer = self.buffer.read(cx).snapshot(cx);
6254
6255 let mut edits = Vec::new();
6256 let mut unfold_ranges = Vec::new();
6257 let mut refold_ranges = Vec::new();
6258
6259 let selections = self.selections.all::<Point>(cx);
6260 let mut selections = selections.iter().peekable();
6261 let mut contiguous_row_selections = Vec::new();
6262 let mut new_selections = Vec::new();
6263
6264 while let Some(selection) = selections.next() {
6265 // Find all the selections that span a contiguous row range
6266 let (start_row, end_row) = consume_contiguous_rows(
6267 &mut contiguous_row_selections,
6268 selection,
6269 &display_map,
6270 &mut selections,
6271 );
6272
6273 // Move the text spanned by the row range to be before the line preceding the row range
6274 if start_row.0 > 0 {
6275 let range_to_move = Point::new(
6276 start_row.previous_row().0,
6277 buffer.line_len(start_row.previous_row()),
6278 )
6279 ..Point::new(
6280 end_row.previous_row().0,
6281 buffer.line_len(end_row.previous_row()),
6282 );
6283 let insertion_point = display_map
6284 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6285 .0;
6286
6287 // Don't move lines across excerpts
6288 if buffer
6289 .excerpt_boundaries_in_range((
6290 Bound::Excluded(insertion_point),
6291 Bound::Included(range_to_move.end),
6292 ))
6293 .next()
6294 .is_none()
6295 {
6296 let text = buffer
6297 .text_for_range(range_to_move.clone())
6298 .flat_map(|s| s.chars())
6299 .skip(1)
6300 .chain(['\n'])
6301 .collect::<String>();
6302
6303 edits.push((
6304 buffer.anchor_after(range_to_move.start)
6305 ..buffer.anchor_before(range_to_move.end),
6306 String::new(),
6307 ));
6308 let insertion_anchor = buffer.anchor_after(insertion_point);
6309 edits.push((insertion_anchor..insertion_anchor, text));
6310
6311 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6312
6313 // Move selections up
6314 new_selections.extend(contiguous_row_selections.drain(..).map(
6315 |mut selection| {
6316 selection.start.row -= row_delta;
6317 selection.end.row -= row_delta;
6318 selection
6319 },
6320 ));
6321
6322 // Move folds up
6323 unfold_ranges.push(range_to_move.clone());
6324 for fold in display_map.folds_in_range(
6325 buffer.anchor_before(range_to_move.start)
6326 ..buffer.anchor_after(range_to_move.end),
6327 ) {
6328 let mut start = fold.range.start.to_point(&buffer);
6329 let mut end = fold.range.end.to_point(&buffer);
6330 start.row -= row_delta;
6331 end.row -= row_delta;
6332 refold_ranges.push((start..end, fold.placeholder.clone()));
6333 }
6334 }
6335 }
6336
6337 // If we didn't move line(s), preserve the existing selections
6338 new_selections.append(&mut contiguous_row_selections);
6339 }
6340
6341 self.transact(cx, |this, cx| {
6342 this.unfold_ranges(unfold_ranges, true, true, cx);
6343 this.buffer.update(cx, |buffer, cx| {
6344 for (range, text) in edits {
6345 buffer.edit([(range, text)], None, cx);
6346 }
6347 });
6348 this.fold_ranges(refold_ranges, true, cx);
6349 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6350 s.select(new_selections);
6351 })
6352 });
6353 }
6354
6355 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6356 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6357 let buffer = self.buffer.read(cx).snapshot(cx);
6358
6359 let mut edits = Vec::new();
6360 let mut unfold_ranges = Vec::new();
6361 let mut refold_ranges = Vec::new();
6362
6363 let selections = self.selections.all::<Point>(cx);
6364 let mut selections = selections.iter().peekable();
6365 let mut contiguous_row_selections = Vec::new();
6366 let mut new_selections = Vec::new();
6367
6368 while let Some(selection) = selections.next() {
6369 // Find all the selections that span a contiguous row range
6370 let (start_row, end_row) = consume_contiguous_rows(
6371 &mut contiguous_row_selections,
6372 selection,
6373 &display_map,
6374 &mut selections,
6375 );
6376
6377 // Move the text spanned by the row range to be after the last line of the row range
6378 if end_row.0 <= buffer.max_point().row {
6379 let range_to_move =
6380 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6381 let insertion_point = display_map
6382 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6383 .0;
6384
6385 // Don't move lines across excerpt boundaries
6386 if buffer
6387 .excerpt_boundaries_in_range((
6388 Bound::Excluded(range_to_move.start),
6389 Bound::Included(insertion_point),
6390 ))
6391 .next()
6392 .is_none()
6393 {
6394 let mut text = String::from("\n");
6395 text.extend(buffer.text_for_range(range_to_move.clone()));
6396 text.pop(); // Drop trailing newline
6397 edits.push((
6398 buffer.anchor_after(range_to_move.start)
6399 ..buffer.anchor_before(range_to_move.end),
6400 String::new(),
6401 ));
6402 let insertion_anchor = buffer.anchor_after(insertion_point);
6403 edits.push((insertion_anchor..insertion_anchor, text));
6404
6405 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6406
6407 // Move selections down
6408 new_selections.extend(contiguous_row_selections.drain(..).map(
6409 |mut selection| {
6410 selection.start.row += row_delta;
6411 selection.end.row += row_delta;
6412 selection
6413 },
6414 ));
6415
6416 // Move folds down
6417 unfold_ranges.push(range_to_move.clone());
6418 for fold in display_map.folds_in_range(
6419 buffer.anchor_before(range_to_move.start)
6420 ..buffer.anchor_after(range_to_move.end),
6421 ) {
6422 let mut start = fold.range.start.to_point(&buffer);
6423 let mut end = fold.range.end.to_point(&buffer);
6424 start.row += row_delta;
6425 end.row += row_delta;
6426 refold_ranges.push((start..end, fold.placeholder.clone()));
6427 }
6428 }
6429 }
6430
6431 // If we didn't move line(s), preserve the existing selections
6432 new_selections.append(&mut contiguous_row_selections);
6433 }
6434
6435 self.transact(cx, |this, cx| {
6436 this.unfold_ranges(unfold_ranges, true, true, cx);
6437 this.buffer.update(cx, |buffer, cx| {
6438 for (range, text) in edits {
6439 buffer.edit([(range, text)], None, cx);
6440 }
6441 });
6442 this.fold_ranges(refold_ranges, true, cx);
6443 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6444 });
6445 }
6446
6447 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6448 let text_layout_details = &self.text_layout_details(cx);
6449 self.transact(cx, |this, cx| {
6450 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6451 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6452 let line_mode = s.line_mode;
6453 s.move_with(|display_map, selection| {
6454 if !selection.is_empty() || line_mode {
6455 return;
6456 }
6457
6458 let mut head = selection.head();
6459 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6460 if head.column() == display_map.line_len(head.row()) {
6461 transpose_offset = display_map
6462 .buffer_snapshot
6463 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6464 }
6465
6466 if transpose_offset == 0 {
6467 return;
6468 }
6469
6470 *head.column_mut() += 1;
6471 head = display_map.clip_point(head, Bias::Right);
6472 let goal = SelectionGoal::HorizontalPosition(
6473 display_map
6474 .x_for_display_point(head, &text_layout_details)
6475 .into(),
6476 );
6477 selection.collapse_to(head, goal);
6478
6479 let transpose_start = display_map
6480 .buffer_snapshot
6481 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6482 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6483 let transpose_end = display_map
6484 .buffer_snapshot
6485 .clip_offset(transpose_offset + 1, Bias::Right);
6486 if let Some(ch) =
6487 display_map.buffer_snapshot.chars_at(transpose_start).next()
6488 {
6489 edits.push((transpose_start..transpose_offset, String::new()));
6490 edits.push((transpose_end..transpose_end, ch.to_string()));
6491 }
6492 }
6493 });
6494 edits
6495 });
6496 this.buffer
6497 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6498 let selections = this.selections.all::<usize>(cx);
6499 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6500 s.select(selections);
6501 });
6502 });
6503 }
6504
6505 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6506 let mut text = String::new();
6507 let buffer = self.buffer.read(cx).snapshot(cx);
6508 let mut selections = self.selections.all::<Point>(cx);
6509 let mut clipboard_selections = Vec::with_capacity(selections.len());
6510 {
6511 let max_point = buffer.max_point();
6512 let mut is_first = true;
6513 for selection in &mut selections {
6514 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6515 if is_entire_line {
6516 selection.start = Point::new(selection.start.row, 0);
6517 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6518 selection.goal = SelectionGoal::None;
6519 }
6520 if is_first {
6521 is_first = false;
6522 } else {
6523 text += "\n";
6524 }
6525 let mut len = 0;
6526 for chunk in buffer.text_for_range(selection.start..selection.end) {
6527 text.push_str(chunk);
6528 len += chunk.len();
6529 }
6530 clipboard_selections.push(ClipboardSelection {
6531 len,
6532 is_entire_line,
6533 first_line_indent: buffer
6534 .indent_size_for_line(MultiBufferRow(selection.start.row))
6535 .len,
6536 });
6537 }
6538 }
6539
6540 self.transact(cx, |this, cx| {
6541 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6542 s.select(selections);
6543 });
6544 this.insert("", cx);
6545 cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
6546 });
6547 }
6548
6549 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6550 let selections = self.selections.all::<Point>(cx);
6551 let buffer = self.buffer.read(cx).read(cx);
6552 let mut text = String::new();
6553
6554 let mut clipboard_selections = Vec::with_capacity(selections.len());
6555 {
6556 let max_point = buffer.max_point();
6557 let mut is_first = true;
6558 for selection in selections.iter() {
6559 let mut start = selection.start;
6560 let mut end = selection.end;
6561 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6562 if is_entire_line {
6563 start = Point::new(start.row, 0);
6564 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6565 }
6566 if is_first {
6567 is_first = false;
6568 } else {
6569 text += "\n";
6570 }
6571 let mut len = 0;
6572 for chunk in buffer.text_for_range(start..end) {
6573 text.push_str(chunk);
6574 len += chunk.len();
6575 }
6576 clipboard_selections.push(ClipboardSelection {
6577 len,
6578 is_entire_line,
6579 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6580 });
6581 }
6582 }
6583
6584 cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
6585 }
6586
6587 pub fn do_paste(
6588 &mut self,
6589 text: &String,
6590 clipboard_selections: Option<Vec<ClipboardSelection>>,
6591 handle_entire_lines: bool,
6592 cx: &mut ViewContext<Self>,
6593 ) {
6594 if self.read_only(cx) {
6595 return;
6596 }
6597
6598 let clipboard_text = Cow::Borrowed(text);
6599
6600 self.transact(cx, |this, cx| {
6601 if let Some(mut clipboard_selections) = clipboard_selections {
6602 let old_selections = this.selections.all::<usize>(cx);
6603 let all_selections_were_entire_line =
6604 clipboard_selections.iter().all(|s| s.is_entire_line);
6605 let first_selection_indent_column =
6606 clipboard_selections.first().map(|s| s.first_line_indent);
6607 if clipboard_selections.len() != old_selections.len() {
6608 clipboard_selections.drain(..);
6609 }
6610
6611 this.buffer.update(cx, |buffer, cx| {
6612 let snapshot = buffer.read(cx);
6613 let mut start_offset = 0;
6614 let mut edits = Vec::new();
6615 let mut original_indent_columns = Vec::new();
6616 for (ix, selection) in old_selections.iter().enumerate() {
6617 let to_insert;
6618 let entire_line;
6619 let original_indent_column;
6620 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6621 let end_offset = start_offset + clipboard_selection.len;
6622 to_insert = &clipboard_text[start_offset..end_offset];
6623 entire_line = clipboard_selection.is_entire_line;
6624 start_offset = end_offset + 1;
6625 original_indent_column = Some(clipboard_selection.first_line_indent);
6626 } else {
6627 to_insert = clipboard_text.as_str();
6628 entire_line = all_selections_were_entire_line;
6629 original_indent_column = first_selection_indent_column
6630 }
6631
6632 // If the corresponding selection was empty when this slice of the
6633 // clipboard text was written, then the entire line containing the
6634 // selection was copied. If this selection is also currently empty,
6635 // then paste the line before the current line of the buffer.
6636 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6637 let column = selection.start.to_point(&snapshot).column as usize;
6638 let line_start = selection.start - column;
6639 line_start..line_start
6640 } else {
6641 selection.range()
6642 };
6643
6644 edits.push((range, to_insert));
6645 original_indent_columns.extend(original_indent_column);
6646 }
6647 drop(snapshot);
6648
6649 buffer.edit(
6650 edits,
6651 Some(AutoindentMode::Block {
6652 original_indent_columns,
6653 }),
6654 cx,
6655 );
6656 });
6657
6658 let selections = this.selections.all::<usize>(cx);
6659 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6660 } else {
6661 this.insert(&clipboard_text, cx);
6662 }
6663 });
6664 }
6665
6666 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
6667 if let Some(item) = cx.read_from_clipboard() {
6668 self.do_paste(
6669 item.text(),
6670 item.metadata::<Vec<ClipboardSelection>>(),
6671 true,
6672 cx,
6673 )
6674 };
6675 }
6676
6677 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
6678 if self.read_only(cx) {
6679 return;
6680 }
6681
6682 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
6683 if let Some((selections, _)) =
6684 self.selection_history.transaction(transaction_id).cloned()
6685 {
6686 self.change_selections(None, cx, |s| {
6687 s.select_anchors(selections.to_vec());
6688 });
6689 }
6690 self.request_autoscroll(Autoscroll::fit(), cx);
6691 self.unmark_text(cx);
6692 self.refresh_inline_completion(true, cx);
6693 cx.emit(EditorEvent::Edited { transaction_id });
6694 cx.emit(EditorEvent::TransactionUndone { transaction_id });
6695 }
6696 }
6697
6698 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
6699 if self.read_only(cx) {
6700 return;
6701 }
6702
6703 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
6704 if let Some((_, Some(selections))) =
6705 self.selection_history.transaction(transaction_id).cloned()
6706 {
6707 self.change_selections(None, cx, |s| {
6708 s.select_anchors(selections.to_vec());
6709 });
6710 }
6711 self.request_autoscroll(Autoscroll::fit(), cx);
6712 self.unmark_text(cx);
6713 self.refresh_inline_completion(true, cx);
6714 cx.emit(EditorEvent::Edited { transaction_id });
6715 }
6716 }
6717
6718 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
6719 self.buffer
6720 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
6721 }
6722
6723 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
6724 self.buffer
6725 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
6726 }
6727
6728 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
6729 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6730 let line_mode = s.line_mode;
6731 s.move_with(|map, selection| {
6732 let cursor = if selection.is_empty() && !line_mode {
6733 movement::left(map, selection.start)
6734 } else {
6735 selection.start
6736 };
6737 selection.collapse_to(cursor, SelectionGoal::None);
6738 });
6739 })
6740 }
6741
6742 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
6743 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6744 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
6745 })
6746 }
6747
6748 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
6749 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6750 let line_mode = s.line_mode;
6751 s.move_with(|map, selection| {
6752 let cursor = if selection.is_empty() && !line_mode {
6753 movement::right(map, selection.end)
6754 } else {
6755 selection.end
6756 };
6757 selection.collapse_to(cursor, SelectionGoal::None)
6758 });
6759 })
6760 }
6761
6762 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
6763 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6764 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
6765 })
6766 }
6767
6768 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
6769 if self.take_rename(true, cx).is_some() {
6770 return;
6771 }
6772
6773 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6774 cx.propagate();
6775 return;
6776 }
6777
6778 let text_layout_details = &self.text_layout_details(cx);
6779 let selection_count = self.selections.count();
6780 let first_selection = self.selections.first_anchor();
6781
6782 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6783 let line_mode = s.line_mode;
6784 s.move_with(|map, selection| {
6785 if !selection.is_empty() && !line_mode {
6786 selection.goal = SelectionGoal::None;
6787 }
6788 let (cursor, goal) = movement::up(
6789 map,
6790 selection.start,
6791 selection.goal,
6792 false,
6793 &text_layout_details,
6794 );
6795 selection.collapse_to(cursor, goal);
6796 });
6797 });
6798
6799 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
6800 {
6801 cx.propagate();
6802 }
6803 }
6804
6805 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
6806 if self.take_rename(true, cx).is_some() {
6807 return;
6808 }
6809
6810 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6811 cx.propagate();
6812 return;
6813 }
6814
6815 let text_layout_details = &self.text_layout_details(cx);
6816
6817 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6818 let line_mode = s.line_mode;
6819 s.move_with(|map, selection| {
6820 if !selection.is_empty() && !line_mode {
6821 selection.goal = SelectionGoal::None;
6822 }
6823 let (cursor, goal) = movement::up_by_rows(
6824 map,
6825 selection.start,
6826 action.lines,
6827 selection.goal,
6828 false,
6829 &text_layout_details,
6830 );
6831 selection.collapse_to(cursor, goal);
6832 });
6833 })
6834 }
6835
6836 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
6837 if self.take_rename(true, cx).is_some() {
6838 return;
6839 }
6840
6841 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6842 cx.propagate();
6843 return;
6844 }
6845
6846 let text_layout_details = &self.text_layout_details(cx);
6847
6848 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6849 let line_mode = s.line_mode;
6850 s.move_with(|map, selection| {
6851 if !selection.is_empty() && !line_mode {
6852 selection.goal = SelectionGoal::None;
6853 }
6854 let (cursor, goal) = movement::down_by_rows(
6855 map,
6856 selection.start,
6857 action.lines,
6858 selection.goal,
6859 false,
6860 &text_layout_details,
6861 );
6862 selection.collapse_to(cursor, goal);
6863 });
6864 })
6865 }
6866
6867 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
6868 let text_layout_details = &self.text_layout_details(cx);
6869 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6870 s.move_heads_with(|map, head, goal| {
6871 movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
6872 })
6873 })
6874 }
6875
6876 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
6877 let text_layout_details = &self.text_layout_details(cx);
6878 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6879 s.move_heads_with(|map, head, goal| {
6880 movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
6881 })
6882 })
6883 }
6884
6885 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
6886 let Some(row_count) = self.visible_row_count() else {
6887 return;
6888 };
6889
6890 let text_layout_details = &self.text_layout_details(cx);
6891
6892 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6893 s.move_heads_with(|map, head, goal| {
6894 movement::up_by_rows(map, head, row_count, goal, false, &text_layout_details)
6895 })
6896 })
6897 }
6898
6899 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
6900 if self.take_rename(true, cx).is_some() {
6901 return;
6902 }
6903
6904 if self
6905 .context_menu
6906 .write()
6907 .as_mut()
6908 .map(|menu| menu.select_first(self.project.as_ref(), cx))
6909 .unwrap_or(false)
6910 {
6911 return;
6912 }
6913
6914 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6915 cx.propagate();
6916 return;
6917 }
6918
6919 let Some(row_count) = self.visible_row_count() else {
6920 return;
6921 };
6922
6923 let autoscroll = if action.center_cursor {
6924 Autoscroll::center()
6925 } else {
6926 Autoscroll::fit()
6927 };
6928
6929 let text_layout_details = &self.text_layout_details(cx);
6930
6931 self.change_selections(Some(autoscroll), cx, |s| {
6932 let line_mode = s.line_mode;
6933 s.move_with(|map, selection| {
6934 if !selection.is_empty() && !line_mode {
6935 selection.goal = SelectionGoal::None;
6936 }
6937 let (cursor, goal) = movement::up_by_rows(
6938 map,
6939 selection.end,
6940 row_count,
6941 selection.goal,
6942 false,
6943 &text_layout_details,
6944 );
6945 selection.collapse_to(cursor, goal);
6946 });
6947 });
6948 }
6949
6950 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
6951 let text_layout_details = &self.text_layout_details(cx);
6952 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6953 s.move_heads_with(|map, head, goal| {
6954 movement::up(map, head, goal, false, &text_layout_details)
6955 })
6956 })
6957 }
6958
6959 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
6960 self.take_rename(true, cx);
6961
6962 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6963 cx.propagate();
6964 return;
6965 }
6966
6967 let text_layout_details = &self.text_layout_details(cx);
6968 let selection_count = self.selections.count();
6969 let first_selection = self.selections.first_anchor();
6970
6971 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6972 let line_mode = s.line_mode;
6973 s.move_with(|map, selection| {
6974 if !selection.is_empty() && !line_mode {
6975 selection.goal = SelectionGoal::None;
6976 }
6977 let (cursor, goal) = movement::down(
6978 map,
6979 selection.end,
6980 selection.goal,
6981 false,
6982 &text_layout_details,
6983 );
6984 selection.collapse_to(cursor, goal);
6985 });
6986 });
6987
6988 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
6989 {
6990 cx.propagate();
6991 }
6992 }
6993
6994 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
6995 let Some(row_count) = self.visible_row_count() else {
6996 return;
6997 };
6998
6999 let text_layout_details = &self.text_layout_details(cx);
7000
7001 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7002 s.move_heads_with(|map, head, goal| {
7003 movement::down_by_rows(map, head, row_count, goal, false, &text_layout_details)
7004 })
7005 })
7006 }
7007
7008 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7009 if self.take_rename(true, cx).is_some() {
7010 return;
7011 }
7012
7013 if self
7014 .context_menu
7015 .write()
7016 .as_mut()
7017 .map(|menu| menu.select_last(self.project.as_ref(), cx))
7018 .unwrap_or(false)
7019 {
7020 return;
7021 }
7022
7023 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7024 cx.propagate();
7025 return;
7026 }
7027
7028 let Some(row_count) = self.visible_row_count() else {
7029 return;
7030 };
7031
7032 let autoscroll = if action.center_cursor {
7033 Autoscroll::center()
7034 } else {
7035 Autoscroll::fit()
7036 };
7037
7038 let text_layout_details = &self.text_layout_details(cx);
7039 self.change_selections(Some(autoscroll), cx, |s| {
7040 let line_mode = s.line_mode;
7041 s.move_with(|map, selection| {
7042 if !selection.is_empty() && !line_mode {
7043 selection.goal = SelectionGoal::None;
7044 }
7045 let (cursor, goal) = movement::down_by_rows(
7046 map,
7047 selection.end,
7048 row_count,
7049 selection.goal,
7050 false,
7051 &text_layout_details,
7052 );
7053 selection.collapse_to(cursor, goal);
7054 });
7055 });
7056 }
7057
7058 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7059 let text_layout_details = &self.text_layout_details(cx);
7060 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7061 s.move_heads_with(|map, head, goal| {
7062 movement::down(map, head, goal, false, &text_layout_details)
7063 })
7064 });
7065 }
7066
7067 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7068 if let Some(context_menu) = self.context_menu.write().as_mut() {
7069 context_menu.select_first(self.project.as_ref(), cx);
7070 }
7071 }
7072
7073 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7074 if let Some(context_menu) = self.context_menu.write().as_mut() {
7075 context_menu.select_prev(self.project.as_ref(), cx);
7076 }
7077 }
7078
7079 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7080 if let Some(context_menu) = self.context_menu.write().as_mut() {
7081 context_menu.select_next(self.project.as_ref(), cx);
7082 }
7083 }
7084
7085 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7086 if let Some(context_menu) = self.context_menu.write().as_mut() {
7087 context_menu.select_last(self.project.as_ref(), cx);
7088 }
7089 }
7090
7091 pub fn move_to_previous_word_start(
7092 &mut self,
7093 _: &MoveToPreviousWordStart,
7094 cx: &mut ViewContext<Self>,
7095 ) {
7096 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7097 s.move_cursors_with(|map, head, _| {
7098 (
7099 movement::previous_word_start(map, head),
7100 SelectionGoal::None,
7101 )
7102 });
7103 })
7104 }
7105
7106 pub fn move_to_previous_subword_start(
7107 &mut self,
7108 _: &MoveToPreviousSubwordStart,
7109 cx: &mut ViewContext<Self>,
7110 ) {
7111 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7112 s.move_cursors_with(|map, head, _| {
7113 (
7114 movement::previous_subword_start(map, head),
7115 SelectionGoal::None,
7116 )
7117 });
7118 })
7119 }
7120
7121 pub fn select_to_previous_word_start(
7122 &mut self,
7123 _: &SelectToPreviousWordStart,
7124 cx: &mut ViewContext<Self>,
7125 ) {
7126 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7127 s.move_heads_with(|map, head, _| {
7128 (
7129 movement::previous_word_start(map, head),
7130 SelectionGoal::None,
7131 )
7132 });
7133 })
7134 }
7135
7136 pub fn select_to_previous_subword_start(
7137 &mut self,
7138 _: &SelectToPreviousSubwordStart,
7139 cx: &mut ViewContext<Self>,
7140 ) {
7141 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7142 s.move_heads_with(|map, head, _| {
7143 (
7144 movement::previous_subword_start(map, head),
7145 SelectionGoal::None,
7146 )
7147 });
7148 })
7149 }
7150
7151 pub fn delete_to_previous_word_start(
7152 &mut self,
7153 _: &DeleteToPreviousWordStart,
7154 cx: &mut ViewContext<Self>,
7155 ) {
7156 self.transact(cx, |this, cx| {
7157 this.select_autoclose_pair(cx);
7158 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7159 let line_mode = s.line_mode;
7160 s.move_with(|map, selection| {
7161 if selection.is_empty() && !line_mode {
7162 let cursor = movement::previous_word_start(map, selection.head());
7163 selection.set_head(cursor, SelectionGoal::None);
7164 }
7165 });
7166 });
7167 this.insert("", cx);
7168 });
7169 }
7170
7171 pub fn delete_to_previous_subword_start(
7172 &mut self,
7173 _: &DeleteToPreviousSubwordStart,
7174 cx: &mut ViewContext<Self>,
7175 ) {
7176 self.transact(cx, |this, cx| {
7177 this.select_autoclose_pair(cx);
7178 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7179 let line_mode = s.line_mode;
7180 s.move_with(|map, selection| {
7181 if selection.is_empty() && !line_mode {
7182 let cursor = movement::previous_subword_start(map, selection.head());
7183 selection.set_head(cursor, SelectionGoal::None);
7184 }
7185 });
7186 });
7187 this.insert("", cx);
7188 });
7189 }
7190
7191 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7192 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7193 s.move_cursors_with(|map, head, _| {
7194 (movement::next_word_end(map, head), SelectionGoal::None)
7195 });
7196 })
7197 }
7198
7199 pub fn move_to_next_subword_end(
7200 &mut self,
7201 _: &MoveToNextSubwordEnd,
7202 cx: &mut ViewContext<Self>,
7203 ) {
7204 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7205 s.move_cursors_with(|map, head, _| {
7206 (movement::next_subword_end(map, head), SelectionGoal::None)
7207 });
7208 })
7209 }
7210
7211 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7212 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7213 s.move_heads_with(|map, head, _| {
7214 (movement::next_word_end(map, head), SelectionGoal::None)
7215 });
7216 })
7217 }
7218
7219 pub fn select_to_next_subword_end(
7220 &mut self,
7221 _: &SelectToNextSubwordEnd,
7222 cx: &mut ViewContext<Self>,
7223 ) {
7224 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7225 s.move_heads_with(|map, head, _| {
7226 (movement::next_subword_end(map, head), SelectionGoal::None)
7227 });
7228 })
7229 }
7230
7231 pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
7232 self.transact(cx, |this, cx| {
7233 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7234 let line_mode = s.line_mode;
7235 s.move_with(|map, selection| {
7236 if selection.is_empty() && !line_mode {
7237 let cursor = movement::next_word_end(map, selection.head());
7238 selection.set_head(cursor, SelectionGoal::None);
7239 }
7240 });
7241 });
7242 this.insert("", cx);
7243 });
7244 }
7245
7246 pub fn delete_to_next_subword_end(
7247 &mut self,
7248 _: &DeleteToNextSubwordEnd,
7249 cx: &mut ViewContext<Self>,
7250 ) {
7251 self.transact(cx, |this, cx| {
7252 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7253 s.move_with(|map, selection| {
7254 if selection.is_empty() {
7255 let cursor = movement::next_subword_end(map, selection.head());
7256 selection.set_head(cursor, SelectionGoal::None);
7257 }
7258 });
7259 });
7260 this.insert("", cx);
7261 });
7262 }
7263
7264 pub fn move_to_beginning_of_line(
7265 &mut self,
7266 action: &MoveToBeginningOfLine,
7267 cx: &mut ViewContext<Self>,
7268 ) {
7269 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7270 s.move_cursors_with(|map, head, _| {
7271 (
7272 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7273 SelectionGoal::None,
7274 )
7275 });
7276 })
7277 }
7278
7279 pub fn select_to_beginning_of_line(
7280 &mut self,
7281 action: &SelectToBeginningOfLine,
7282 cx: &mut ViewContext<Self>,
7283 ) {
7284 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7285 s.move_heads_with(|map, head, _| {
7286 (
7287 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7288 SelectionGoal::None,
7289 )
7290 });
7291 });
7292 }
7293
7294 pub fn delete_to_beginning_of_line(
7295 &mut self,
7296 _: &DeleteToBeginningOfLine,
7297 cx: &mut ViewContext<Self>,
7298 ) {
7299 self.transact(cx, |this, cx| {
7300 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7301 s.move_with(|_, selection| {
7302 selection.reversed = true;
7303 });
7304 });
7305
7306 this.select_to_beginning_of_line(
7307 &SelectToBeginningOfLine {
7308 stop_at_soft_wraps: false,
7309 },
7310 cx,
7311 );
7312 this.backspace(&Backspace, cx);
7313 });
7314 }
7315
7316 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7317 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7318 s.move_cursors_with(|map, head, _| {
7319 (
7320 movement::line_end(map, head, action.stop_at_soft_wraps),
7321 SelectionGoal::None,
7322 )
7323 });
7324 })
7325 }
7326
7327 pub fn select_to_end_of_line(
7328 &mut self,
7329 action: &SelectToEndOfLine,
7330 cx: &mut ViewContext<Self>,
7331 ) {
7332 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7333 s.move_heads_with(|map, head, _| {
7334 (
7335 movement::line_end(map, head, action.stop_at_soft_wraps),
7336 SelectionGoal::None,
7337 )
7338 });
7339 })
7340 }
7341
7342 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7343 self.transact(cx, |this, cx| {
7344 this.select_to_end_of_line(
7345 &SelectToEndOfLine {
7346 stop_at_soft_wraps: false,
7347 },
7348 cx,
7349 );
7350 this.delete(&Delete, cx);
7351 });
7352 }
7353
7354 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7355 self.transact(cx, |this, cx| {
7356 this.select_to_end_of_line(
7357 &SelectToEndOfLine {
7358 stop_at_soft_wraps: false,
7359 },
7360 cx,
7361 );
7362 this.cut(&Cut, cx);
7363 });
7364 }
7365
7366 pub fn move_to_start_of_paragraph(
7367 &mut self,
7368 _: &MoveToStartOfParagraph,
7369 cx: &mut ViewContext<Self>,
7370 ) {
7371 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7372 cx.propagate();
7373 return;
7374 }
7375
7376 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7377 s.move_with(|map, selection| {
7378 selection.collapse_to(
7379 movement::start_of_paragraph(map, selection.head(), 1),
7380 SelectionGoal::None,
7381 )
7382 });
7383 })
7384 }
7385
7386 pub fn move_to_end_of_paragraph(
7387 &mut self,
7388 _: &MoveToEndOfParagraph,
7389 cx: &mut ViewContext<Self>,
7390 ) {
7391 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7392 cx.propagate();
7393 return;
7394 }
7395
7396 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7397 s.move_with(|map, selection| {
7398 selection.collapse_to(
7399 movement::end_of_paragraph(map, selection.head(), 1),
7400 SelectionGoal::None,
7401 )
7402 });
7403 })
7404 }
7405
7406 pub fn select_to_start_of_paragraph(
7407 &mut self,
7408 _: &SelectToStartOfParagraph,
7409 cx: &mut ViewContext<Self>,
7410 ) {
7411 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7412 cx.propagate();
7413 return;
7414 }
7415
7416 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7417 s.move_heads_with(|map, head, _| {
7418 (
7419 movement::start_of_paragraph(map, head, 1),
7420 SelectionGoal::None,
7421 )
7422 });
7423 })
7424 }
7425
7426 pub fn select_to_end_of_paragraph(
7427 &mut self,
7428 _: &SelectToEndOfParagraph,
7429 cx: &mut ViewContext<Self>,
7430 ) {
7431 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7432 cx.propagate();
7433 return;
7434 }
7435
7436 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7437 s.move_heads_with(|map, head, _| {
7438 (
7439 movement::end_of_paragraph(map, head, 1),
7440 SelectionGoal::None,
7441 )
7442 });
7443 })
7444 }
7445
7446 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7447 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7448 cx.propagate();
7449 return;
7450 }
7451
7452 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7453 s.select_ranges(vec![0..0]);
7454 });
7455 }
7456
7457 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7458 let mut selection = self.selections.last::<Point>(cx);
7459 selection.set_head(Point::zero(), SelectionGoal::None);
7460
7461 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7462 s.select(vec![selection]);
7463 });
7464 }
7465
7466 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7467 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7468 cx.propagate();
7469 return;
7470 }
7471
7472 let cursor = self.buffer.read(cx).read(cx).len();
7473 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7474 s.select_ranges(vec![cursor..cursor])
7475 });
7476 }
7477
7478 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7479 self.nav_history = nav_history;
7480 }
7481
7482 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7483 self.nav_history.as_ref()
7484 }
7485
7486 fn push_to_nav_history(
7487 &mut self,
7488 cursor_anchor: Anchor,
7489 new_position: Option<Point>,
7490 cx: &mut ViewContext<Self>,
7491 ) {
7492 if let Some(nav_history) = self.nav_history.as_mut() {
7493 let buffer = self.buffer.read(cx).read(cx);
7494 let cursor_position = cursor_anchor.to_point(&buffer);
7495 let scroll_state = self.scroll_manager.anchor();
7496 let scroll_top_row = scroll_state.top_row(&buffer);
7497 drop(buffer);
7498
7499 if let Some(new_position) = new_position {
7500 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7501 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7502 return;
7503 }
7504 }
7505
7506 nav_history.push(
7507 Some(NavigationData {
7508 cursor_anchor,
7509 cursor_position,
7510 scroll_anchor: scroll_state,
7511 scroll_top_row,
7512 }),
7513 cx,
7514 );
7515 }
7516 }
7517
7518 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7519 let buffer = self.buffer.read(cx).snapshot(cx);
7520 let mut selection = self.selections.first::<usize>(cx);
7521 selection.set_head(buffer.len(), SelectionGoal::None);
7522 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7523 s.select(vec![selection]);
7524 });
7525 }
7526
7527 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7528 let end = self.buffer.read(cx).read(cx).len();
7529 self.change_selections(None, cx, |s| {
7530 s.select_ranges(vec![0..end]);
7531 });
7532 }
7533
7534 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7535 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7536 let mut selections = self.selections.all::<Point>(cx);
7537 let max_point = display_map.buffer_snapshot.max_point();
7538 for selection in &mut selections {
7539 let rows = selection.spanned_rows(true, &display_map);
7540 selection.start = Point::new(rows.start.0, 0);
7541 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7542 selection.reversed = false;
7543 }
7544 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7545 s.select(selections);
7546 });
7547 }
7548
7549 pub fn split_selection_into_lines(
7550 &mut self,
7551 _: &SplitSelectionIntoLines,
7552 cx: &mut ViewContext<Self>,
7553 ) {
7554 let mut to_unfold = Vec::new();
7555 let mut new_selection_ranges = Vec::new();
7556 {
7557 let selections = self.selections.all::<Point>(cx);
7558 let buffer = self.buffer.read(cx).read(cx);
7559 for selection in selections {
7560 for row in selection.start.row..selection.end.row {
7561 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7562 new_selection_ranges.push(cursor..cursor);
7563 }
7564 new_selection_ranges.push(selection.end..selection.end);
7565 to_unfold.push(selection.start..selection.end);
7566 }
7567 }
7568 self.unfold_ranges(to_unfold, true, true, cx);
7569 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7570 s.select_ranges(new_selection_ranges);
7571 });
7572 }
7573
7574 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7575 self.add_selection(true, cx);
7576 }
7577
7578 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7579 self.add_selection(false, cx);
7580 }
7581
7582 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7583 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7584 let mut selections = self.selections.all::<Point>(cx);
7585 let text_layout_details = self.text_layout_details(cx);
7586 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7587 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7588 let range = oldest_selection.display_range(&display_map).sorted();
7589
7590 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7591 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7592 let positions = start_x.min(end_x)..start_x.max(end_x);
7593
7594 selections.clear();
7595 let mut stack = Vec::new();
7596 for row in range.start.row().0..=range.end.row().0 {
7597 if let Some(selection) = self.selections.build_columnar_selection(
7598 &display_map,
7599 DisplayRow(row),
7600 &positions,
7601 oldest_selection.reversed,
7602 &text_layout_details,
7603 ) {
7604 stack.push(selection.id);
7605 selections.push(selection);
7606 }
7607 }
7608
7609 if above {
7610 stack.reverse();
7611 }
7612
7613 AddSelectionsState { above, stack }
7614 });
7615
7616 let last_added_selection = *state.stack.last().unwrap();
7617 let mut new_selections = Vec::new();
7618 if above == state.above {
7619 let end_row = if above {
7620 DisplayRow(0)
7621 } else {
7622 display_map.max_point().row()
7623 };
7624
7625 'outer: for selection in selections {
7626 if selection.id == last_added_selection {
7627 let range = selection.display_range(&display_map).sorted();
7628 debug_assert_eq!(range.start.row(), range.end.row());
7629 let mut row = range.start.row();
7630 let positions =
7631 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7632 px(start)..px(end)
7633 } else {
7634 let start_x =
7635 display_map.x_for_display_point(range.start, &text_layout_details);
7636 let end_x =
7637 display_map.x_for_display_point(range.end, &text_layout_details);
7638 start_x.min(end_x)..start_x.max(end_x)
7639 };
7640
7641 while row != end_row {
7642 if above {
7643 row.0 -= 1;
7644 } else {
7645 row.0 += 1;
7646 }
7647
7648 if let Some(new_selection) = self.selections.build_columnar_selection(
7649 &display_map,
7650 row,
7651 &positions,
7652 selection.reversed,
7653 &text_layout_details,
7654 ) {
7655 state.stack.push(new_selection.id);
7656 if above {
7657 new_selections.push(new_selection);
7658 new_selections.push(selection);
7659 } else {
7660 new_selections.push(selection);
7661 new_selections.push(new_selection);
7662 }
7663
7664 continue 'outer;
7665 }
7666 }
7667 }
7668
7669 new_selections.push(selection);
7670 }
7671 } else {
7672 new_selections = selections;
7673 new_selections.retain(|s| s.id != last_added_selection);
7674 state.stack.pop();
7675 }
7676
7677 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7678 s.select(new_selections);
7679 });
7680 if state.stack.len() > 1 {
7681 self.add_selections_state = Some(state);
7682 }
7683 }
7684
7685 pub fn select_next_match_internal(
7686 &mut self,
7687 display_map: &DisplaySnapshot,
7688 replace_newest: bool,
7689 autoscroll: Option<Autoscroll>,
7690 cx: &mut ViewContext<Self>,
7691 ) -> Result<()> {
7692 fn select_next_match_ranges(
7693 this: &mut Editor,
7694 range: Range<usize>,
7695 replace_newest: bool,
7696 auto_scroll: Option<Autoscroll>,
7697 cx: &mut ViewContext<Editor>,
7698 ) {
7699 this.unfold_ranges([range.clone()], false, true, cx);
7700 this.change_selections(auto_scroll, cx, |s| {
7701 if replace_newest {
7702 s.delete(s.newest_anchor().id);
7703 }
7704 s.insert_range(range.clone());
7705 });
7706 }
7707
7708 let buffer = &display_map.buffer_snapshot;
7709 let mut selections = self.selections.all::<usize>(cx);
7710 if let Some(mut select_next_state) = self.select_next_state.take() {
7711 let query = &select_next_state.query;
7712 if !select_next_state.done {
7713 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7714 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7715 let mut next_selected_range = None;
7716
7717 let bytes_after_last_selection =
7718 buffer.bytes_in_range(last_selection.end..buffer.len());
7719 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
7720 let query_matches = query
7721 .stream_find_iter(bytes_after_last_selection)
7722 .map(|result| (last_selection.end, result))
7723 .chain(
7724 query
7725 .stream_find_iter(bytes_before_first_selection)
7726 .map(|result| (0, result)),
7727 );
7728
7729 for (start_offset, query_match) in query_matches {
7730 let query_match = query_match.unwrap(); // can only fail due to I/O
7731 let offset_range =
7732 start_offset + query_match.start()..start_offset + query_match.end();
7733 let display_range = offset_range.start.to_display_point(&display_map)
7734 ..offset_range.end.to_display_point(&display_map);
7735
7736 if !select_next_state.wordwise
7737 || (!movement::is_inside_word(&display_map, display_range.start)
7738 && !movement::is_inside_word(&display_map, display_range.end))
7739 {
7740 // TODO: This is n^2, because we might check all the selections
7741 if !selections
7742 .iter()
7743 .any(|selection| selection.range().overlaps(&offset_range))
7744 {
7745 next_selected_range = Some(offset_range);
7746 break;
7747 }
7748 }
7749 }
7750
7751 if let Some(next_selected_range) = next_selected_range {
7752 select_next_match_ranges(
7753 self,
7754 next_selected_range,
7755 replace_newest,
7756 autoscroll,
7757 cx,
7758 );
7759 } else {
7760 select_next_state.done = true;
7761 }
7762 }
7763
7764 self.select_next_state = Some(select_next_state);
7765 } else {
7766 let mut only_carets = true;
7767 let mut same_text_selected = true;
7768 let mut selected_text = None;
7769
7770 let mut selections_iter = selections.iter().peekable();
7771 while let Some(selection) = selections_iter.next() {
7772 if selection.start != selection.end {
7773 only_carets = false;
7774 }
7775
7776 if same_text_selected {
7777 if selected_text.is_none() {
7778 selected_text =
7779 Some(buffer.text_for_range(selection.range()).collect::<String>());
7780 }
7781
7782 if let Some(next_selection) = selections_iter.peek() {
7783 if next_selection.range().len() == selection.range().len() {
7784 let next_selected_text = buffer
7785 .text_for_range(next_selection.range())
7786 .collect::<String>();
7787 if Some(next_selected_text) != selected_text {
7788 same_text_selected = false;
7789 selected_text = None;
7790 }
7791 } else {
7792 same_text_selected = false;
7793 selected_text = None;
7794 }
7795 }
7796 }
7797 }
7798
7799 if only_carets {
7800 for selection in &mut selections {
7801 let word_range = movement::surrounding_word(
7802 &display_map,
7803 selection.start.to_display_point(&display_map),
7804 );
7805 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
7806 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
7807 selection.goal = SelectionGoal::None;
7808 selection.reversed = false;
7809 select_next_match_ranges(
7810 self,
7811 selection.start..selection.end,
7812 replace_newest,
7813 autoscroll,
7814 cx,
7815 );
7816 }
7817
7818 if selections.len() == 1 {
7819 let selection = selections
7820 .last()
7821 .expect("ensured that there's only one selection");
7822 let query = buffer
7823 .text_for_range(selection.start..selection.end)
7824 .collect::<String>();
7825 let is_empty = query.is_empty();
7826 let select_state = SelectNextState {
7827 query: AhoCorasick::new(&[query])?,
7828 wordwise: true,
7829 done: is_empty,
7830 };
7831 self.select_next_state = Some(select_state);
7832 } else {
7833 self.select_next_state = None;
7834 }
7835 } else if let Some(selected_text) = selected_text {
7836 self.select_next_state = Some(SelectNextState {
7837 query: AhoCorasick::new(&[selected_text])?,
7838 wordwise: false,
7839 done: false,
7840 });
7841 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
7842 }
7843 }
7844 Ok(())
7845 }
7846
7847 pub fn select_all_matches(
7848 &mut self,
7849 _action: &SelectAllMatches,
7850 cx: &mut ViewContext<Self>,
7851 ) -> Result<()> {
7852 self.push_to_selection_history();
7853 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7854
7855 self.select_next_match_internal(&display_map, false, None, cx)?;
7856 let Some(select_next_state) = self.select_next_state.as_mut() else {
7857 return Ok(());
7858 };
7859 if select_next_state.done {
7860 return Ok(());
7861 }
7862
7863 let mut new_selections = self.selections.all::<usize>(cx);
7864
7865 let buffer = &display_map.buffer_snapshot;
7866 let query_matches = select_next_state
7867 .query
7868 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
7869
7870 for query_match in query_matches {
7871 let query_match = query_match.unwrap(); // can only fail due to I/O
7872 let offset_range = query_match.start()..query_match.end();
7873 let display_range = offset_range.start.to_display_point(&display_map)
7874 ..offset_range.end.to_display_point(&display_map);
7875
7876 if !select_next_state.wordwise
7877 || (!movement::is_inside_word(&display_map, display_range.start)
7878 && !movement::is_inside_word(&display_map, display_range.end))
7879 {
7880 self.selections.change_with(cx, |selections| {
7881 new_selections.push(Selection {
7882 id: selections.new_selection_id(),
7883 start: offset_range.start,
7884 end: offset_range.end,
7885 reversed: false,
7886 goal: SelectionGoal::None,
7887 });
7888 });
7889 }
7890 }
7891
7892 new_selections.sort_by_key(|selection| selection.start);
7893 let mut ix = 0;
7894 while ix + 1 < new_selections.len() {
7895 let current_selection = &new_selections[ix];
7896 let next_selection = &new_selections[ix + 1];
7897 if current_selection.range().overlaps(&next_selection.range()) {
7898 if current_selection.id < next_selection.id {
7899 new_selections.remove(ix + 1);
7900 } else {
7901 new_selections.remove(ix);
7902 }
7903 } else {
7904 ix += 1;
7905 }
7906 }
7907
7908 select_next_state.done = true;
7909 self.unfold_ranges(
7910 new_selections.iter().map(|selection| selection.range()),
7911 false,
7912 false,
7913 cx,
7914 );
7915 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
7916 selections.select(new_selections)
7917 });
7918
7919 Ok(())
7920 }
7921
7922 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
7923 self.push_to_selection_history();
7924 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7925 self.select_next_match_internal(
7926 &display_map,
7927 action.replace_newest,
7928 Some(Autoscroll::newest()),
7929 cx,
7930 )?;
7931 Ok(())
7932 }
7933
7934 pub fn select_previous(
7935 &mut self,
7936 action: &SelectPrevious,
7937 cx: &mut ViewContext<Self>,
7938 ) -> Result<()> {
7939 self.push_to_selection_history();
7940 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7941 let buffer = &display_map.buffer_snapshot;
7942 let mut selections = self.selections.all::<usize>(cx);
7943 if let Some(mut select_prev_state) = self.select_prev_state.take() {
7944 let query = &select_prev_state.query;
7945 if !select_prev_state.done {
7946 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7947 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7948 let mut next_selected_range = None;
7949 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
7950 let bytes_before_last_selection =
7951 buffer.reversed_bytes_in_range(0..last_selection.start);
7952 let bytes_after_first_selection =
7953 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
7954 let query_matches = query
7955 .stream_find_iter(bytes_before_last_selection)
7956 .map(|result| (last_selection.start, result))
7957 .chain(
7958 query
7959 .stream_find_iter(bytes_after_first_selection)
7960 .map(|result| (buffer.len(), result)),
7961 );
7962 for (end_offset, query_match) in query_matches {
7963 let query_match = query_match.unwrap(); // can only fail due to I/O
7964 let offset_range =
7965 end_offset - query_match.end()..end_offset - query_match.start();
7966 let display_range = offset_range.start.to_display_point(&display_map)
7967 ..offset_range.end.to_display_point(&display_map);
7968
7969 if !select_prev_state.wordwise
7970 || (!movement::is_inside_word(&display_map, display_range.start)
7971 && !movement::is_inside_word(&display_map, display_range.end))
7972 {
7973 next_selected_range = Some(offset_range);
7974 break;
7975 }
7976 }
7977
7978 if let Some(next_selected_range) = next_selected_range {
7979 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
7980 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
7981 if action.replace_newest {
7982 s.delete(s.newest_anchor().id);
7983 }
7984 s.insert_range(next_selected_range);
7985 });
7986 } else {
7987 select_prev_state.done = true;
7988 }
7989 }
7990
7991 self.select_prev_state = Some(select_prev_state);
7992 } else {
7993 let mut only_carets = true;
7994 let mut same_text_selected = true;
7995 let mut selected_text = None;
7996
7997 let mut selections_iter = selections.iter().peekable();
7998 while let Some(selection) = selections_iter.next() {
7999 if selection.start != selection.end {
8000 only_carets = false;
8001 }
8002
8003 if same_text_selected {
8004 if selected_text.is_none() {
8005 selected_text =
8006 Some(buffer.text_for_range(selection.range()).collect::<String>());
8007 }
8008
8009 if let Some(next_selection) = selections_iter.peek() {
8010 if next_selection.range().len() == selection.range().len() {
8011 let next_selected_text = buffer
8012 .text_for_range(next_selection.range())
8013 .collect::<String>();
8014 if Some(next_selected_text) != selected_text {
8015 same_text_selected = false;
8016 selected_text = None;
8017 }
8018 } else {
8019 same_text_selected = false;
8020 selected_text = None;
8021 }
8022 }
8023 }
8024 }
8025
8026 if only_carets {
8027 for selection in &mut selections {
8028 let word_range = movement::surrounding_word(
8029 &display_map,
8030 selection.start.to_display_point(&display_map),
8031 );
8032 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8033 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8034 selection.goal = SelectionGoal::None;
8035 selection.reversed = false;
8036 }
8037 if selections.len() == 1 {
8038 let selection = selections
8039 .last()
8040 .expect("ensured that there's only one selection");
8041 let query = buffer
8042 .text_for_range(selection.start..selection.end)
8043 .collect::<String>();
8044 let is_empty = query.is_empty();
8045 let select_state = SelectNextState {
8046 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8047 wordwise: true,
8048 done: is_empty,
8049 };
8050 self.select_prev_state = Some(select_state);
8051 } else {
8052 self.select_prev_state = None;
8053 }
8054
8055 self.unfold_ranges(
8056 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8057 false,
8058 true,
8059 cx,
8060 );
8061 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8062 s.select(selections);
8063 });
8064 } else if let Some(selected_text) = selected_text {
8065 self.select_prev_state = Some(SelectNextState {
8066 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8067 wordwise: false,
8068 done: false,
8069 });
8070 self.select_previous(action, cx)?;
8071 }
8072 }
8073 Ok(())
8074 }
8075
8076 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8077 let text_layout_details = &self.text_layout_details(cx);
8078 self.transact(cx, |this, cx| {
8079 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8080 let mut edits = Vec::new();
8081 let mut selection_edit_ranges = Vec::new();
8082 let mut last_toggled_row = None;
8083 let snapshot = this.buffer.read(cx).read(cx);
8084 let empty_str: Arc<str> = "".into();
8085 let mut suffixes_inserted = Vec::new();
8086
8087 fn comment_prefix_range(
8088 snapshot: &MultiBufferSnapshot,
8089 row: MultiBufferRow,
8090 comment_prefix: &str,
8091 comment_prefix_whitespace: &str,
8092 ) -> Range<Point> {
8093 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8094
8095 let mut line_bytes = snapshot
8096 .bytes_in_range(start..snapshot.max_point())
8097 .flatten()
8098 .copied();
8099
8100 // If this line currently begins with the line comment prefix, then record
8101 // the range containing the prefix.
8102 if line_bytes
8103 .by_ref()
8104 .take(comment_prefix.len())
8105 .eq(comment_prefix.bytes())
8106 {
8107 // Include any whitespace that matches the comment prefix.
8108 let matching_whitespace_len = line_bytes
8109 .zip(comment_prefix_whitespace.bytes())
8110 .take_while(|(a, b)| a == b)
8111 .count() as u32;
8112 let end = Point::new(
8113 start.row,
8114 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8115 );
8116 start..end
8117 } else {
8118 start..start
8119 }
8120 }
8121
8122 fn comment_suffix_range(
8123 snapshot: &MultiBufferSnapshot,
8124 row: MultiBufferRow,
8125 comment_suffix: &str,
8126 comment_suffix_has_leading_space: bool,
8127 ) -> Range<Point> {
8128 let end = Point::new(row.0, snapshot.line_len(row));
8129 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8130
8131 let mut line_end_bytes = snapshot
8132 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8133 .flatten()
8134 .copied();
8135
8136 let leading_space_len = if suffix_start_column > 0
8137 && line_end_bytes.next() == Some(b' ')
8138 && comment_suffix_has_leading_space
8139 {
8140 1
8141 } else {
8142 0
8143 };
8144
8145 // If this line currently begins with the line comment prefix, then record
8146 // the range containing the prefix.
8147 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8148 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8149 start..end
8150 } else {
8151 end..end
8152 }
8153 }
8154
8155 // TODO: Handle selections that cross excerpts
8156 for selection in &mut selections {
8157 let start_column = snapshot
8158 .indent_size_for_line(MultiBufferRow(selection.start.row))
8159 .len;
8160 let language = if let Some(language) =
8161 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8162 {
8163 language
8164 } else {
8165 continue;
8166 };
8167
8168 selection_edit_ranges.clear();
8169
8170 // If multiple selections contain a given row, avoid processing that
8171 // row more than once.
8172 let mut start_row = MultiBufferRow(selection.start.row);
8173 if last_toggled_row == Some(start_row) {
8174 start_row = start_row.next_row();
8175 }
8176 let end_row =
8177 if selection.end.row > selection.start.row && selection.end.column == 0 {
8178 MultiBufferRow(selection.end.row - 1)
8179 } else {
8180 MultiBufferRow(selection.end.row)
8181 };
8182 last_toggled_row = Some(end_row);
8183
8184 if start_row > end_row {
8185 continue;
8186 }
8187
8188 // If the language has line comments, toggle those.
8189 let full_comment_prefixes = language.line_comment_prefixes();
8190 if !full_comment_prefixes.is_empty() {
8191 let first_prefix = full_comment_prefixes
8192 .first()
8193 .expect("prefixes is non-empty");
8194 let prefix_trimmed_lengths = full_comment_prefixes
8195 .iter()
8196 .map(|p| p.trim_end_matches(' ').len())
8197 .collect::<SmallVec<[usize; 4]>>();
8198
8199 let mut all_selection_lines_are_comments = true;
8200
8201 for row in start_row.0..=end_row.0 {
8202 let row = MultiBufferRow(row);
8203 if start_row < end_row && snapshot.is_line_blank(row) {
8204 continue;
8205 }
8206
8207 let prefix_range = full_comment_prefixes
8208 .iter()
8209 .zip(prefix_trimmed_lengths.iter().copied())
8210 .map(|(prefix, trimmed_prefix_len)| {
8211 comment_prefix_range(
8212 snapshot.deref(),
8213 row,
8214 &prefix[..trimmed_prefix_len],
8215 &prefix[trimmed_prefix_len..],
8216 )
8217 })
8218 .max_by_key(|range| range.end.column - range.start.column)
8219 .expect("prefixes is non-empty");
8220
8221 if prefix_range.is_empty() {
8222 all_selection_lines_are_comments = false;
8223 }
8224
8225 selection_edit_ranges.push(prefix_range);
8226 }
8227
8228 if all_selection_lines_are_comments {
8229 edits.extend(
8230 selection_edit_ranges
8231 .iter()
8232 .cloned()
8233 .map(|range| (range, empty_str.clone())),
8234 );
8235 } else {
8236 let min_column = selection_edit_ranges
8237 .iter()
8238 .map(|range| range.start.column)
8239 .min()
8240 .unwrap_or(0);
8241 edits.extend(selection_edit_ranges.iter().map(|range| {
8242 let position = Point::new(range.start.row, min_column);
8243 (position..position, first_prefix.clone())
8244 }));
8245 }
8246 } else if let Some((full_comment_prefix, comment_suffix)) =
8247 language.block_comment_delimiters()
8248 {
8249 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8250 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8251 let prefix_range = comment_prefix_range(
8252 snapshot.deref(),
8253 start_row,
8254 comment_prefix,
8255 comment_prefix_whitespace,
8256 );
8257 let suffix_range = comment_suffix_range(
8258 snapshot.deref(),
8259 end_row,
8260 comment_suffix.trim_start_matches(' '),
8261 comment_suffix.starts_with(' '),
8262 );
8263
8264 if prefix_range.is_empty() || suffix_range.is_empty() {
8265 edits.push((
8266 prefix_range.start..prefix_range.start,
8267 full_comment_prefix.clone(),
8268 ));
8269 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8270 suffixes_inserted.push((end_row, comment_suffix.len()));
8271 } else {
8272 edits.push((prefix_range, empty_str.clone()));
8273 edits.push((suffix_range, empty_str.clone()));
8274 }
8275 } else {
8276 continue;
8277 }
8278 }
8279
8280 drop(snapshot);
8281 this.buffer.update(cx, |buffer, cx| {
8282 buffer.edit(edits, None, cx);
8283 });
8284
8285 // Adjust selections so that they end before any comment suffixes that
8286 // were inserted.
8287 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8288 let mut selections = this.selections.all::<Point>(cx);
8289 let snapshot = this.buffer.read(cx).read(cx);
8290 for selection in &mut selections {
8291 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8292 match row.cmp(&MultiBufferRow(selection.end.row)) {
8293 Ordering::Less => {
8294 suffixes_inserted.next();
8295 continue;
8296 }
8297 Ordering::Greater => break,
8298 Ordering::Equal => {
8299 if selection.end.column == snapshot.line_len(row) {
8300 if selection.is_empty() {
8301 selection.start.column -= suffix_len as u32;
8302 }
8303 selection.end.column -= suffix_len as u32;
8304 }
8305 break;
8306 }
8307 }
8308 }
8309 }
8310
8311 drop(snapshot);
8312 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8313
8314 let selections = this.selections.all::<Point>(cx);
8315 let selections_on_single_row = selections.windows(2).all(|selections| {
8316 selections[0].start.row == selections[1].start.row
8317 && selections[0].end.row == selections[1].end.row
8318 && selections[0].start.row == selections[0].end.row
8319 });
8320 let selections_selecting = selections
8321 .iter()
8322 .any(|selection| selection.start != selection.end);
8323 let advance_downwards = action.advance_downwards
8324 && selections_on_single_row
8325 && !selections_selecting
8326 && !matches!(this.mode, EditorMode::SingleLine { .. });
8327
8328 if advance_downwards {
8329 let snapshot = this.buffer.read(cx).snapshot(cx);
8330
8331 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8332 s.move_cursors_with(|display_snapshot, display_point, _| {
8333 let mut point = display_point.to_point(display_snapshot);
8334 point.row += 1;
8335 point = snapshot.clip_point(point, Bias::Left);
8336 let display_point = point.to_display_point(display_snapshot);
8337 let goal = SelectionGoal::HorizontalPosition(
8338 display_snapshot
8339 .x_for_display_point(display_point, &text_layout_details)
8340 .into(),
8341 );
8342 (display_point, goal)
8343 })
8344 });
8345 }
8346 });
8347 }
8348
8349 pub fn select_enclosing_symbol(
8350 &mut self,
8351 _: &SelectEnclosingSymbol,
8352 cx: &mut ViewContext<Self>,
8353 ) {
8354 let buffer = self.buffer.read(cx).snapshot(cx);
8355 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8356
8357 fn update_selection(
8358 selection: &Selection<usize>,
8359 buffer_snap: &MultiBufferSnapshot,
8360 ) -> Option<Selection<usize>> {
8361 let cursor = selection.head();
8362 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8363 for symbol in symbols.iter().rev() {
8364 let start = symbol.range.start.to_offset(&buffer_snap);
8365 let end = symbol.range.end.to_offset(&buffer_snap);
8366 let new_range = start..end;
8367 if start < selection.start || end > selection.end {
8368 return Some(Selection {
8369 id: selection.id,
8370 start: new_range.start,
8371 end: new_range.end,
8372 goal: SelectionGoal::None,
8373 reversed: selection.reversed,
8374 });
8375 }
8376 }
8377 None
8378 }
8379
8380 let mut selected_larger_symbol = false;
8381 let new_selections = old_selections
8382 .iter()
8383 .map(|selection| match update_selection(selection, &buffer) {
8384 Some(new_selection) => {
8385 if new_selection.range() != selection.range() {
8386 selected_larger_symbol = true;
8387 }
8388 new_selection
8389 }
8390 None => selection.clone(),
8391 })
8392 .collect::<Vec<_>>();
8393
8394 if selected_larger_symbol {
8395 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8396 s.select(new_selections);
8397 });
8398 }
8399 }
8400
8401 pub fn select_larger_syntax_node(
8402 &mut self,
8403 _: &SelectLargerSyntaxNode,
8404 cx: &mut ViewContext<Self>,
8405 ) {
8406 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8407 let buffer = self.buffer.read(cx).snapshot(cx);
8408 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8409
8410 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8411 let mut selected_larger_node = false;
8412 let new_selections = old_selections
8413 .iter()
8414 .map(|selection| {
8415 let old_range = selection.start..selection.end;
8416 let mut new_range = old_range.clone();
8417 while let Some(containing_range) =
8418 buffer.range_for_syntax_ancestor(new_range.clone())
8419 {
8420 new_range = containing_range;
8421 if !display_map.intersects_fold(new_range.start)
8422 && !display_map.intersects_fold(new_range.end)
8423 {
8424 break;
8425 }
8426 }
8427
8428 selected_larger_node |= new_range != old_range;
8429 Selection {
8430 id: selection.id,
8431 start: new_range.start,
8432 end: new_range.end,
8433 goal: SelectionGoal::None,
8434 reversed: selection.reversed,
8435 }
8436 })
8437 .collect::<Vec<_>>();
8438
8439 if selected_larger_node {
8440 stack.push(old_selections);
8441 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8442 s.select(new_selections);
8443 });
8444 }
8445 self.select_larger_syntax_node_stack = stack;
8446 }
8447
8448 pub fn select_smaller_syntax_node(
8449 &mut self,
8450 _: &SelectSmallerSyntaxNode,
8451 cx: &mut ViewContext<Self>,
8452 ) {
8453 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8454 if let Some(selections) = stack.pop() {
8455 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8456 s.select(selections.to_vec());
8457 });
8458 }
8459 self.select_larger_syntax_node_stack = stack;
8460 }
8461
8462 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8463 if !EditorSettings::get_global(cx).gutter.runnables {
8464 self.clear_tasks();
8465 return Task::ready(());
8466 }
8467 let project = self.project.clone();
8468 cx.spawn(|this, mut cx| async move {
8469 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8470 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8471 }) else {
8472 return;
8473 };
8474
8475 let Some(project) = project else {
8476 return;
8477 };
8478
8479 let hide_runnables = project
8480 .update(&mut cx, |project, cx| {
8481 // Do not display any test indicators in non-dev server remote projects.
8482 project.is_remote() && project.ssh_connection_string(cx).is_none()
8483 })
8484 .unwrap_or(true);
8485 if hide_runnables {
8486 return;
8487 }
8488 let new_rows =
8489 cx.background_executor()
8490 .spawn({
8491 let snapshot = display_snapshot.clone();
8492 async move {
8493 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8494 }
8495 })
8496 .await;
8497 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8498
8499 this.update(&mut cx, |this, _| {
8500 this.clear_tasks();
8501 for (key, value) in rows {
8502 this.insert_tasks(key, value);
8503 }
8504 })
8505 .ok();
8506 })
8507 }
8508 fn fetch_runnable_ranges(
8509 snapshot: &DisplaySnapshot,
8510 range: Range<Anchor>,
8511 ) -> Vec<language::RunnableRange> {
8512 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8513 }
8514
8515 fn runnable_rows(
8516 project: Model<Project>,
8517 snapshot: DisplaySnapshot,
8518 runnable_ranges: Vec<RunnableRange>,
8519 mut cx: AsyncWindowContext,
8520 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8521 runnable_ranges
8522 .into_iter()
8523 .filter_map(|mut runnable| {
8524 let tasks = cx
8525 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8526 .ok()?;
8527 if tasks.is_empty() {
8528 return None;
8529 }
8530
8531 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8532
8533 let row = snapshot
8534 .buffer_snapshot
8535 .buffer_line_for_row(MultiBufferRow(point.row))?
8536 .1
8537 .start
8538 .row;
8539
8540 let context_range =
8541 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8542 Some((
8543 (runnable.buffer_id, row),
8544 RunnableTasks {
8545 templates: tasks,
8546 offset: MultiBufferOffset(runnable.run_range.start),
8547 context_range,
8548 column: point.column,
8549 extra_variables: runnable.extra_captures,
8550 },
8551 ))
8552 })
8553 .collect()
8554 }
8555
8556 fn templates_with_tags(
8557 project: &Model<Project>,
8558 runnable: &mut Runnable,
8559 cx: &WindowContext<'_>,
8560 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8561 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8562 let (worktree_id, file) = project
8563 .buffer_for_id(runnable.buffer, cx)
8564 .and_then(|buffer| buffer.read(cx).file())
8565 .map(|file| (WorktreeId::from_usize(file.worktree_id()), file.clone()))
8566 .unzip();
8567
8568 (project.task_inventory().clone(), worktree_id, file)
8569 });
8570
8571 let inventory = inventory.read(cx);
8572 let tags = mem::take(&mut runnable.tags);
8573 let mut tags: Vec<_> = tags
8574 .into_iter()
8575 .flat_map(|tag| {
8576 let tag = tag.0.clone();
8577 inventory
8578 .list_tasks(
8579 file.clone(),
8580 Some(runnable.language.clone()),
8581 worktree_id,
8582 cx,
8583 )
8584 .into_iter()
8585 .filter(move |(_, template)| {
8586 template.tags.iter().any(|source_tag| source_tag == &tag)
8587 })
8588 })
8589 .sorted_by_key(|(kind, _)| kind.to_owned())
8590 .collect();
8591 if let Some((leading_tag_source, _)) = tags.first() {
8592 // Strongest source wins; if we have worktree tag binding, prefer that to
8593 // global and language bindings;
8594 // if we have a global binding, prefer that to language binding.
8595 let first_mismatch = tags
8596 .iter()
8597 .position(|(tag_source, _)| tag_source != leading_tag_source);
8598 if let Some(index) = first_mismatch {
8599 tags.truncate(index);
8600 }
8601 }
8602
8603 tags
8604 }
8605
8606 pub fn move_to_enclosing_bracket(
8607 &mut self,
8608 _: &MoveToEnclosingBracket,
8609 cx: &mut ViewContext<Self>,
8610 ) {
8611 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8612 s.move_offsets_with(|snapshot, selection| {
8613 let Some(enclosing_bracket_ranges) =
8614 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
8615 else {
8616 return;
8617 };
8618
8619 let mut best_length = usize::MAX;
8620 let mut best_inside = false;
8621 let mut best_in_bracket_range = false;
8622 let mut best_destination = None;
8623 for (open, close) in enclosing_bracket_ranges {
8624 let close = close.to_inclusive();
8625 let length = close.end() - open.start;
8626 let inside = selection.start >= open.end && selection.end <= *close.start();
8627 let in_bracket_range = open.to_inclusive().contains(&selection.head())
8628 || close.contains(&selection.head());
8629
8630 // If best is next to a bracket and current isn't, skip
8631 if !in_bracket_range && best_in_bracket_range {
8632 continue;
8633 }
8634
8635 // Prefer smaller lengths unless best is inside and current isn't
8636 if length > best_length && (best_inside || !inside) {
8637 continue;
8638 }
8639
8640 best_length = length;
8641 best_inside = inside;
8642 best_in_bracket_range = in_bracket_range;
8643 best_destination = Some(
8644 if close.contains(&selection.start) && close.contains(&selection.end) {
8645 if inside {
8646 open.end
8647 } else {
8648 open.start
8649 }
8650 } else {
8651 if inside {
8652 *close.start()
8653 } else {
8654 *close.end()
8655 }
8656 },
8657 );
8658 }
8659
8660 if let Some(destination) = best_destination {
8661 selection.collapse_to(destination, SelectionGoal::None);
8662 }
8663 })
8664 });
8665 }
8666
8667 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
8668 self.end_selection(cx);
8669 self.selection_history.mode = SelectionHistoryMode::Undoing;
8670 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
8671 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8672 self.select_next_state = entry.select_next_state;
8673 self.select_prev_state = entry.select_prev_state;
8674 self.add_selections_state = entry.add_selections_state;
8675 self.request_autoscroll(Autoscroll::newest(), cx);
8676 }
8677 self.selection_history.mode = SelectionHistoryMode::Normal;
8678 }
8679
8680 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
8681 self.end_selection(cx);
8682 self.selection_history.mode = SelectionHistoryMode::Redoing;
8683 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
8684 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8685 self.select_next_state = entry.select_next_state;
8686 self.select_prev_state = entry.select_prev_state;
8687 self.add_selections_state = entry.add_selections_state;
8688 self.request_autoscroll(Autoscroll::newest(), cx);
8689 }
8690 self.selection_history.mode = SelectionHistoryMode::Normal;
8691 }
8692
8693 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
8694 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
8695 }
8696
8697 pub fn expand_excerpts_down(
8698 &mut self,
8699 action: &ExpandExcerptsDown,
8700 cx: &mut ViewContext<Self>,
8701 ) {
8702 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
8703 }
8704
8705 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
8706 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
8707 }
8708
8709 pub fn expand_excerpts_for_direction(
8710 &mut self,
8711 lines: u32,
8712 direction: ExpandExcerptDirection,
8713 cx: &mut ViewContext<Self>,
8714 ) {
8715 let selections = self.selections.disjoint_anchors();
8716
8717 let lines = if lines == 0 {
8718 EditorSettings::get_global(cx).expand_excerpt_lines
8719 } else {
8720 lines
8721 };
8722
8723 self.buffer.update(cx, |buffer, cx| {
8724 buffer.expand_excerpts(
8725 selections
8726 .into_iter()
8727 .map(|selection| selection.head().excerpt_id)
8728 .dedup(),
8729 lines,
8730 direction,
8731 cx,
8732 )
8733 })
8734 }
8735
8736 pub fn expand_excerpt(
8737 &mut self,
8738 excerpt: ExcerptId,
8739 direction: ExpandExcerptDirection,
8740 cx: &mut ViewContext<Self>,
8741 ) {
8742 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
8743 self.buffer.update(cx, |buffer, cx| {
8744 buffer.expand_excerpts([excerpt], lines, direction, cx)
8745 })
8746 }
8747
8748 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
8749 self.go_to_diagnostic_impl(Direction::Next, cx)
8750 }
8751
8752 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
8753 self.go_to_diagnostic_impl(Direction::Prev, cx)
8754 }
8755
8756 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
8757 let buffer = self.buffer.read(cx).snapshot(cx);
8758 let selection = self.selections.newest::<usize>(cx);
8759
8760 // If there is an active Diagnostic Popover jump to its diagnostic instead.
8761 if direction == Direction::Next {
8762 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
8763 let (group_id, jump_to) = popover.activation_info();
8764 if self.activate_diagnostics(group_id, cx) {
8765 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8766 let mut new_selection = s.newest_anchor().clone();
8767 new_selection.collapse_to(jump_to, SelectionGoal::None);
8768 s.select_anchors(vec![new_selection.clone()]);
8769 });
8770 }
8771 return;
8772 }
8773 }
8774
8775 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
8776 active_diagnostics
8777 .primary_range
8778 .to_offset(&buffer)
8779 .to_inclusive()
8780 });
8781 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
8782 if active_primary_range.contains(&selection.head()) {
8783 *active_primary_range.start()
8784 } else {
8785 selection.head()
8786 }
8787 } else {
8788 selection.head()
8789 };
8790 let snapshot = self.snapshot(cx);
8791 loop {
8792 let diagnostics = if direction == Direction::Prev {
8793 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
8794 } else {
8795 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
8796 }
8797 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
8798 let group = diagnostics
8799 // relies on diagnostics_in_range to return diagnostics with the same starting range to
8800 // be sorted in a stable way
8801 // skip until we are at current active diagnostic, if it exists
8802 .skip_while(|entry| {
8803 (match direction {
8804 Direction::Prev => entry.range.start >= search_start,
8805 Direction::Next => entry.range.start <= search_start,
8806 }) && self
8807 .active_diagnostics
8808 .as_ref()
8809 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
8810 })
8811 .find_map(|entry| {
8812 if entry.diagnostic.is_primary
8813 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
8814 && !entry.range.is_empty()
8815 // if we match with the active diagnostic, skip it
8816 && Some(entry.diagnostic.group_id)
8817 != self.active_diagnostics.as_ref().map(|d| d.group_id)
8818 {
8819 Some((entry.range, entry.diagnostic.group_id))
8820 } else {
8821 None
8822 }
8823 });
8824
8825 if let Some((primary_range, group_id)) = group {
8826 if self.activate_diagnostics(group_id, cx) {
8827 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8828 s.select(vec![Selection {
8829 id: selection.id,
8830 start: primary_range.start,
8831 end: primary_range.start,
8832 reversed: false,
8833 goal: SelectionGoal::None,
8834 }]);
8835 });
8836 }
8837 break;
8838 } else {
8839 // Cycle around to the start of the buffer, potentially moving back to the start of
8840 // the currently active diagnostic.
8841 active_primary_range.take();
8842 if direction == Direction::Prev {
8843 if search_start == buffer.len() {
8844 break;
8845 } else {
8846 search_start = buffer.len();
8847 }
8848 } else if search_start == 0 {
8849 break;
8850 } else {
8851 search_start = 0;
8852 }
8853 }
8854 }
8855 }
8856
8857 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
8858 let snapshot = self
8859 .display_map
8860 .update(cx, |display_map, cx| display_map.snapshot(cx));
8861 let selection = self.selections.newest::<Point>(cx);
8862
8863 if !self.seek_in_direction(
8864 &snapshot,
8865 selection.head(),
8866 false,
8867 snapshot.buffer_snapshot.git_diff_hunks_in_range(
8868 MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
8869 ),
8870 cx,
8871 ) {
8872 let wrapped_point = Point::zero();
8873 self.seek_in_direction(
8874 &snapshot,
8875 wrapped_point,
8876 true,
8877 snapshot.buffer_snapshot.git_diff_hunks_in_range(
8878 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
8879 ),
8880 cx,
8881 );
8882 }
8883 }
8884
8885 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, 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_rev(
8896 MultiBufferRow(0)..MultiBufferRow(selection.head().row),
8897 ),
8898 cx,
8899 ) {
8900 let wrapped_point = snapshot.buffer_snapshot.max_point();
8901 self.seek_in_direction(
8902 &snapshot,
8903 wrapped_point,
8904 true,
8905 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
8906 MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
8907 ),
8908 cx,
8909 );
8910 }
8911 }
8912
8913 fn seek_in_direction(
8914 &mut self,
8915 snapshot: &DisplaySnapshot,
8916 initial_point: Point,
8917 is_wrapped: bool,
8918 hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
8919 cx: &mut ViewContext<Editor>,
8920 ) -> bool {
8921 let display_point = initial_point.to_display_point(snapshot);
8922 let mut hunks = hunks
8923 .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
8924 .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
8925 .dedup();
8926
8927 if let Some(hunk) = hunks.next() {
8928 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8929 let row = hunk.start_display_row();
8930 let point = DisplayPoint::new(row, 0);
8931 s.select_display_ranges([point..point]);
8932 });
8933
8934 true
8935 } else {
8936 false
8937 }
8938 }
8939
8940 pub fn go_to_definition(
8941 &mut self,
8942 _: &GoToDefinition,
8943 cx: &mut ViewContext<Self>,
8944 ) -> Task<Result<bool>> {
8945 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx)
8946 }
8947
8948 pub fn go_to_implementation(
8949 &mut self,
8950 _: &GoToImplementation,
8951 cx: &mut ViewContext<Self>,
8952 ) -> Task<Result<bool>> {
8953 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
8954 }
8955
8956 pub fn go_to_implementation_split(
8957 &mut self,
8958 _: &GoToImplementationSplit,
8959 cx: &mut ViewContext<Self>,
8960 ) -> Task<Result<bool>> {
8961 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
8962 }
8963
8964 pub fn go_to_type_definition(
8965 &mut self,
8966 _: &GoToTypeDefinition,
8967 cx: &mut ViewContext<Self>,
8968 ) -> Task<Result<bool>> {
8969 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
8970 }
8971
8972 pub fn go_to_definition_split(
8973 &mut self,
8974 _: &GoToDefinitionSplit,
8975 cx: &mut ViewContext<Self>,
8976 ) -> Task<Result<bool>> {
8977 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
8978 }
8979
8980 pub fn go_to_type_definition_split(
8981 &mut self,
8982 _: &GoToTypeDefinitionSplit,
8983 cx: &mut ViewContext<Self>,
8984 ) -> Task<Result<bool>> {
8985 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
8986 }
8987
8988 fn go_to_definition_of_kind(
8989 &mut self,
8990 kind: GotoDefinitionKind,
8991 split: bool,
8992 cx: &mut ViewContext<Self>,
8993 ) -> Task<Result<bool>> {
8994 let Some(workspace) = self.workspace() else {
8995 return Task::ready(Ok(false));
8996 };
8997 let buffer = self.buffer.read(cx);
8998 let head = self.selections.newest::<usize>(cx).head();
8999 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9000 text_anchor
9001 } else {
9002 return Task::ready(Ok(false));
9003 };
9004
9005 let project = workspace.read(cx).project().clone();
9006 let definitions = project.update(cx, |project, cx| match kind {
9007 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
9008 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
9009 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
9010 });
9011
9012 cx.spawn(|editor, mut cx| async move {
9013 let definitions = definitions.await?;
9014 let navigated = editor
9015 .update(&mut cx, |editor, cx| {
9016 editor.navigate_to_hover_links(
9017 Some(kind),
9018 definitions
9019 .into_iter()
9020 .filter(|location| {
9021 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9022 })
9023 .map(HoverLink::Text)
9024 .collect::<Vec<_>>(),
9025 split,
9026 cx,
9027 )
9028 })?
9029 .await?;
9030 anyhow::Ok(navigated)
9031 })
9032 }
9033
9034 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9035 let position = self.selections.newest_anchor().head();
9036 let Some((buffer, buffer_position)) =
9037 self.buffer.read(cx).text_anchor_for_position(position, cx)
9038 else {
9039 return;
9040 };
9041
9042 cx.spawn(|editor, mut cx| async move {
9043 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9044 editor.update(&mut cx, |_, cx| {
9045 cx.open_url(&url);
9046 })
9047 } else {
9048 Ok(())
9049 }
9050 })
9051 .detach();
9052 }
9053
9054 pub(crate) fn navigate_to_hover_links(
9055 &mut self,
9056 kind: Option<GotoDefinitionKind>,
9057 mut definitions: Vec<HoverLink>,
9058 split: bool,
9059 cx: &mut ViewContext<Editor>,
9060 ) -> Task<Result<bool>> {
9061 // If there is one definition, just open it directly
9062 if definitions.len() == 1 {
9063 let definition = definitions.pop().unwrap();
9064 let target_task = match definition {
9065 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9066 HoverLink::InlayHint(lsp_location, server_id) => {
9067 self.compute_target_location(lsp_location, server_id, cx)
9068 }
9069 HoverLink::Url(url) => {
9070 cx.open_url(&url);
9071 Task::ready(Ok(None))
9072 }
9073 };
9074 cx.spawn(|editor, mut cx| async move {
9075 let target = target_task.await.context("target resolution task")?;
9076 if let Some(target) = target {
9077 editor.update(&mut cx, |editor, cx| {
9078 let Some(workspace) = editor.workspace() else {
9079 return false;
9080 };
9081 let pane = workspace.read(cx).active_pane().clone();
9082
9083 let range = target.range.to_offset(target.buffer.read(cx));
9084 let range = editor.range_for_match(&range);
9085
9086 /// If select range has more than one line, we
9087 /// just point the cursor to range.start.
9088 fn check_multiline_range(
9089 buffer: &Buffer,
9090 range: Range<usize>,
9091 ) -> Range<usize> {
9092 if buffer.offset_to_point(range.start).row
9093 == buffer.offset_to_point(range.end).row
9094 {
9095 range
9096 } else {
9097 range.start..range.start
9098 }
9099 }
9100
9101 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9102 let buffer = target.buffer.read(cx);
9103 let range = check_multiline_range(buffer, range);
9104 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
9105 s.select_ranges([range]);
9106 });
9107 } else {
9108 cx.window_context().defer(move |cx| {
9109 let target_editor: View<Self> =
9110 workspace.update(cx, |workspace, cx| {
9111 let pane = if split {
9112 workspace.adjacent_pane(cx)
9113 } else {
9114 workspace.active_pane().clone()
9115 };
9116
9117 workspace.open_project_item(
9118 pane,
9119 target.buffer.clone(),
9120 true,
9121 true,
9122 cx,
9123 )
9124 });
9125 target_editor.update(cx, |target_editor, cx| {
9126 // When selecting a definition in a different buffer, disable the nav history
9127 // to avoid creating a history entry at the previous cursor location.
9128 pane.update(cx, |pane, _| pane.disable_history());
9129 let buffer = target.buffer.read(cx);
9130 let range = check_multiline_range(buffer, range);
9131 target_editor.change_selections(
9132 Some(Autoscroll::focused()),
9133 cx,
9134 |s| {
9135 s.select_ranges([range]);
9136 },
9137 );
9138 pane.update(cx, |pane, _| pane.enable_history());
9139 });
9140 });
9141 }
9142 true
9143 })
9144 } else {
9145 Ok(false)
9146 }
9147 })
9148 } else if !definitions.is_empty() {
9149 let replica_id = self.replica_id(cx);
9150 cx.spawn(|editor, mut cx| async move {
9151 let (title, location_tasks, workspace) = editor
9152 .update(&mut cx, |editor, cx| {
9153 let tab_kind = match kind {
9154 Some(GotoDefinitionKind::Implementation) => "Implementations",
9155 _ => "Definitions",
9156 };
9157 let title = definitions
9158 .iter()
9159 .find_map(|definition| match definition {
9160 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9161 let buffer = origin.buffer.read(cx);
9162 format!(
9163 "{} for {}",
9164 tab_kind,
9165 buffer
9166 .text_for_range(origin.range.clone())
9167 .collect::<String>()
9168 )
9169 }),
9170 HoverLink::InlayHint(_, _) => None,
9171 HoverLink::Url(_) => None,
9172 })
9173 .unwrap_or(tab_kind.to_string());
9174 let location_tasks = definitions
9175 .into_iter()
9176 .map(|definition| match definition {
9177 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9178 HoverLink::InlayHint(lsp_location, server_id) => {
9179 editor.compute_target_location(lsp_location, server_id, cx)
9180 }
9181 HoverLink::Url(_) => Task::ready(Ok(None)),
9182 })
9183 .collect::<Vec<_>>();
9184 (title, location_tasks, editor.workspace().clone())
9185 })
9186 .context("location tasks preparation")?;
9187
9188 let locations = futures::future::join_all(location_tasks)
9189 .await
9190 .into_iter()
9191 .filter_map(|location| location.transpose())
9192 .collect::<Result<_>>()
9193 .context("location tasks")?;
9194
9195 let Some(workspace) = workspace else {
9196 return Ok(false);
9197 };
9198 let opened = workspace
9199 .update(&mut cx, |workspace, cx| {
9200 Self::open_locations_in_multibuffer(
9201 workspace, locations, replica_id, title, split, cx,
9202 )
9203 })
9204 .ok();
9205
9206 anyhow::Ok(opened.is_some())
9207 })
9208 } else {
9209 Task::ready(Ok(false))
9210 }
9211 }
9212
9213 fn compute_target_location(
9214 &self,
9215 lsp_location: lsp::Location,
9216 server_id: LanguageServerId,
9217 cx: &mut ViewContext<Editor>,
9218 ) -> Task<anyhow::Result<Option<Location>>> {
9219 let Some(project) = self.project.clone() else {
9220 return Task::Ready(Some(Ok(None)));
9221 };
9222
9223 cx.spawn(move |editor, mut cx| async move {
9224 let location_task = editor.update(&mut cx, |editor, cx| {
9225 project.update(cx, |project, cx| {
9226 let language_server_name =
9227 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9228 project
9229 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9230 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9231 });
9232 language_server_name.map(|language_server_name| {
9233 project.open_local_buffer_via_lsp(
9234 lsp_location.uri.clone(),
9235 server_id,
9236 language_server_name,
9237 cx,
9238 )
9239 })
9240 })
9241 })?;
9242 let location = match location_task {
9243 Some(task) => Some({
9244 let target_buffer_handle = task.await.context("open local buffer")?;
9245 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9246 let target_start = target_buffer
9247 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9248 let target_end = target_buffer
9249 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9250 target_buffer.anchor_after(target_start)
9251 ..target_buffer.anchor_before(target_end)
9252 })?;
9253 Location {
9254 buffer: target_buffer_handle,
9255 range,
9256 }
9257 }),
9258 None => None,
9259 };
9260 Ok(location)
9261 })
9262 }
9263
9264 pub fn find_all_references(
9265 &mut self,
9266 _: &FindAllReferences,
9267 cx: &mut ViewContext<Self>,
9268 ) -> Option<Task<Result<()>>> {
9269 let multi_buffer = self.buffer.read(cx);
9270 let selection = self.selections.newest::<usize>(cx);
9271 let head = selection.head();
9272
9273 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9274 let head_anchor = multi_buffer_snapshot.anchor_at(
9275 head,
9276 if head < selection.tail() {
9277 Bias::Right
9278 } else {
9279 Bias::Left
9280 },
9281 );
9282
9283 match self
9284 .find_all_references_task_sources
9285 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9286 {
9287 Ok(_) => {
9288 log::info!(
9289 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9290 );
9291 return None;
9292 }
9293 Err(i) => {
9294 self.find_all_references_task_sources.insert(i, head_anchor);
9295 }
9296 }
9297
9298 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9299 let replica_id = self.replica_id(cx);
9300 let workspace = self.workspace()?;
9301 let project = workspace.read(cx).project().clone();
9302 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9303 Some(cx.spawn(|editor, mut cx| async move {
9304 let _cleanup = defer({
9305 let mut cx = cx.clone();
9306 move || {
9307 let _ = editor.update(&mut cx, |editor, _| {
9308 if let Ok(i) =
9309 editor
9310 .find_all_references_task_sources
9311 .binary_search_by(|anchor| {
9312 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9313 })
9314 {
9315 editor.find_all_references_task_sources.remove(i);
9316 }
9317 });
9318 }
9319 });
9320
9321 let locations = references.await?;
9322 if locations.is_empty() {
9323 return anyhow::Ok(());
9324 }
9325
9326 workspace.update(&mut cx, |workspace, cx| {
9327 let title = locations
9328 .first()
9329 .as_ref()
9330 .map(|location| {
9331 let buffer = location.buffer.read(cx);
9332 format!(
9333 "References to `{}`",
9334 buffer
9335 .text_for_range(location.range.clone())
9336 .collect::<String>()
9337 )
9338 })
9339 .unwrap();
9340 Self::open_locations_in_multibuffer(
9341 workspace, locations, replica_id, title, false, cx,
9342 );
9343 })
9344 }))
9345 }
9346
9347 /// Opens a multibuffer with the given project locations in it
9348 pub fn open_locations_in_multibuffer(
9349 workspace: &mut Workspace,
9350 mut locations: Vec<Location>,
9351 replica_id: ReplicaId,
9352 title: String,
9353 split: bool,
9354 cx: &mut ViewContext<Workspace>,
9355 ) {
9356 // If there are multiple definitions, open them in a multibuffer
9357 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9358 let mut locations = locations.into_iter().peekable();
9359 let mut ranges_to_highlight = Vec::new();
9360 let capability = workspace.project().read(cx).capability();
9361
9362 let excerpt_buffer = cx.new_model(|cx| {
9363 let mut multibuffer = MultiBuffer::new(replica_id, capability);
9364 while let Some(location) = locations.next() {
9365 let buffer = location.buffer.read(cx);
9366 let mut ranges_for_buffer = Vec::new();
9367 let range = location.range.to_offset(buffer);
9368 ranges_for_buffer.push(range.clone());
9369
9370 while let Some(next_location) = locations.peek() {
9371 if next_location.buffer == location.buffer {
9372 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9373 locations.next();
9374 } else {
9375 break;
9376 }
9377 }
9378
9379 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9380 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9381 location.buffer.clone(),
9382 ranges_for_buffer,
9383 DEFAULT_MULTIBUFFER_CONTEXT,
9384 cx,
9385 ))
9386 }
9387
9388 multibuffer.with_title(title)
9389 });
9390
9391 let editor = cx.new_view(|cx| {
9392 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9393 });
9394 editor.update(cx, |editor, cx| {
9395 if let Some(first_range) = ranges_to_highlight.first() {
9396 editor.change_selections(None, cx, |selections| {
9397 selections.clear_disjoint();
9398 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9399 });
9400 }
9401 editor.highlight_background::<Self>(
9402 &ranges_to_highlight,
9403 |theme| theme.editor_highlighted_line_background,
9404 cx,
9405 );
9406 });
9407
9408 let item = Box::new(editor);
9409 let item_id = item.item_id();
9410
9411 if split {
9412 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9413 } else {
9414 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9415 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9416 pane.close_current_preview_item(cx)
9417 } else {
9418 None
9419 }
9420 });
9421 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9422 }
9423 workspace.active_pane().update(cx, |pane, cx| {
9424 pane.set_preview_item_id(Some(item_id), cx);
9425 });
9426 }
9427
9428 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9429 use language::ToOffset as _;
9430
9431 let project = self.project.clone()?;
9432 let selection = self.selections.newest_anchor().clone();
9433 let (cursor_buffer, cursor_buffer_position) = self
9434 .buffer
9435 .read(cx)
9436 .text_anchor_for_position(selection.head(), cx)?;
9437 let (tail_buffer, cursor_buffer_position_end) = self
9438 .buffer
9439 .read(cx)
9440 .text_anchor_for_position(selection.tail(), cx)?;
9441 if tail_buffer != cursor_buffer {
9442 return None;
9443 }
9444
9445 let snapshot = cursor_buffer.read(cx).snapshot();
9446 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9447 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9448 let prepare_rename = project.update(cx, |project, cx| {
9449 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
9450 });
9451 drop(snapshot);
9452
9453 Some(cx.spawn(|this, mut cx| async move {
9454 let rename_range = if let Some(range) = prepare_rename.await? {
9455 Some(range)
9456 } else {
9457 this.update(&mut cx, |this, cx| {
9458 let buffer = this.buffer.read(cx).snapshot(cx);
9459 let mut buffer_highlights = this
9460 .document_highlights_for_position(selection.head(), &buffer)
9461 .filter(|highlight| {
9462 highlight.start.excerpt_id == selection.head().excerpt_id
9463 && highlight.end.excerpt_id == selection.head().excerpt_id
9464 });
9465 buffer_highlights
9466 .next()
9467 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9468 })?
9469 };
9470 if let Some(rename_range) = rename_range {
9471 this.update(&mut cx, |this, cx| {
9472 let snapshot = cursor_buffer.read(cx).snapshot();
9473 let rename_buffer_range = rename_range.to_offset(&snapshot);
9474 let cursor_offset_in_rename_range =
9475 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9476 let cursor_offset_in_rename_range_end =
9477 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9478
9479 this.take_rename(false, cx);
9480 let buffer = this.buffer.read(cx).read(cx);
9481 let cursor_offset = selection.head().to_offset(&buffer);
9482 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9483 let rename_end = rename_start + rename_buffer_range.len();
9484 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9485 let mut old_highlight_id = None;
9486 let old_name: Arc<str> = buffer
9487 .chunks(rename_start..rename_end, true)
9488 .map(|chunk| {
9489 if old_highlight_id.is_none() {
9490 old_highlight_id = chunk.syntax_highlight_id;
9491 }
9492 chunk.text
9493 })
9494 .collect::<String>()
9495 .into();
9496
9497 drop(buffer);
9498
9499 // Position the selection in the rename editor so that it matches the current selection.
9500 this.show_local_selections = false;
9501 let rename_editor = cx.new_view(|cx| {
9502 let mut editor = Editor::single_line(cx);
9503 editor.buffer.update(cx, |buffer, cx| {
9504 buffer.edit([(0..0, old_name.clone())], None, cx)
9505 });
9506 let rename_selection_range = match cursor_offset_in_rename_range
9507 .cmp(&cursor_offset_in_rename_range_end)
9508 {
9509 Ordering::Equal => {
9510 editor.select_all(&SelectAll, cx);
9511 return editor;
9512 }
9513 Ordering::Less => {
9514 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9515 }
9516 Ordering::Greater => {
9517 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9518 }
9519 };
9520 if rename_selection_range.end > old_name.len() {
9521 editor.select_all(&SelectAll, cx);
9522 } else {
9523 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9524 s.select_ranges([rename_selection_range]);
9525 });
9526 }
9527 editor
9528 });
9529 cx.subscribe(&rename_editor, |_, _, e, cx| match e {
9530 EditorEvent::Focused => cx.emit(EditorEvent::FocusedIn),
9531 _ => {}
9532 })
9533 .detach();
9534
9535 let write_highlights =
9536 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
9537 let read_highlights =
9538 this.clear_background_highlights::<DocumentHighlightRead>(cx);
9539 let ranges = write_highlights
9540 .iter()
9541 .flat_map(|(_, ranges)| ranges.iter())
9542 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
9543 .cloned()
9544 .collect();
9545
9546 this.highlight_text::<Rename>(
9547 ranges,
9548 HighlightStyle {
9549 fade_out: Some(0.6),
9550 ..Default::default()
9551 },
9552 cx,
9553 );
9554 let rename_focus_handle = rename_editor.focus_handle(cx);
9555 cx.focus(&rename_focus_handle);
9556 let block_id = this.insert_blocks(
9557 [BlockProperties {
9558 style: BlockStyle::Flex,
9559 position: range.start,
9560 height: 1,
9561 render: Box::new({
9562 let rename_editor = rename_editor.clone();
9563 move |cx: &mut BlockContext| {
9564 let mut text_style = cx.editor_style.text.clone();
9565 if let Some(highlight_style) = old_highlight_id
9566 .and_then(|h| h.style(&cx.editor_style.syntax))
9567 {
9568 text_style = text_style.highlight(highlight_style);
9569 }
9570 div()
9571 .pl(cx.anchor_x)
9572 .child(EditorElement::new(
9573 &rename_editor,
9574 EditorStyle {
9575 background: cx.theme().system().transparent,
9576 local_player: cx.editor_style.local_player,
9577 text: text_style,
9578 scrollbar_width: cx.editor_style.scrollbar_width,
9579 syntax: cx.editor_style.syntax.clone(),
9580 status: cx.editor_style.status.clone(),
9581 inlay_hints_style: HighlightStyle {
9582 color: Some(cx.theme().status().hint),
9583 font_weight: Some(FontWeight::BOLD),
9584 ..HighlightStyle::default()
9585 },
9586 suggestions_style: HighlightStyle {
9587 color: Some(cx.theme().status().predictive),
9588 ..HighlightStyle::default()
9589 },
9590 },
9591 ))
9592 .into_any_element()
9593 }
9594 }),
9595 disposition: BlockDisposition::Below,
9596 }],
9597 Some(Autoscroll::fit()),
9598 cx,
9599 )[0];
9600 this.pending_rename = Some(RenameState {
9601 range,
9602 old_name,
9603 editor: rename_editor,
9604 block_id,
9605 });
9606 })?;
9607 }
9608
9609 Ok(())
9610 }))
9611 }
9612
9613 pub fn confirm_rename(
9614 &mut self,
9615 _: &ConfirmRename,
9616 cx: &mut ViewContext<Self>,
9617 ) -> Option<Task<Result<()>>> {
9618 let rename = self.take_rename(false, cx)?;
9619 let workspace = self.workspace()?;
9620 let (start_buffer, start) = self
9621 .buffer
9622 .read(cx)
9623 .text_anchor_for_position(rename.range.start, cx)?;
9624 let (end_buffer, end) = self
9625 .buffer
9626 .read(cx)
9627 .text_anchor_for_position(rename.range.end, cx)?;
9628 if start_buffer != end_buffer {
9629 return None;
9630 }
9631
9632 let buffer = start_buffer;
9633 let range = start..end;
9634 let old_name = rename.old_name;
9635 let new_name = rename.editor.read(cx).text(cx);
9636
9637 let rename = workspace
9638 .read(cx)
9639 .project()
9640 .clone()
9641 .update(cx, |project, cx| {
9642 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
9643 });
9644 let workspace = workspace.downgrade();
9645
9646 Some(cx.spawn(|editor, mut cx| async move {
9647 let project_transaction = rename.await?;
9648 Self::open_project_transaction(
9649 &editor,
9650 workspace,
9651 project_transaction,
9652 format!("Rename: {} → {}", old_name, new_name),
9653 cx.clone(),
9654 )
9655 .await?;
9656
9657 editor.update(&mut cx, |editor, cx| {
9658 editor.refresh_document_highlights(cx);
9659 })?;
9660 Ok(())
9661 }))
9662 }
9663
9664 fn take_rename(
9665 &mut self,
9666 moving_cursor: bool,
9667 cx: &mut ViewContext<Self>,
9668 ) -> Option<RenameState> {
9669 let rename = self.pending_rename.take()?;
9670 if rename.editor.focus_handle(cx).is_focused(cx) {
9671 cx.focus(&self.focus_handle);
9672 }
9673
9674 self.remove_blocks(
9675 [rename.block_id].into_iter().collect(),
9676 Some(Autoscroll::fit()),
9677 cx,
9678 );
9679 self.clear_highlights::<Rename>(cx);
9680 self.show_local_selections = true;
9681
9682 if moving_cursor {
9683 let rename_editor = rename.editor.read(cx);
9684 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
9685
9686 // Update the selection to match the position of the selection inside
9687 // the rename editor.
9688 let snapshot = self.buffer.read(cx).read(cx);
9689 let rename_range = rename.range.to_offset(&snapshot);
9690 let cursor_in_editor = snapshot
9691 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
9692 .min(rename_range.end);
9693 drop(snapshot);
9694
9695 self.change_selections(None, cx, |s| {
9696 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
9697 });
9698 } else {
9699 self.refresh_document_highlights(cx);
9700 }
9701
9702 Some(rename)
9703 }
9704
9705 pub fn pending_rename(&self) -> Option<&RenameState> {
9706 self.pending_rename.as_ref()
9707 }
9708
9709 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9710 let project = match &self.project {
9711 Some(project) => project.clone(),
9712 None => return None,
9713 };
9714
9715 Some(self.perform_format(project, FormatTrigger::Manual, cx))
9716 }
9717
9718 fn perform_format(
9719 &mut self,
9720 project: Model<Project>,
9721 trigger: FormatTrigger,
9722 cx: &mut ViewContext<Self>,
9723 ) -> Task<Result<()>> {
9724 let buffer = self.buffer().clone();
9725 let mut buffers = buffer.read(cx).all_buffers();
9726 if trigger == FormatTrigger::Save {
9727 buffers.retain(|buffer| buffer.read(cx).is_dirty());
9728 }
9729
9730 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
9731 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
9732
9733 cx.spawn(|_, mut cx| async move {
9734 let transaction = futures::select_biased! {
9735 () = timeout => {
9736 log::warn!("timed out waiting for formatting");
9737 None
9738 }
9739 transaction = format.log_err().fuse() => transaction,
9740 };
9741
9742 buffer
9743 .update(&mut cx, |buffer, cx| {
9744 if let Some(transaction) = transaction {
9745 if !buffer.is_singleton() {
9746 buffer.push_transaction(&transaction.0, cx);
9747 }
9748 }
9749
9750 cx.notify();
9751 })
9752 .ok();
9753
9754 Ok(())
9755 })
9756 }
9757
9758 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
9759 if let Some(project) = self.project.clone() {
9760 self.buffer.update(cx, |multi_buffer, cx| {
9761 project.update(cx, |project, cx| {
9762 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
9763 });
9764 })
9765 }
9766 }
9767
9768 fn cancel_language_server_work(
9769 &mut self,
9770 _: &CancelLanguageServerWork,
9771 cx: &mut ViewContext<Self>,
9772 ) {
9773 if let Some(project) = self.project.clone() {
9774 self.buffer.update(cx, |multi_buffer, cx| {
9775 project.update(cx, |project, cx| {
9776 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
9777 });
9778 })
9779 }
9780 }
9781
9782 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
9783 cx.show_character_palette();
9784 }
9785
9786 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
9787 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
9788 let buffer = self.buffer.read(cx).snapshot(cx);
9789 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
9790 let is_valid = buffer
9791 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
9792 .any(|entry| {
9793 entry.diagnostic.is_primary
9794 && !entry.range.is_empty()
9795 && entry.range.start == primary_range_start
9796 && entry.diagnostic.message == active_diagnostics.primary_message
9797 });
9798
9799 if is_valid != active_diagnostics.is_valid {
9800 active_diagnostics.is_valid = is_valid;
9801 let mut new_styles = HashMap::default();
9802 for (block_id, diagnostic) in &active_diagnostics.blocks {
9803 new_styles.insert(
9804 *block_id,
9805 (
9806 None,
9807 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
9808 ),
9809 );
9810 }
9811 self.display_map.update(cx, |display_map, cx| {
9812 display_map.replace_blocks(new_styles, cx)
9813 });
9814 }
9815 }
9816 }
9817
9818 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
9819 self.dismiss_diagnostics(cx);
9820 let snapshot = self.snapshot(cx);
9821 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
9822 let buffer = self.buffer.read(cx).snapshot(cx);
9823
9824 let mut primary_range = None;
9825 let mut primary_message = None;
9826 let mut group_end = Point::zero();
9827 let diagnostic_group = buffer
9828 .diagnostic_group::<MultiBufferPoint>(group_id)
9829 .filter_map(|entry| {
9830 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
9831 && (entry.range.start.row == entry.range.end.row
9832 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
9833 {
9834 return None;
9835 }
9836 if entry.range.end > group_end {
9837 group_end = entry.range.end;
9838 }
9839 if entry.diagnostic.is_primary {
9840 primary_range = Some(entry.range.clone());
9841 primary_message = Some(entry.diagnostic.message.clone());
9842 }
9843 Some(entry)
9844 })
9845 .collect::<Vec<_>>();
9846 let primary_range = primary_range?;
9847 let primary_message = primary_message?;
9848 let primary_range =
9849 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
9850
9851 let blocks = display_map
9852 .insert_blocks(
9853 diagnostic_group.iter().map(|entry| {
9854 let diagnostic = entry.diagnostic.clone();
9855 let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
9856 BlockProperties {
9857 style: BlockStyle::Fixed,
9858 position: buffer.anchor_after(entry.range.start),
9859 height: message_height,
9860 render: diagnostic_block_renderer(diagnostic, None, true, true),
9861 disposition: BlockDisposition::Below,
9862 }
9863 }),
9864 cx,
9865 )
9866 .into_iter()
9867 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
9868 .collect();
9869
9870 Some(ActiveDiagnosticGroup {
9871 primary_range,
9872 primary_message,
9873 group_id,
9874 blocks,
9875 is_valid: true,
9876 })
9877 });
9878 self.active_diagnostics.is_some()
9879 }
9880
9881 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
9882 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
9883 self.display_map.update(cx, |display_map, cx| {
9884 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
9885 });
9886 cx.notify();
9887 }
9888 }
9889
9890 pub fn set_selections_from_remote(
9891 &mut self,
9892 selections: Vec<Selection<Anchor>>,
9893 pending_selection: Option<Selection<Anchor>>,
9894 cx: &mut ViewContext<Self>,
9895 ) {
9896 let old_cursor_position = self.selections.newest_anchor().head();
9897 self.selections.change_with(cx, |s| {
9898 s.select_anchors(selections);
9899 if let Some(pending_selection) = pending_selection {
9900 s.set_pending(pending_selection, SelectMode::Character);
9901 } else {
9902 s.clear_pending();
9903 }
9904 });
9905 self.selections_did_change(false, &old_cursor_position, true, cx);
9906 }
9907
9908 fn push_to_selection_history(&mut self) {
9909 self.selection_history.push(SelectionHistoryEntry {
9910 selections: self.selections.disjoint_anchors(),
9911 select_next_state: self.select_next_state.clone(),
9912 select_prev_state: self.select_prev_state.clone(),
9913 add_selections_state: self.add_selections_state.clone(),
9914 });
9915 }
9916
9917 pub fn transact(
9918 &mut self,
9919 cx: &mut ViewContext<Self>,
9920 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
9921 ) -> Option<TransactionId> {
9922 self.start_transaction_at(Instant::now(), cx);
9923 update(self, cx);
9924 self.end_transaction_at(Instant::now(), cx)
9925 }
9926
9927 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
9928 self.end_selection(cx);
9929 if let Some(tx_id) = self
9930 .buffer
9931 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
9932 {
9933 self.selection_history
9934 .insert_transaction(tx_id, self.selections.disjoint_anchors());
9935 cx.emit(EditorEvent::TransactionBegun {
9936 transaction_id: tx_id,
9937 })
9938 }
9939 }
9940
9941 fn end_transaction_at(
9942 &mut self,
9943 now: Instant,
9944 cx: &mut ViewContext<Self>,
9945 ) -> Option<TransactionId> {
9946 if let Some(transaction_id) = self
9947 .buffer
9948 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
9949 {
9950 if let Some((_, end_selections)) =
9951 self.selection_history.transaction_mut(transaction_id)
9952 {
9953 *end_selections = Some(self.selections.disjoint_anchors());
9954 } else {
9955 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
9956 }
9957
9958 cx.emit(EditorEvent::Edited { transaction_id });
9959 Some(transaction_id)
9960 } else {
9961 None
9962 }
9963 }
9964
9965 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
9966 let mut fold_ranges = Vec::new();
9967
9968 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9969
9970 let selections = self.selections.all_adjusted(cx);
9971 for selection in selections {
9972 let range = selection.range().sorted();
9973 let buffer_start_row = range.start.row;
9974
9975 for row in (0..=range.end.row).rev() {
9976 if let Some((foldable_range, fold_text)) =
9977 display_map.foldable_range(MultiBufferRow(row))
9978 {
9979 if foldable_range.end.row >= buffer_start_row {
9980 fold_ranges.push((foldable_range, fold_text));
9981 if row <= range.start.row {
9982 break;
9983 }
9984 }
9985 }
9986 }
9987 }
9988
9989 self.fold_ranges(fold_ranges, true, cx);
9990 }
9991
9992 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
9993 let buffer_row = fold_at.buffer_row;
9994 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9995
9996 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
9997 let autoscroll = self
9998 .selections
9999 .all::<Point>(cx)
10000 .iter()
10001 .any(|selection| fold_range.overlaps(&selection.range()));
10002
10003 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10004 }
10005 }
10006
10007 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10008 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10009 let buffer = &display_map.buffer_snapshot;
10010 let selections = self.selections.all::<Point>(cx);
10011 let ranges = selections
10012 .iter()
10013 .map(|s| {
10014 let range = s.display_range(&display_map).sorted();
10015 let mut start = range.start.to_point(&display_map);
10016 let mut end = range.end.to_point(&display_map);
10017 start.column = 0;
10018 end.column = buffer.line_len(MultiBufferRow(end.row));
10019 start..end
10020 })
10021 .collect::<Vec<_>>();
10022
10023 self.unfold_ranges(ranges, true, true, cx);
10024 }
10025
10026 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10027 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10028
10029 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10030 ..Point::new(
10031 unfold_at.buffer_row.0,
10032 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10033 );
10034
10035 let autoscroll = self
10036 .selections
10037 .all::<Point>(cx)
10038 .iter()
10039 .any(|selection| selection.range().overlaps(&intersection_range));
10040
10041 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10042 }
10043
10044 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10045 let selections = self.selections.all::<Point>(cx);
10046 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10047 let line_mode = self.selections.line_mode;
10048 let ranges = selections.into_iter().map(|s| {
10049 if line_mode {
10050 let start = Point::new(s.start.row, 0);
10051 let end = Point::new(
10052 s.end.row,
10053 display_map
10054 .buffer_snapshot
10055 .line_len(MultiBufferRow(s.end.row)),
10056 );
10057 (start..end, display_map.fold_placeholder.clone())
10058 } else {
10059 (s.start..s.end, display_map.fold_placeholder.clone())
10060 }
10061 });
10062 self.fold_ranges(ranges, true, cx);
10063 }
10064
10065 pub fn fold_ranges<T: ToOffset + Clone>(
10066 &mut self,
10067 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10068 auto_scroll: bool,
10069 cx: &mut ViewContext<Self>,
10070 ) {
10071 let mut fold_ranges = Vec::new();
10072 let mut buffers_affected = HashMap::default();
10073 let multi_buffer = self.buffer().read(cx);
10074 for (fold_range, fold_text) in ranges {
10075 if let Some((_, buffer, _)) =
10076 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10077 {
10078 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10079 };
10080 fold_ranges.push((fold_range, fold_text));
10081 }
10082
10083 let mut ranges = fold_ranges.into_iter().peekable();
10084 if ranges.peek().is_some() {
10085 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10086
10087 if auto_scroll {
10088 self.request_autoscroll(Autoscroll::fit(), cx);
10089 }
10090
10091 for buffer in buffers_affected.into_values() {
10092 self.sync_expanded_diff_hunks(buffer, cx);
10093 }
10094
10095 cx.notify();
10096
10097 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10098 // Clear diagnostics block when folding a range that contains it.
10099 let snapshot = self.snapshot(cx);
10100 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10101 drop(snapshot);
10102 self.active_diagnostics = Some(active_diagnostics);
10103 self.dismiss_diagnostics(cx);
10104 } else {
10105 self.active_diagnostics = Some(active_diagnostics);
10106 }
10107 }
10108
10109 self.scrollbar_marker_state.dirty = true;
10110 }
10111 }
10112
10113 pub fn unfold_ranges<T: ToOffset + Clone>(
10114 &mut self,
10115 ranges: impl IntoIterator<Item = Range<T>>,
10116 inclusive: bool,
10117 auto_scroll: bool,
10118 cx: &mut ViewContext<Self>,
10119 ) {
10120 let mut unfold_ranges = Vec::new();
10121 let mut buffers_affected = HashMap::default();
10122 let multi_buffer = self.buffer().read(cx);
10123 for range in ranges {
10124 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10125 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10126 };
10127 unfold_ranges.push(range);
10128 }
10129
10130 let mut ranges = unfold_ranges.into_iter().peekable();
10131 if ranges.peek().is_some() {
10132 self.display_map
10133 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10134 if auto_scroll {
10135 self.request_autoscroll(Autoscroll::fit(), cx);
10136 }
10137
10138 for buffer in buffers_affected.into_values() {
10139 self.sync_expanded_diff_hunks(buffer, cx);
10140 }
10141
10142 cx.notify();
10143 self.scrollbar_marker_state.dirty = true;
10144 self.active_indent_guides_state.dirty = true;
10145 }
10146 }
10147
10148 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10149 if hovered != self.gutter_hovered {
10150 self.gutter_hovered = hovered;
10151 cx.notify();
10152 }
10153 }
10154
10155 pub fn insert_blocks(
10156 &mut self,
10157 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10158 autoscroll: Option<Autoscroll>,
10159 cx: &mut ViewContext<Self>,
10160 ) -> Vec<CustomBlockId> {
10161 let blocks = self
10162 .display_map
10163 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10164 if let Some(autoscroll) = autoscroll {
10165 self.request_autoscroll(autoscroll, cx);
10166 }
10167 blocks
10168 }
10169
10170 pub fn replace_blocks(
10171 &mut self,
10172 blocks: HashMap<CustomBlockId, (Option<u8>, RenderBlock)>,
10173 autoscroll: Option<Autoscroll>,
10174 cx: &mut ViewContext<Self>,
10175 ) {
10176 self.display_map
10177 .update(cx, |display_map, cx| display_map.replace_blocks(blocks, cx));
10178 if let Some(autoscroll) = autoscroll {
10179 self.request_autoscroll(autoscroll, cx);
10180 }
10181 }
10182
10183 pub fn remove_blocks(
10184 &mut self,
10185 block_ids: HashSet<CustomBlockId>,
10186 autoscroll: Option<Autoscroll>,
10187 cx: &mut ViewContext<Self>,
10188 ) {
10189 self.display_map.update(cx, |display_map, cx| {
10190 display_map.remove_blocks(block_ids, cx)
10191 });
10192 if let Some(autoscroll) = autoscroll {
10193 self.request_autoscroll(autoscroll, cx);
10194 }
10195 }
10196
10197 pub fn row_for_block(
10198 &self,
10199 block_id: CustomBlockId,
10200 cx: &mut ViewContext<Self>,
10201 ) -> Option<DisplayRow> {
10202 self.display_map
10203 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10204 }
10205
10206 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10207 self.focused_block = Some(focused_block);
10208 }
10209
10210 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10211 self.focused_block.take()
10212 }
10213
10214 pub fn insert_creases(
10215 &mut self,
10216 creases: impl IntoIterator<Item = Crease>,
10217 cx: &mut ViewContext<Self>,
10218 ) -> Vec<CreaseId> {
10219 self.display_map
10220 .update(cx, |map, cx| map.insert_creases(creases, cx))
10221 }
10222
10223 pub fn remove_creases(
10224 &mut self,
10225 ids: impl IntoIterator<Item = CreaseId>,
10226 cx: &mut ViewContext<Self>,
10227 ) {
10228 self.display_map
10229 .update(cx, |map, cx| map.remove_creases(ids, cx));
10230 }
10231
10232 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10233 self.display_map
10234 .update(cx, |map, cx| map.snapshot(cx))
10235 .longest_row()
10236 }
10237
10238 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10239 self.display_map
10240 .update(cx, |map, cx| map.snapshot(cx))
10241 .max_point()
10242 }
10243
10244 pub fn text(&self, cx: &AppContext) -> String {
10245 self.buffer.read(cx).read(cx).text()
10246 }
10247
10248 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10249 let text = self.text(cx);
10250 let text = text.trim();
10251
10252 if text.is_empty() {
10253 return None;
10254 }
10255
10256 Some(text.to_string())
10257 }
10258
10259 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10260 self.transact(cx, |this, cx| {
10261 this.buffer
10262 .read(cx)
10263 .as_singleton()
10264 .expect("you can only call set_text on editors for singleton buffers")
10265 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10266 });
10267 }
10268
10269 pub fn display_text(&self, cx: &mut AppContext) -> String {
10270 self.display_map
10271 .update(cx, |map, cx| map.snapshot(cx))
10272 .text()
10273 }
10274
10275 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10276 let mut wrap_guides = smallvec::smallvec![];
10277
10278 if self.show_wrap_guides == Some(false) {
10279 return wrap_guides;
10280 }
10281
10282 let settings = self.buffer.read(cx).settings_at(0, cx);
10283 if settings.show_wrap_guides {
10284 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10285 wrap_guides.push((soft_wrap as usize, true));
10286 }
10287 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10288 }
10289
10290 wrap_guides
10291 }
10292
10293 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10294 let settings = self.buffer.read(cx).settings_at(0, cx);
10295 let mode = self
10296 .soft_wrap_mode_override
10297 .unwrap_or_else(|| settings.soft_wrap);
10298 match mode {
10299 language_settings::SoftWrap::None => SoftWrap::None,
10300 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10301 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10302 language_settings::SoftWrap::PreferredLineLength => {
10303 SoftWrap::Column(settings.preferred_line_length)
10304 }
10305 }
10306 }
10307
10308 pub fn set_soft_wrap_mode(
10309 &mut self,
10310 mode: language_settings::SoftWrap,
10311 cx: &mut ViewContext<Self>,
10312 ) {
10313 self.soft_wrap_mode_override = Some(mode);
10314 cx.notify();
10315 }
10316
10317 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10318 let rem_size = cx.rem_size();
10319 self.display_map.update(cx, |map, cx| {
10320 map.set_font(
10321 style.text.font(),
10322 style.text.font_size.to_pixels(rem_size),
10323 cx,
10324 )
10325 });
10326 self.style = Some(style);
10327 }
10328
10329 pub fn style(&self) -> Option<&EditorStyle> {
10330 self.style.as_ref()
10331 }
10332
10333 // Called by the element. This method is not designed to be called outside of the editor
10334 // element's layout code because it does not notify when rewrapping is computed synchronously.
10335 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10336 self.display_map
10337 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10338 }
10339
10340 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10341 if self.soft_wrap_mode_override.is_some() {
10342 self.soft_wrap_mode_override.take();
10343 } else {
10344 let soft_wrap = match self.soft_wrap_mode(cx) {
10345 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10346 SoftWrap::EditorWidth | SoftWrap::Column(_) => {
10347 language_settings::SoftWrap::PreferLine
10348 }
10349 };
10350 self.soft_wrap_mode_override = Some(soft_wrap);
10351 }
10352 cx.notify();
10353 }
10354
10355 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10356 let Some(workspace) = self.workspace() else {
10357 return;
10358 };
10359 let fs = workspace.read(cx).app_state().fs.clone();
10360 let current_show = TabBarSettings::get_global(cx).show;
10361 update_settings_file::<TabBarSettings>(fs, cx, move |setting| {
10362 setting.show = Some(!current_show);
10363 });
10364 }
10365
10366 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10367 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10368 self.buffer
10369 .read(cx)
10370 .settings_at(0, cx)
10371 .indent_guides
10372 .enabled
10373 });
10374 self.show_indent_guides = Some(!currently_enabled);
10375 cx.notify();
10376 }
10377
10378 fn should_show_indent_guides(&self) -> Option<bool> {
10379 self.show_indent_guides
10380 }
10381
10382 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10383 let mut editor_settings = EditorSettings::get_global(cx).clone();
10384 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10385 EditorSettings::override_global(editor_settings, cx);
10386 }
10387
10388 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10389 self.show_gutter = show_gutter;
10390 cx.notify();
10391 }
10392
10393 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10394 self.show_line_numbers = Some(show_line_numbers);
10395 cx.notify();
10396 }
10397
10398 pub fn set_show_git_diff_gutter(
10399 &mut self,
10400 show_git_diff_gutter: bool,
10401 cx: &mut ViewContext<Self>,
10402 ) {
10403 self.show_git_diff_gutter = Some(show_git_diff_gutter);
10404 cx.notify();
10405 }
10406
10407 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10408 self.show_code_actions = Some(show_code_actions);
10409 cx.notify();
10410 }
10411
10412 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10413 self.show_runnables = Some(show_runnables);
10414 cx.notify();
10415 }
10416
10417 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10418 self.show_wrap_guides = Some(show_wrap_guides);
10419 cx.notify();
10420 }
10421
10422 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10423 self.show_indent_guides = Some(show_indent_guides);
10424 cx.notify();
10425 }
10426
10427 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10428 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10429 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10430 if let Some(dir) = file.abs_path(cx).parent() {
10431 return Some(dir.to_owned());
10432 }
10433 }
10434
10435 if let Some(project_path) = buffer.read(cx).project_path(cx) {
10436 return Some(project_path.path.to_path_buf());
10437 }
10438 }
10439
10440 None
10441 }
10442
10443 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10444 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10445 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10446 cx.reveal_path(&file.abs_path(cx));
10447 }
10448 }
10449 }
10450
10451 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10452 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10453 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10454 if let Some(path) = file.abs_path(cx).to_str() {
10455 cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10456 }
10457 }
10458 }
10459 }
10460
10461 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10462 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10463 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10464 if let Some(path) = file.path().to_str() {
10465 cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10466 }
10467 }
10468 }
10469 }
10470
10471 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10472 self.show_git_blame_gutter = !self.show_git_blame_gutter;
10473
10474 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10475 self.start_git_blame(true, cx);
10476 }
10477
10478 cx.notify();
10479 }
10480
10481 pub fn toggle_git_blame_inline(
10482 &mut self,
10483 _: &ToggleGitBlameInline,
10484 cx: &mut ViewContext<Self>,
10485 ) {
10486 self.toggle_git_blame_inline_internal(true, cx);
10487 cx.notify();
10488 }
10489
10490 pub fn git_blame_inline_enabled(&self) -> bool {
10491 self.git_blame_inline_enabled
10492 }
10493
10494 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10495 self.show_selection_menu = self
10496 .show_selection_menu
10497 .map(|show_selections_menu| !show_selections_menu)
10498 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10499
10500 cx.notify();
10501 }
10502
10503 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10504 self.show_selection_menu
10505 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10506 }
10507
10508 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10509 if let Some(project) = self.project.as_ref() {
10510 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10511 return;
10512 };
10513
10514 if buffer.read(cx).file().is_none() {
10515 return;
10516 }
10517
10518 let focused = self.focus_handle(cx).contains_focused(cx);
10519
10520 let project = project.clone();
10521 let blame =
10522 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10523 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10524 self.blame = Some(blame);
10525 }
10526 }
10527
10528 fn toggle_git_blame_inline_internal(
10529 &mut self,
10530 user_triggered: bool,
10531 cx: &mut ViewContext<Self>,
10532 ) {
10533 if self.git_blame_inline_enabled {
10534 self.git_blame_inline_enabled = false;
10535 self.show_git_blame_inline = false;
10536 self.show_git_blame_inline_delay_task.take();
10537 } else {
10538 self.git_blame_inline_enabled = true;
10539 self.start_git_blame_inline(user_triggered, cx);
10540 }
10541
10542 cx.notify();
10543 }
10544
10545 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10546 self.start_git_blame(user_triggered, cx);
10547
10548 if ProjectSettings::get_global(cx)
10549 .git
10550 .inline_blame_delay()
10551 .is_some()
10552 {
10553 self.start_inline_blame_timer(cx);
10554 } else {
10555 self.show_git_blame_inline = true
10556 }
10557 }
10558
10559 pub fn blame(&self) -> Option<&Model<GitBlame>> {
10560 self.blame.as_ref()
10561 }
10562
10563 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10564 self.show_git_blame_gutter && self.has_blame_entries(cx)
10565 }
10566
10567 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10568 self.show_git_blame_inline
10569 && self.focus_handle.is_focused(cx)
10570 && !self.newest_selection_head_on_empty_line(cx)
10571 && self.has_blame_entries(cx)
10572 }
10573
10574 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10575 self.blame()
10576 .map_or(false, |blame| blame.read(cx).has_generated_entries())
10577 }
10578
10579 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10580 let cursor_anchor = self.selections.newest_anchor().head();
10581
10582 let snapshot = self.buffer.read(cx).snapshot(cx);
10583 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10584
10585 snapshot.line_len(buffer_row) == 0
10586 }
10587
10588 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10589 let (path, selection, repo) = maybe!({
10590 let project_handle = self.project.as_ref()?.clone();
10591 let project = project_handle.read(cx);
10592
10593 let selection = self.selections.newest::<Point>(cx);
10594 let selection_range = selection.range();
10595
10596 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10597 (buffer, selection_range.start.row..selection_range.end.row)
10598 } else {
10599 let buffer_ranges = self
10600 .buffer()
10601 .read(cx)
10602 .range_to_buffer_ranges(selection_range, cx);
10603
10604 let (buffer, range, _) = if selection.reversed {
10605 buffer_ranges.first()
10606 } else {
10607 buffer_ranges.last()
10608 }?;
10609
10610 let snapshot = buffer.read(cx).snapshot();
10611 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10612 ..text::ToPoint::to_point(&range.end, &snapshot).row;
10613 (buffer.clone(), selection)
10614 };
10615
10616 let path = buffer
10617 .read(cx)
10618 .file()?
10619 .as_local()?
10620 .path()
10621 .to_str()?
10622 .to_string();
10623 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10624 Some((path, selection, repo))
10625 })
10626 .ok_or_else(|| anyhow!("unable to open git repository"))?;
10627
10628 const REMOTE_NAME: &str = "origin";
10629 let origin_url = repo
10630 .remote_url(REMOTE_NAME)
10631 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10632 let sha = repo
10633 .head_sha()
10634 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10635
10636 let (provider, remote) =
10637 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10638 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10639
10640 Ok(provider.build_permalink(
10641 remote,
10642 BuildPermalinkParams {
10643 sha: &sha,
10644 path: &path,
10645 selection: Some(selection),
10646 },
10647 ))
10648 }
10649
10650 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10651 let permalink = self.get_permalink_to_line(cx);
10652
10653 match permalink {
10654 Ok(permalink) => {
10655 cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
10656 }
10657 Err(err) => {
10658 let message = format!("Failed to copy permalink: {err}");
10659
10660 Err::<(), anyhow::Error>(err).log_err();
10661
10662 if let Some(workspace) = self.workspace() {
10663 workspace.update(cx, |workspace, cx| {
10664 struct CopyPermalinkToLine;
10665
10666 workspace.show_toast(
10667 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10668 cx,
10669 )
10670 })
10671 }
10672 }
10673 }
10674 }
10675
10676 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10677 let permalink = self.get_permalink_to_line(cx);
10678
10679 match permalink {
10680 Ok(permalink) => {
10681 cx.open_url(permalink.as_ref());
10682 }
10683 Err(err) => {
10684 let message = format!("Failed to open permalink: {err}");
10685
10686 Err::<(), anyhow::Error>(err).log_err();
10687
10688 if let Some(workspace) = self.workspace() {
10689 workspace.update(cx, |workspace, cx| {
10690 struct OpenPermalinkToLine;
10691
10692 workspace.show_toast(
10693 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
10694 cx,
10695 )
10696 })
10697 }
10698 }
10699 }
10700 }
10701
10702 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
10703 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
10704 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
10705 pub fn highlight_rows<T: 'static>(
10706 &mut self,
10707 rows: RangeInclusive<Anchor>,
10708 color: Option<Hsla>,
10709 should_autoscroll: bool,
10710 cx: &mut ViewContext<Self>,
10711 ) {
10712 let snapshot = self.buffer().read(cx).snapshot(cx);
10713 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
10714 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
10715 highlight
10716 .range
10717 .start()
10718 .cmp(&rows.start(), &snapshot)
10719 .then(highlight.range.end().cmp(&rows.end(), &snapshot))
10720 });
10721 match (color, existing_highlight_index) {
10722 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
10723 ix,
10724 RowHighlight {
10725 index: post_inc(&mut self.highlight_order),
10726 range: rows,
10727 should_autoscroll,
10728 color,
10729 },
10730 ),
10731 (None, Ok(i)) => {
10732 row_highlights.remove(i);
10733 }
10734 }
10735 }
10736
10737 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
10738 pub fn clear_row_highlights<T: 'static>(&mut self) {
10739 self.highlighted_rows.remove(&TypeId::of::<T>());
10740 }
10741
10742 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
10743 pub fn highlighted_rows<T: 'static>(
10744 &self,
10745 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
10746 Some(
10747 self.highlighted_rows
10748 .get(&TypeId::of::<T>())?
10749 .iter()
10750 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
10751 )
10752 }
10753
10754 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
10755 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
10756 /// Allows to ignore certain kinds of highlights.
10757 pub fn highlighted_display_rows(
10758 &mut self,
10759 cx: &mut WindowContext,
10760 ) -> BTreeMap<DisplayRow, Hsla> {
10761 let snapshot = self.snapshot(cx);
10762 let mut used_highlight_orders = HashMap::default();
10763 self.highlighted_rows
10764 .iter()
10765 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
10766 .fold(
10767 BTreeMap::<DisplayRow, Hsla>::new(),
10768 |mut unique_rows, highlight| {
10769 let start_row = highlight.range.start().to_display_point(&snapshot).row();
10770 let end_row = highlight.range.end().to_display_point(&snapshot).row();
10771 for row in start_row.0..=end_row.0 {
10772 let used_index =
10773 used_highlight_orders.entry(row).or_insert(highlight.index);
10774 if highlight.index >= *used_index {
10775 *used_index = highlight.index;
10776 match highlight.color {
10777 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
10778 None => unique_rows.remove(&DisplayRow(row)),
10779 };
10780 }
10781 }
10782 unique_rows
10783 },
10784 )
10785 }
10786
10787 pub fn highlighted_display_row_for_autoscroll(
10788 &self,
10789 snapshot: &DisplaySnapshot,
10790 ) -> Option<DisplayRow> {
10791 self.highlighted_rows
10792 .values()
10793 .flat_map(|highlighted_rows| highlighted_rows.iter())
10794 .filter_map(|highlight| {
10795 if highlight.color.is_none() || !highlight.should_autoscroll {
10796 return None;
10797 }
10798 Some(highlight.range.start().to_display_point(&snapshot).row())
10799 })
10800 .min()
10801 }
10802
10803 pub fn set_search_within_ranges(
10804 &mut self,
10805 ranges: &[Range<Anchor>],
10806 cx: &mut ViewContext<Self>,
10807 ) {
10808 self.highlight_background::<SearchWithinRange>(
10809 ranges,
10810 |colors| colors.editor_document_highlight_read_background,
10811 cx,
10812 )
10813 }
10814
10815 pub fn set_breadcrumb_header(&mut self, new_header: String) {
10816 self.breadcrumb_header = Some(new_header);
10817 }
10818
10819 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
10820 self.clear_background_highlights::<SearchWithinRange>(cx);
10821 }
10822
10823 pub fn highlight_background<T: 'static>(
10824 &mut self,
10825 ranges: &[Range<Anchor>],
10826 color_fetcher: fn(&ThemeColors) -> Hsla,
10827 cx: &mut ViewContext<Self>,
10828 ) {
10829 let snapshot = self.snapshot(cx);
10830 // this is to try and catch a panic sooner
10831 for range in ranges {
10832 snapshot
10833 .buffer_snapshot
10834 .summary_for_anchor::<usize>(&range.start);
10835 snapshot
10836 .buffer_snapshot
10837 .summary_for_anchor::<usize>(&range.end);
10838 }
10839
10840 self.background_highlights
10841 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10842 self.scrollbar_marker_state.dirty = true;
10843 cx.notify();
10844 }
10845
10846 pub fn clear_background_highlights<T: 'static>(
10847 &mut self,
10848 cx: &mut ViewContext<Self>,
10849 ) -> Option<BackgroundHighlight> {
10850 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
10851 if !text_highlights.1.is_empty() {
10852 self.scrollbar_marker_state.dirty = true;
10853 cx.notify();
10854 }
10855 Some(text_highlights)
10856 }
10857
10858 pub fn highlight_gutter<T: 'static>(
10859 &mut self,
10860 ranges: &[Range<Anchor>],
10861 color_fetcher: fn(&AppContext) -> Hsla,
10862 cx: &mut ViewContext<Self>,
10863 ) {
10864 self.gutter_highlights
10865 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10866 cx.notify();
10867 }
10868
10869 pub fn clear_gutter_highlights<T: 'static>(
10870 &mut self,
10871 cx: &mut ViewContext<Self>,
10872 ) -> Option<GutterHighlight> {
10873 cx.notify();
10874 self.gutter_highlights.remove(&TypeId::of::<T>())
10875 }
10876
10877 #[cfg(feature = "test-support")]
10878 pub fn all_text_background_highlights(
10879 &mut self,
10880 cx: &mut ViewContext<Self>,
10881 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10882 let snapshot = self.snapshot(cx);
10883 let buffer = &snapshot.buffer_snapshot;
10884 let start = buffer.anchor_before(0);
10885 let end = buffer.anchor_after(buffer.len());
10886 let theme = cx.theme().colors();
10887 self.background_highlights_in_range(start..end, &snapshot, theme)
10888 }
10889
10890 #[cfg(feature = "test-support")]
10891 pub fn search_background_highlights(
10892 &mut self,
10893 cx: &mut ViewContext<Self>,
10894 ) -> Vec<Range<Point>> {
10895 let snapshot = self.buffer().read(cx).snapshot(cx);
10896
10897 let highlights = self
10898 .background_highlights
10899 .get(&TypeId::of::<items::BufferSearchHighlights>());
10900
10901 if let Some((_color, ranges)) = highlights {
10902 ranges
10903 .iter()
10904 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
10905 .collect_vec()
10906 } else {
10907 vec![]
10908 }
10909 }
10910
10911 fn document_highlights_for_position<'a>(
10912 &'a self,
10913 position: Anchor,
10914 buffer: &'a MultiBufferSnapshot,
10915 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
10916 let read_highlights = self
10917 .background_highlights
10918 .get(&TypeId::of::<DocumentHighlightRead>())
10919 .map(|h| &h.1);
10920 let write_highlights = self
10921 .background_highlights
10922 .get(&TypeId::of::<DocumentHighlightWrite>())
10923 .map(|h| &h.1);
10924 let left_position = position.bias_left(buffer);
10925 let right_position = position.bias_right(buffer);
10926 read_highlights
10927 .into_iter()
10928 .chain(write_highlights)
10929 .flat_map(move |ranges| {
10930 let start_ix = match ranges.binary_search_by(|probe| {
10931 let cmp = probe.end.cmp(&left_position, buffer);
10932 if cmp.is_ge() {
10933 Ordering::Greater
10934 } else {
10935 Ordering::Less
10936 }
10937 }) {
10938 Ok(i) | Err(i) => i,
10939 };
10940
10941 ranges[start_ix..]
10942 .iter()
10943 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
10944 })
10945 }
10946
10947 pub fn has_background_highlights<T: 'static>(&self) -> bool {
10948 self.background_highlights
10949 .get(&TypeId::of::<T>())
10950 .map_or(false, |(_, highlights)| !highlights.is_empty())
10951 }
10952
10953 pub fn background_highlights_in_range(
10954 &self,
10955 search_range: Range<Anchor>,
10956 display_snapshot: &DisplaySnapshot,
10957 theme: &ThemeColors,
10958 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10959 let mut results = Vec::new();
10960 for (color_fetcher, ranges) in self.background_highlights.values() {
10961 let color = color_fetcher(theme);
10962 let start_ix = match ranges.binary_search_by(|probe| {
10963 let cmp = probe
10964 .end
10965 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10966 if cmp.is_gt() {
10967 Ordering::Greater
10968 } else {
10969 Ordering::Less
10970 }
10971 }) {
10972 Ok(i) | Err(i) => i,
10973 };
10974 for range in &ranges[start_ix..] {
10975 if range
10976 .start
10977 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10978 .is_ge()
10979 {
10980 break;
10981 }
10982
10983 let start = range.start.to_display_point(&display_snapshot);
10984 let end = range.end.to_display_point(&display_snapshot);
10985 results.push((start..end, color))
10986 }
10987 }
10988 results
10989 }
10990
10991 pub fn background_highlight_row_ranges<T: 'static>(
10992 &self,
10993 search_range: Range<Anchor>,
10994 display_snapshot: &DisplaySnapshot,
10995 count: usize,
10996 ) -> Vec<RangeInclusive<DisplayPoint>> {
10997 let mut results = Vec::new();
10998 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
10999 return vec![];
11000 };
11001
11002 let start_ix = match ranges.binary_search_by(|probe| {
11003 let cmp = probe
11004 .end
11005 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11006 if cmp.is_gt() {
11007 Ordering::Greater
11008 } else {
11009 Ordering::Less
11010 }
11011 }) {
11012 Ok(i) | Err(i) => i,
11013 };
11014 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11015 if let (Some(start_display), Some(end_display)) = (start, end) {
11016 results.push(
11017 start_display.to_display_point(display_snapshot)
11018 ..=end_display.to_display_point(display_snapshot),
11019 );
11020 }
11021 };
11022 let mut start_row: Option<Point> = None;
11023 let mut end_row: Option<Point> = None;
11024 if ranges.len() > count {
11025 return Vec::new();
11026 }
11027 for range in &ranges[start_ix..] {
11028 if range
11029 .start
11030 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11031 .is_ge()
11032 {
11033 break;
11034 }
11035 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11036 if let Some(current_row) = &end_row {
11037 if end.row == current_row.row {
11038 continue;
11039 }
11040 }
11041 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11042 if start_row.is_none() {
11043 assert_eq!(end_row, None);
11044 start_row = Some(start);
11045 end_row = Some(end);
11046 continue;
11047 }
11048 if let Some(current_end) = end_row.as_mut() {
11049 if start.row > current_end.row + 1 {
11050 push_region(start_row, end_row);
11051 start_row = Some(start);
11052 end_row = Some(end);
11053 } else {
11054 // Merge two hunks.
11055 *current_end = end;
11056 }
11057 } else {
11058 unreachable!();
11059 }
11060 }
11061 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11062 push_region(start_row, end_row);
11063 results
11064 }
11065
11066 pub fn gutter_highlights_in_range(
11067 &self,
11068 search_range: Range<Anchor>,
11069 display_snapshot: &DisplaySnapshot,
11070 cx: &AppContext,
11071 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11072 let mut results = Vec::new();
11073 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11074 let color = color_fetcher(cx);
11075 let start_ix = match ranges.binary_search_by(|probe| {
11076 let cmp = probe
11077 .end
11078 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11079 if cmp.is_gt() {
11080 Ordering::Greater
11081 } else {
11082 Ordering::Less
11083 }
11084 }) {
11085 Ok(i) | Err(i) => i,
11086 };
11087 for range in &ranges[start_ix..] {
11088 if range
11089 .start
11090 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11091 .is_ge()
11092 {
11093 break;
11094 }
11095
11096 let start = range.start.to_display_point(&display_snapshot);
11097 let end = range.end.to_display_point(&display_snapshot);
11098 results.push((start..end, color))
11099 }
11100 }
11101 results
11102 }
11103
11104 /// Get the text ranges corresponding to the redaction query
11105 pub fn redacted_ranges(
11106 &self,
11107 search_range: Range<Anchor>,
11108 display_snapshot: &DisplaySnapshot,
11109 cx: &WindowContext,
11110 ) -> Vec<Range<DisplayPoint>> {
11111 display_snapshot
11112 .buffer_snapshot
11113 .redacted_ranges(search_range, |file| {
11114 if let Some(file) = file {
11115 file.is_private()
11116 && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
11117 } else {
11118 false
11119 }
11120 })
11121 .map(|range| {
11122 range.start.to_display_point(display_snapshot)
11123 ..range.end.to_display_point(display_snapshot)
11124 })
11125 .collect()
11126 }
11127
11128 pub fn highlight_text<T: 'static>(
11129 &mut self,
11130 ranges: Vec<Range<Anchor>>,
11131 style: HighlightStyle,
11132 cx: &mut ViewContext<Self>,
11133 ) {
11134 self.display_map.update(cx, |map, _| {
11135 map.highlight_text(TypeId::of::<T>(), ranges, style)
11136 });
11137 cx.notify();
11138 }
11139
11140 pub(crate) fn highlight_inlays<T: 'static>(
11141 &mut self,
11142 highlights: Vec<InlayHighlight>,
11143 style: HighlightStyle,
11144 cx: &mut ViewContext<Self>,
11145 ) {
11146 self.display_map.update(cx, |map, _| {
11147 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11148 });
11149 cx.notify();
11150 }
11151
11152 pub fn text_highlights<'a, T: 'static>(
11153 &'a self,
11154 cx: &'a AppContext,
11155 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11156 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11157 }
11158
11159 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11160 let cleared = self
11161 .display_map
11162 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11163 if cleared {
11164 cx.notify();
11165 }
11166 }
11167
11168 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11169 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11170 && self.focus_handle.is_focused(cx)
11171 }
11172
11173 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11174 self.show_cursor_when_unfocused = is_enabled;
11175 cx.notify();
11176 }
11177
11178 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11179 cx.notify();
11180 }
11181
11182 fn on_buffer_event(
11183 &mut self,
11184 multibuffer: Model<MultiBuffer>,
11185 event: &multi_buffer::Event,
11186 cx: &mut ViewContext<Self>,
11187 ) {
11188 match event {
11189 multi_buffer::Event::Edited {
11190 singleton_buffer_edited,
11191 } => {
11192 self.scrollbar_marker_state.dirty = true;
11193 self.active_indent_guides_state.dirty = true;
11194 self.refresh_active_diagnostics(cx);
11195 self.refresh_code_actions(cx);
11196 if self.has_active_inline_completion(cx) {
11197 self.update_visible_inline_completion(cx);
11198 }
11199 cx.emit(EditorEvent::BufferEdited);
11200 cx.emit(SearchEvent::MatchesInvalidated);
11201 if *singleton_buffer_edited {
11202 if let Some(project) = &self.project {
11203 let project = project.read(cx);
11204 #[allow(clippy::mutable_key_type)]
11205 let languages_affected = multibuffer
11206 .read(cx)
11207 .all_buffers()
11208 .into_iter()
11209 .filter_map(|buffer| {
11210 let buffer = buffer.read(cx);
11211 let language = buffer.language()?;
11212 if project.is_local()
11213 && project.language_servers_for_buffer(buffer, cx).count() == 0
11214 {
11215 None
11216 } else {
11217 Some(language)
11218 }
11219 })
11220 .cloned()
11221 .collect::<HashSet<_>>();
11222 if !languages_affected.is_empty() {
11223 self.refresh_inlay_hints(
11224 InlayHintRefreshReason::BufferEdited(languages_affected),
11225 cx,
11226 );
11227 }
11228 }
11229 }
11230
11231 let Some(project) = &self.project else { return };
11232 let telemetry = project.read(cx).client().telemetry().clone();
11233 refresh_linked_ranges(self, cx);
11234 telemetry.log_edit_event("editor");
11235 }
11236 multi_buffer::Event::ExcerptsAdded {
11237 buffer,
11238 predecessor,
11239 excerpts,
11240 } => {
11241 self.tasks_update_task = Some(self.refresh_runnables(cx));
11242 cx.emit(EditorEvent::ExcerptsAdded {
11243 buffer: buffer.clone(),
11244 predecessor: *predecessor,
11245 excerpts: excerpts.clone(),
11246 });
11247 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11248 }
11249 multi_buffer::Event::ExcerptsRemoved { ids } => {
11250 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11251 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11252 }
11253 multi_buffer::Event::ExcerptsEdited { ids } => {
11254 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11255 }
11256 multi_buffer::Event::ExcerptsExpanded { ids } => {
11257 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11258 }
11259 multi_buffer::Event::Reparsed(buffer_id) => {
11260 self.tasks_update_task = Some(self.refresh_runnables(cx));
11261
11262 cx.emit(EditorEvent::Reparsed(*buffer_id));
11263 }
11264 multi_buffer::Event::LanguageChanged(buffer_id) => {
11265 linked_editing_ranges::refresh_linked_ranges(self, cx);
11266 cx.emit(EditorEvent::Reparsed(*buffer_id));
11267 cx.notify();
11268 }
11269 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11270 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11271 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11272 cx.emit(EditorEvent::TitleChanged)
11273 }
11274 multi_buffer::Event::DiffBaseChanged => {
11275 self.scrollbar_marker_state.dirty = true;
11276 cx.emit(EditorEvent::DiffBaseChanged);
11277 cx.notify();
11278 }
11279 multi_buffer::Event::DiffUpdated { buffer } => {
11280 self.sync_expanded_diff_hunks(buffer.clone(), cx);
11281 cx.notify();
11282 }
11283 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11284 multi_buffer::Event::DiagnosticsUpdated => {
11285 self.refresh_active_diagnostics(cx);
11286 self.scrollbar_marker_state.dirty = true;
11287 cx.notify();
11288 }
11289 _ => {}
11290 };
11291 }
11292
11293 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11294 cx.notify();
11295 }
11296
11297 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11298 self.tasks_update_task = Some(self.refresh_runnables(cx));
11299 self.refresh_inline_completion(true, cx);
11300 self.refresh_inlay_hints(
11301 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11302 self.selections.newest_anchor().head(),
11303 &self.buffer.read(cx).snapshot(cx),
11304 cx,
11305 )),
11306 cx,
11307 );
11308 let editor_settings = EditorSettings::get_global(cx);
11309 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11310 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11311
11312 let project_settings = ProjectSettings::get_global(cx);
11313 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11314
11315 if self.mode == EditorMode::Full {
11316 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11317 if self.git_blame_inline_enabled != inline_blame_enabled {
11318 self.toggle_git_blame_inline_internal(false, cx);
11319 }
11320 }
11321
11322 cx.notify();
11323 }
11324
11325 pub fn set_searchable(&mut self, searchable: bool) {
11326 self.searchable = searchable;
11327 }
11328
11329 pub fn searchable(&self) -> bool {
11330 self.searchable
11331 }
11332
11333 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11334 self.open_excerpts_common(true, cx)
11335 }
11336
11337 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11338 self.open_excerpts_common(false, cx)
11339 }
11340
11341 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11342 let buffer = self.buffer.read(cx);
11343 if buffer.is_singleton() {
11344 cx.propagate();
11345 return;
11346 }
11347
11348 let Some(workspace) = self.workspace() else {
11349 cx.propagate();
11350 return;
11351 };
11352
11353 let mut new_selections_by_buffer = HashMap::default();
11354 for selection in self.selections.all::<usize>(cx) {
11355 for (buffer, mut range, _) in
11356 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11357 {
11358 if selection.reversed {
11359 mem::swap(&mut range.start, &mut range.end);
11360 }
11361 new_selections_by_buffer
11362 .entry(buffer)
11363 .or_insert(Vec::new())
11364 .push(range)
11365 }
11366 }
11367
11368 // We defer the pane interaction because we ourselves are a workspace item
11369 // and activating a new item causes the pane to call a method on us reentrantly,
11370 // which panics if we're on the stack.
11371 cx.window_context().defer(move |cx| {
11372 workspace.update(cx, |workspace, cx| {
11373 let pane = if split {
11374 workspace.adjacent_pane(cx)
11375 } else {
11376 workspace.active_pane().clone()
11377 };
11378
11379 for (buffer, ranges) in new_selections_by_buffer {
11380 let editor =
11381 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
11382 editor.update(cx, |editor, cx| {
11383 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11384 s.select_ranges(ranges);
11385 });
11386 });
11387 }
11388 })
11389 });
11390 }
11391
11392 fn jump(
11393 &mut self,
11394 path: ProjectPath,
11395 position: Point,
11396 anchor: language::Anchor,
11397 offset_from_top: u32,
11398 cx: &mut ViewContext<Self>,
11399 ) {
11400 let workspace = self.workspace();
11401 cx.spawn(|_, mut cx| async move {
11402 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11403 let editor = workspace.update(&mut cx, |workspace, cx| {
11404 // Reset the preview item id before opening the new item
11405 workspace.active_pane().update(cx, |pane, cx| {
11406 pane.set_preview_item_id(None, cx);
11407 });
11408 workspace.open_path_preview(path, None, true, true, cx)
11409 })?;
11410 let editor = editor
11411 .await?
11412 .downcast::<Editor>()
11413 .ok_or_else(|| anyhow!("opened item was not an editor"))?
11414 .downgrade();
11415 editor.update(&mut cx, |editor, cx| {
11416 let buffer = editor
11417 .buffer()
11418 .read(cx)
11419 .as_singleton()
11420 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11421 let buffer = buffer.read(cx);
11422 let cursor = if buffer.can_resolve(&anchor) {
11423 language::ToPoint::to_point(&anchor, buffer)
11424 } else {
11425 buffer.clip_point(position, Bias::Left)
11426 };
11427
11428 let nav_history = editor.nav_history.take();
11429 editor.change_selections(
11430 Some(Autoscroll::top_relative(offset_from_top as usize)),
11431 cx,
11432 |s| {
11433 s.select_ranges([cursor..cursor]);
11434 },
11435 );
11436 editor.nav_history = nav_history;
11437
11438 anyhow::Ok(())
11439 })??;
11440
11441 anyhow::Ok(())
11442 })
11443 .detach_and_log_err(cx);
11444 }
11445
11446 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11447 let snapshot = self.buffer.read(cx).read(cx);
11448 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11449 Some(
11450 ranges
11451 .iter()
11452 .map(move |range| {
11453 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11454 })
11455 .collect(),
11456 )
11457 }
11458
11459 fn selection_replacement_ranges(
11460 &self,
11461 range: Range<OffsetUtf16>,
11462 cx: &AppContext,
11463 ) -> Vec<Range<OffsetUtf16>> {
11464 let selections = self.selections.all::<OffsetUtf16>(cx);
11465 let newest_selection = selections
11466 .iter()
11467 .max_by_key(|selection| selection.id)
11468 .unwrap();
11469 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11470 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11471 let snapshot = self.buffer.read(cx).read(cx);
11472 selections
11473 .into_iter()
11474 .map(|mut selection| {
11475 selection.start.0 =
11476 (selection.start.0 as isize).saturating_add(start_delta) as usize;
11477 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11478 snapshot.clip_offset_utf16(selection.start, Bias::Left)
11479 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11480 })
11481 .collect()
11482 }
11483
11484 fn report_editor_event(
11485 &self,
11486 operation: &'static str,
11487 file_extension: Option<String>,
11488 cx: &AppContext,
11489 ) {
11490 if cfg!(any(test, feature = "test-support")) {
11491 return;
11492 }
11493
11494 let Some(project) = &self.project else { return };
11495
11496 // If None, we are in a file without an extension
11497 let file = self
11498 .buffer
11499 .read(cx)
11500 .as_singleton()
11501 .and_then(|b| b.read(cx).file());
11502 let file_extension = file_extension.or(file
11503 .as_ref()
11504 .and_then(|file| Path::new(file.file_name(cx)).extension())
11505 .and_then(|e| e.to_str())
11506 .map(|a| a.to_string()));
11507
11508 let vim_mode = cx
11509 .global::<SettingsStore>()
11510 .raw_user_settings()
11511 .get("vim_mode")
11512 == Some(&serde_json::Value::Bool(true));
11513
11514 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11515 == language::language_settings::InlineCompletionProvider::Copilot;
11516 let copilot_enabled_for_language = self
11517 .buffer
11518 .read(cx)
11519 .settings_at(0, cx)
11520 .show_inline_completions;
11521
11522 let telemetry = project.read(cx).client().telemetry().clone();
11523 telemetry.report_editor_event(
11524 file_extension,
11525 vim_mode,
11526 operation,
11527 copilot_enabled,
11528 copilot_enabled_for_language,
11529 )
11530 }
11531
11532 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11533 /// with each line being an array of {text, highlight} objects.
11534 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11535 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11536 return;
11537 };
11538
11539 #[derive(Serialize)]
11540 struct Chunk<'a> {
11541 text: String,
11542 highlight: Option<&'a str>,
11543 }
11544
11545 let snapshot = buffer.read(cx).snapshot();
11546 let range = self
11547 .selected_text_range(cx)
11548 .and_then(|selected_range| {
11549 if selected_range.is_empty() {
11550 None
11551 } else {
11552 Some(selected_range)
11553 }
11554 })
11555 .unwrap_or_else(|| 0..snapshot.len());
11556
11557 let chunks = snapshot.chunks(range, true);
11558 let mut lines = Vec::new();
11559 let mut line: VecDeque<Chunk> = VecDeque::new();
11560
11561 let Some(style) = self.style.as_ref() else {
11562 return;
11563 };
11564
11565 for chunk in chunks {
11566 let highlight = chunk
11567 .syntax_highlight_id
11568 .and_then(|id| id.name(&style.syntax));
11569 let mut chunk_lines = chunk.text.split('\n').peekable();
11570 while let Some(text) = chunk_lines.next() {
11571 let mut merged_with_last_token = false;
11572 if let Some(last_token) = line.back_mut() {
11573 if last_token.highlight == highlight {
11574 last_token.text.push_str(text);
11575 merged_with_last_token = true;
11576 }
11577 }
11578
11579 if !merged_with_last_token {
11580 line.push_back(Chunk {
11581 text: text.into(),
11582 highlight,
11583 });
11584 }
11585
11586 if chunk_lines.peek().is_some() {
11587 if line.len() > 1 && line.front().unwrap().text.is_empty() {
11588 line.pop_front();
11589 }
11590 if line.len() > 1 && line.back().unwrap().text.is_empty() {
11591 line.pop_back();
11592 }
11593
11594 lines.push(mem::take(&mut line));
11595 }
11596 }
11597 }
11598
11599 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11600 return;
11601 };
11602 cx.write_to_clipboard(ClipboardItem::new(lines));
11603 }
11604
11605 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11606 &self.inlay_hint_cache
11607 }
11608
11609 pub fn replay_insert_event(
11610 &mut self,
11611 text: &str,
11612 relative_utf16_range: Option<Range<isize>>,
11613 cx: &mut ViewContext<Self>,
11614 ) {
11615 if !self.input_enabled {
11616 cx.emit(EditorEvent::InputIgnored { text: text.into() });
11617 return;
11618 }
11619 if let Some(relative_utf16_range) = relative_utf16_range {
11620 let selections = self.selections.all::<OffsetUtf16>(cx);
11621 self.change_selections(None, cx, |s| {
11622 let new_ranges = selections.into_iter().map(|range| {
11623 let start = OffsetUtf16(
11624 range
11625 .head()
11626 .0
11627 .saturating_add_signed(relative_utf16_range.start),
11628 );
11629 let end = OffsetUtf16(
11630 range
11631 .head()
11632 .0
11633 .saturating_add_signed(relative_utf16_range.end),
11634 );
11635 start..end
11636 });
11637 s.select_ranges(new_ranges);
11638 });
11639 }
11640
11641 self.handle_input(text, cx);
11642 }
11643
11644 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11645 let Some(project) = self.project.as_ref() else {
11646 return false;
11647 };
11648 let project = project.read(cx);
11649
11650 let mut supports = false;
11651 self.buffer().read(cx).for_each_buffer(|buffer| {
11652 if !supports {
11653 supports = project
11654 .language_servers_for_buffer(buffer.read(cx), cx)
11655 .any(
11656 |(_, server)| match server.capabilities().inlay_hint_provider {
11657 Some(lsp::OneOf::Left(enabled)) => enabled,
11658 Some(lsp::OneOf::Right(_)) => true,
11659 None => false,
11660 },
11661 )
11662 }
11663 });
11664 supports
11665 }
11666
11667 pub fn focus(&self, cx: &mut WindowContext) {
11668 cx.focus(&self.focus_handle)
11669 }
11670
11671 pub fn is_focused(&self, cx: &WindowContext) -> bool {
11672 self.focus_handle.is_focused(cx)
11673 }
11674
11675 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11676 cx.emit(EditorEvent::Focused);
11677
11678 if let Some(descendant) = self
11679 .last_focused_descendant
11680 .take()
11681 .and_then(|descendant| descendant.upgrade())
11682 {
11683 cx.focus(&descendant);
11684 } else {
11685 if let Some(blame) = self.blame.as_ref() {
11686 blame.update(cx, GitBlame::focus)
11687 }
11688
11689 self.blink_manager.update(cx, BlinkManager::enable);
11690 self.show_cursor_names(cx);
11691 self.buffer.update(cx, |buffer, cx| {
11692 buffer.finalize_last_transaction(cx);
11693 if self.leader_peer_id.is_none() {
11694 buffer.set_active_selections(
11695 &self.selections.disjoint_anchors(),
11696 self.selections.line_mode,
11697 self.cursor_shape,
11698 cx,
11699 );
11700 }
11701 });
11702 }
11703 }
11704
11705 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
11706 cx.emit(EditorEvent::FocusedIn)
11707 }
11708
11709 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
11710 if event.blurred != self.focus_handle {
11711 self.last_focused_descendant = Some(event.blurred);
11712 }
11713 }
11714
11715 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
11716 self.blink_manager.update(cx, BlinkManager::disable);
11717 self.buffer
11718 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
11719
11720 if let Some(blame) = self.blame.as_ref() {
11721 blame.update(cx, GitBlame::blur)
11722 }
11723 if !self.hover_state.focused(cx) {
11724 hide_hover(self, cx);
11725 }
11726
11727 self.hide_context_menu(cx);
11728 cx.emit(EditorEvent::Blurred);
11729 cx.notify();
11730 }
11731
11732 pub fn register_action<A: Action>(
11733 &mut self,
11734 listener: impl Fn(&A, &mut WindowContext) + 'static,
11735 ) -> Subscription {
11736 let id = self.next_editor_action_id.post_inc();
11737 let listener = Arc::new(listener);
11738 self.editor_actions.borrow_mut().insert(
11739 id,
11740 Box::new(move |cx| {
11741 let _view = cx.view().clone();
11742 let cx = cx.window_context();
11743 let listener = listener.clone();
11744 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
11745 let action = action.downcast_ref().unwrap();
11746 if phase == DispatchPhase::Bubble {
11747 listener(action, cx)
11748 }
11749 })
11750 }),
11751 );
11752
11753 let editor_actions = self.editor_actions.clone();
11754 Subscription::new(move || {
11755 editor_actions.borrow_mut().remove(&id);
11756 })
11757 }
11758
11759 pub fn file_header_size(&self) -> u8 {
11760 self.file_header_size
11761 }
11762
11763 pub fn revert(
11764 &mut self,
11765 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
11766 cx: &mut ViewContext<Self>,
11767 ) {
11768 self.buffer().update(cx, |multi_buffer, cx| {
11769 for (buffer_id, changes) in revert_changes {
11770 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
11771 buffer.update(cx, |buffer, cx| {
11772 buffer.edit(
11773 changes.into_iter().map(|(range, text)| {
11774 (range, text.to_string().map(Arc::<str>::from))
11775 }),
11776 None,
11777 cx,
11778 );
11779 });
11780 }
11781 }
11782 });
11783 self.change_selections(None, cx, |selections| selections.refresh());
11784 }
11785
11786 pub fn to_pixel_point(
11787 &mut self,
11788 source: multi_buffer::Anchor,
11789 editor_snapshot: &EditorSnapshot,
11790 cx: &mut ViewContext<Self>,
11791 ) -> Option<gpui::Point<Pixels>> {
11792 let text_layout_details = self.text_layout_details(cx);
11793 let line_height = text_layout_details
11794 .editor_style
11795 .text
11796 .line_height_in_pixels(cx.rem_size());
11797 let source_point = source.to_display_point(editor_snapshot);
11798 let first_visible_line = text_layout_details
11799 .scroll_anchor
11800 .anchor
11801 .to_display_point(editor_snapshot);
11802 if first_visible_line > source_point {
11803 return None;
11804 }
11805 let source_x = editor_snapshot.x_for_display_point(source_point, &text_layout_details);
11806 let source_y = line_height
11807 * ((source_point.row() - first_visible_line.row()).0 as f32
11808 - text_layout_details.scroll_anchor.offset.y);
11809 Some(gpui::Point::new(source_x, source_y))
11810 }
11811
11812 pub fn display_to_pixel_point(
11813 &mut self,
11814 source: DisplayPoint,
11815 editor_snapshot: &EditorSnapshot,
11816 cx: &mut ViewContext<Self>,
11817 ) -> Option<gpui::Point<Pixels>> {
11818 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
11819 let text_layout_details = self.text_layout_details(cx);
11820 let first_visible_line = text_layout_details
11821 .scroll_anchor
11822 .anchor
11823 .to_display_point(editor_snapshot);
11824 if first_visible_line > source {
11825 return None;
11826 }
11827 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
11828 let source_y = line_height * (source.row() - first_visible_line.row()).0 as f32;
11829 Some(gpui::Point::new(source_x, source_y))
11830 }
11831}
11832
11833fn hunks_for_selections(
11834 multi_buffer_snapshot: &MultiBufferSnapshot,
11835 selections: &[Selection<Anchor>],
11836) -> Vec<DiffHunk<MultiBufferRow>> {
11837 let buffer_rows_for_selections = selections.iter().map(|selection| {
11838 let head = selection.head();
11839 let tail = selection.tail();
11840 let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
11841 let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
11842 if start > end {
11843 end..start
11844 } else {
11845 start..end
11846 }
11847 });
11848
11849 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
11850}
11851
11852pub fn hunks_for_rows(
11853 rows: impl Iterator<Item = Range<MultiBufferRow>>,
11854 multi_buffer_snapshot: &MultiBufferSnapshot,
11855) -> Vec<DiffHunk<MultiBufferRow>> {
11856 let mut hunks = Vec::new();
11857 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
11858 HashMap::default();
11859 for selected_multi_buffer_rows in rows {
11860 let query_rows =
11861 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
11862 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
11863 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
11864 // when the caret is just above or just below the deleted hunk.
11865 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
11866 let related_to_selection = if allow_adjacent {
11867 hunk.associated_range.overlaps(&query_rows)
11868 || hunk.associated_range.start == query_rows.end
11869 || hunk.associated_range.end == query_rows.start
11870 } else {
11871 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
11872 // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
11873 hunk.associated_range.overlaps(&selected_multi_buffer_rows)
11874 || selected_multi_buffer_rows.end == hunk.associated_range.start
11875 };
11876 if related_to_selection {
11877 if !processed_buffer_rows
11878 .entry(hunk.buffer_id)
11879 .or_default()
11880 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
11881 {
11882 continue;
11883 }
11884 hunks.push(hunk);
11885 }
11886 }
11887 }
11888
11889 hunks
11890}
11891
11892pub trait CollaborationHub {
11893 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
11894 fn user_participant_indices<'a>(
11895 &self,
11896 cx: &'a AppContext,
11897 ) -> &'a HashMap<u64, ParticipantIndex>;
11898 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
11899}
11900
11901impl CollaborationHub for Model<Project> {
11902 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
11903 self.read(cx).collaborators()
11904 }
11905
11906 fn user_participant_indices<'a>(
11907 &self,
11908 cx: &'a AppContext,
11909 ) -> &'a HashMap<u64, ParticipantIndex> {
11910 self.read(cx).user_store().read(cx).participant_indices()
11911 }
11912
11913 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
11914 let this = self.read(cx);
11915 let user_ids = this.collaborators().values().map(|c| c.user_id);
11916 this.user_store().read_with(cx, |user_store, cx| {
11917 user_store.participant_names(user_ids, cx)
11918 })
11919 }
11920}
11921
11922pub trait CompletionProvider {
11923 fn completions(
11924 &self,
11925 buffer: &Model<Buffer>,
11926 buffer_position: text::Anchor,
11927 trigger: CompletionContext,
11928 cx: &mut ViewContext<Editor>,
11929 ) -> Task<Result<Vec<Completion>>>;
11930
11931 fn resolve_completions(
11932 &self,
11933 buffer: Model<Buffer>,
11934 completion_indices: Vec<usize>,
11935 completions: Arc<RwLock<Box<[Completion]>>>,
11936 cx: &mut ViewContext<Editor>,
11937 ) -> Task<Result<bool>>;
11938
11939 fn apply_additional_edits_for_completion(
11940 &self,
11941 buffer: Model<Buffer>,
11942 completion: Completion,
11943 push_to_history: bool,
11944 cx: &mut ViewContext<Editor>,
11945 ) -> Task<Result<Option<language::Transaction>>>;
11946
11947 fn is_completion_trigger(
11948 &self,
11949 buffer: &Model<Buffer>,
11950 position: language::Anchor,
11951 text: &str,
11952 trigger_in_words: bool,
11953 cx: &mut ViewContext<Editor>,
11954 ) -> bool;
11955}
11956
11957fn snippet_completions(
11958 project: &Project,
11959 buffer: &Model<Buffer>,
11960 buffer_position: text::Anchor,
11961 cx: &mut AppContext,
11962) -> Vec<Completion> {
11963 let language = buffer.read(cx).language_at(buffer_position);
11964 let language_name = language.as_ref().map(|language| language.lsp_id());
11965 let snippet_store = project.snippets().read(cx);
11966 let snippets = snippet_store.snippets_for(language_name, cx);
11967
11968 if snippets.is_empty() {
11969 return vec![];
11970 }
11971 let snapshot = buffer.read(cx).text_snapshot();
11972 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
11973
11974 let mut lines = chunks.lines();
11975 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
11976 return vec![];
11977 };
11978
11979 let scope = language.map(|language| language.default_scope());
11980 let mut last_word = line_at
11981 .chars()
11982 .rev()
11983 .take_while(|c| char_kind(&scope, *c) == CharKind::Word)
11984 .collect::<String>();
11985 last_word = last_word.chars().rev().collect();
11986 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
11987 let to_lsp = |point: &text::Anchor| {
11988 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
11989 point_to_lsp(end)
11990 };
11991 let lsp_end = to_lsp(&buffer_position);
11992 snippets
11993 .into_iter()
11994 .filter_map(|snippet| {
11995 let matching_prefix = snippet
11996 .prefix
11997 .iter()
11998 .find(|prefix| prefix.starts_with(&last_word))?;
11999 let start = as_offset - last_word.len();
12000 let start = snapshot.anchor_before(start);
12001 let range = start..buffer_position;
12002 let lsp_start = to_lsp(&start);
12003 let lsp_range = lsp::Range {
12004 start: lsp_start,
12005 end: lsp_end,
12006 };
12007 Some(Completion {
12008 old_range: range,
12009 new_text: snippet.body.clone(),
12010 label: CodeLabel {
12011 text: matching_prefix.clone(),
12012 runs: vec![],
12013 filter_range: 0..matching_prefix.len(),
12014 },
12015 server_id: LanguageServerId(usize::MAX),
12016 documentation: snippet
12017 .description
12018 .clone()
12019 .map(|description| Documentation::SingleLine(description)),
12020 lsp_completion: lsp::CompletionItem {
12021 label: snippet.prefix.first().unwrap().clone(),
12022 kind: Some(CompletionItemKind::SNIPPET),
12023 label_details: snippet.description.as_ref().map(|description| {
12024 lsp::CompletionItemLabelDetails {
12025 detail: Some(description.clone()),
12026 description: None,
12027 }
12028 }),
12029 insert_text_format: Some(InsertTextFormat::SNIPPET),
12030 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12031 lsp::InsertReplaceEdit {
12032 new_text: snippet.body.clone(),
12033 insert: lsp_range,
12034 replace: lsp_range,
12035 },
12036 )),
12037 filter_text: Some(snippet.body.clone()),
12038 sort_text: Some(char::MAX.to_string()),
12039 ..Default::default()
12040 },
12041 confirm: None,
12042 show_new_completions_on_confirm: false,
12043 })
12044 })
12045 .collect()
12046}
12047
12048impl CompletionProvider for Model<Project> {
12049 fn completions(
12050 &self,
12051 buffer: &Model<Buffer>,
12052 buffer_position: text::Anchor,
12053 options: CompletionContext,
12054 cx: &mut ViewContext<Editor>,
12055 ) -> Task<Result<Vec<Completion>>> {
12056 self.update(cx, |project, cx| {
12057 let snippets = snippet_completions(project, buffer, buffer_position, cx);
12058 let project_completions = project.completions(&buffer, buffer_position, options, cx);
12059 cx.background_executor().spawn(async move {
12060 let mut completions = project_completions.await?;
12061 //let snippets = snippets.into_iter().;
12062 completions.extend(snippets);
12063 Ok(completions)
12064 })
12065 })
12066 }
12067
12068 fn resolve_completions(
12069 &self,
12070 buffer: Model<Buffer>,
12071 completion_indices: Vec<usize>,
12072 completions: Arc<RwLock<Box<[Completion]>>>,
12073 cx: &mut ViewContext<Editor>,
12074 ) -> Task<Result<bool>> {
12075 self.update(cx, |project, cx| {
12076 project.resolve_completions(buffer, completion_indices, completions, cx)
12077 })
12078 }
12079
12080 fn apply_additional_edits_for_completion(
12081 &self,
12082 buffer: Model<Buffer>,
12083 completion: Completion,
12084 push_to_history: bool,
12085 cx: &mut ViewContext<Editor>,
12086 ) -> Task<Result<Option<language::Transaction>>> {
12087 self.update(cx, |project, cx| {
12088 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12089 })
12090 }
12091
12092 fn is_completion_trigger(
12093 &self,
12094 buffer: &Model<Buffer>,
12095 position: language::Anchor,
12096 text: &str,
12097 trigger_in_words: bool,
12098 cx: &mut ViewContext<Editor>,
12099 ) -> bool {
12100 if !EditorSettings::get_global(cx).show_completions_on_input {
12101 return false;
12102 }
12103
12104 let mut chars = text.chars();
12105 let char = if let Some(char) = chars.next() {
12106 char
12107 } else {
12108 return false;
12109 };
12110 if chars.next().is_some() {
12111 return false;
12112 }
12113
12114 let buffer = buffer.read(cx);
12115 let scope = buffer.snapshot().language_scope_at(position);
12116 if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
12117 return true;
12118 }
12119
12120 buffer
12121 .completion_triggers()
12122 .iter()
12123 .any(|string| string == text)
12124 }
12125}
12126
12127fn inlay_hint_settings(
12128 location: Anchor,
12129 snapshot: &MultiBufferSnapshot,
12130 cx: &mut ViewContext<'_, Editor>,
12131) -> InlayHintSettings {
12132 let file = snapshot.file_at(location);
12133 let language = snapshot.language_at(location);
12134 let settings = all_language_settings(file, cx);
12135 settings
12136 .language(language.map(|l| l.name()).as_deref())
12137 .inlay_hints
12138}
12139
12140fn consume_contiguous_rows(
12141 contiguous_row_selections: &mut Vec<Selection<Point>>,
12142 selection: &Selection<Point>,
12143 display_map: &DisplaySnapshot,
12144 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12145) -> (MultiBufferRow, MultiBufferRow) {
12146 contiguous_row_selections.push(selection.clone());
12147 let start_row = MultiBufferRow(selection.start.row);
12148 let mut end_row = ending_row(selection, display_map);
12149
12150 while let Some(next_selection) = selections.peek() {
12151 if next_selection.start.row <= end_row.0 {
12152 end_row = ending_row(next_selection, display_map);
12153 contiguous_row_selections.push(selections.next().unwrap().clone());
12154 } else {
12155 break;
12156 }
12157 }
12158 (start_row, end_row)
12159}
12160
12161fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12162 if next_selection.end.column > 0 || next_selection.is_empty() {
12163 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12164 } else {
12165 MultiBufferRow(next_selection.end.row)
12166 }
12167}
12168
12169impl EditorSnapshot {
12170 pub fn remote_selections_in_range<'a>(
12171 &'a self,
12172 range: &'a Range<Anchor>,
12173 collaboration_hub: &dyn CollaborationHub,
12174 cx: &'a AppContext,
12175 ) -> impl 'a + Iterator<Item = RemoteSelection> {
12176 let participant_names = collaboration_hub.user_names(cx);
12177 let participant_indices = collaboration_hub.user_participant_indices(cx);
12178 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12179 let collaborators_by_replica_id = collaborators_by_peer_id
12180 .iter()
12181 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12182 .collect::<HashMap<_, _>>();
12183 self.buffer_snapshot
12184 .selections_in_range(range, false)
12185 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12186 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12187 let participant_index = participant_indices.get(&collaborator.user_id).copied();
12188 let user_name = participant_names.get(&collaborator.user_id).cloned();
12189 Some(RemoteSelection {
12190 replica_id,
12191 selection,
12192 cursor_shape,
12193 line_mode,
12194 participant_index,
12195 peer_id: collaborator.peer_id,
12196 user_name,
12197 })
12198 })
12199 }
12200
12201 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12202 self.display_snapshot.buffer_snapshot.language_at(position)
12203 }
12204
12205 pub fn is_focused(&self) -> bool {
12206 self.is_focused
12207 }
12208
12209 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12210 self.placeholder_text.as_ref()
12211 }
12212
12213 pub fn scroll_position(&self) -> gpui::Point<f32> {
12214 self.scroll_anchor.scroll_position(&self.display_snapshot)
12215 }
12216
12217 pub fn gutter_dimensions(
12218 &self,
12219 font_id: FontId,
12220 font_size: Pixels,
12221 em_width: Pixels,
12222 max_line_number_width: Pixels,
12223 cx: &AppContext,
12224 ) -> GutterDimensions {
12225 if !self.show_gutter {
12226 return GutterDimensions::default();
12227 }
12228 let descent = cx.text_system().descent(font_id, font_size);
12229
12230 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12231 matches!(
12232 ProjectSettings::get_global(cx).git.git_gutter,
12233 Some(GitGutterSetting::TrackedFiles)
12234 )
12235 });
12236 let gutter_settings = EditorSettings::get_global(cx).gutter;
12237 let show_line_numbers = self
12238 .show_line_numbers
12239 .unwrap_or(gutter_settings.line_numbers);
12240 let line_gutter_width = if show_line_numbers {
12241 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12242 let min_width_for_number_on_gutter = em_width * 4.0;
12243 max_line_number_width.max(min_width_for_number_on_gutter)
12244 } else {
12245 0.0.into()
12246 };
12247
12248 let show_code_actions = self
12249 .show_code_actions
12250 .unwrap_or(gutter_settings.code_actions);
12251
12252 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12253
12254 let git_blame_entries_width = self
12255 .render_git_blame_gutter
12256 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12257
12258 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12259 left_padding += if show_code_actions || show_runnables {
12260 em_width * 3.0
12261 } else if show_git_gutter && show_line_numbers {
12262 em_width * 2.0
12263 } else if show_git_gutter || show_line_numbers {
12264 em_width
12265 } else {
12266 px(0.)
12267 };
12268
12269 let right_padding = if gutter_settings.folds && show_line_numbers {
12270 em_width * 4.0
12271 } else if gutter_settings.folds {
12272 em_width * 3.0
12273 } else if show_line_numbers {
12274 em_width
12275 } else {
12276 px(0.)
12277 };
12278
12279 GutterDimensions {
12280 left_padding,
12281 right_padding,
12282 width: line_gutter_width + left_padding + right_padding,
12283 margin: -descent,
12284 git_blame_entries_width,
12285 }
12286 }
12287
12288 pub fn render_fold_toggle(
12289 &self,
12290 buffer_row: MultiBufferRow,
12291 row_contains_cursor: bool,
12292 editor: View<Editor>,
12293 cx: &mut WindowContext,
12294 ) -> Option<AnyElement> {
12295 let folded = self.is_line_folded(buffer_row);
12296
12297 if let Some(crease) = self
12298 .crease_snapshot
12299 .query_row(buffer_row, &self.buffer_snapshot)
12300 {
12301 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12302 if folded {
12303 editor.update(cx, |editor, cx| {
12304 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12305 });
12306 } else {
12307 editor.update(cx, |editor, cx| {
12308 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12309 });
12310 }
12311 });
12312
12313 Some((crease.render_toggle)(
12314 buffer_row,
12315 folded,
12316 toggle_callback,
12317 cx,
12318 ))
12319 } else if folded
12320 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12321 {
12322 Some(
12323 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12324 .selected(folded)
12325 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12326 if folded {
12327 this.unfold_at(&UnfoldAt { buffer_row }, cx);
12328 } else {
12329 this.fold_at(&FoldAt { buffer_row }, cx);
12330 }
12331 }))
12332 .into_any_element(),
12333 )
12334 } else {
12335 None
12336 }
12337 }
12338
12339 pub fn render_crease_trailer(
12340 &self,
12341 buffer_row: MultiBufferRow,
12342 cx: &mut WindowContext,
12343 ) -> Option<AnyElement> {
12344 let folded = self.is_line_folded(buffer_row);
12345 let crease = self
12346 .crease_snapshot
12347 .query_row(buffer_row, &self.buffer_snapshot)?;
12348 Some((crease.render_trailer)(buffer_row, folded, cx))
12349 }
12350}
12351
12352impl Deref for EditorSnapshot {
12353 type Target = DisplaySnapshot;
12354
12355 fn deref(&self) -> &Self::Target {
12356 &self.display_snapshot
12357 }
12358}
12359
12360#[derive(Clone, Debug, PartialEq, Eq)]
12361pub enum EditorEvent {
12362 InputIgnored {
12363 text: Arc<str>,
12364 },
12365 InputHandled {
12366 utf16_range_to_replace: Option<Range<isize>>,
12367 text: Arc<str>,
12368 },
12369 ExcerptsAdded {
12370 buffer: Model<Buffer>,
12371 predecessor: ExcerptId,
12372 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12373 },
12374 ExcerptsRemoved {
12375 ids: Vec<ExcerptId>,
12376 },
12377 ExcerptsEdited {
12378 ids: Vec<ExcerptId>,
12379 },
12380 ExcerptsExpanded {
12381 ids: Vec<ExcerptId>,
12382 },
12383 BufferEdited,
12384 Edited {
12385 transaction_id: clock::Lamport,
12386 },
12387 Reparsed(BufferId),
12388 Focused,
12389 FocusedIn,
12390 Blurred,
12391 DirtyChanged,
12392 Saved,
12393 TitleChanged,
12394 DiffBaseChanged,
12395 SelectionsChanged {
12396 local: bool,
12397 },
12398 ScrollPositionChanged {
12399 local: bool,
12400 autoscroll: bool,
12401 },
12402 Closed,
12403 TransactionUndone {
12404 transaction_id: clock::Lamport,
12405 },
12406 TransactionBegun {
12407 transaction_id: clock::Lamport,
12408 },
12409}
12410
12411impl EventEmitter<EditorEvent> for Editor {}
12412
12413impl FocusableView for Editor {
12414 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12415 self.focus_handle.clone()
12416 }
12417}
12418
12419impl Render for Editor {
12420 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12421 let settings = ThemeSettings::get_global(cx);
12422
12423 let text_style = match self.mode {
12424 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12425 color: cx.theme().colors().editor_foreground,
12426 font_family: settings.ui_font.family.clone(),
12427 font_features: settings.ui_font.features.clone(),
12428 font_size: rems(0.875).into(),
12429 font_weight: settings.ui_font.weight,
12430 font_style: FontStyle::Normal,
12431 line_height: relative(settings.buffer_line_height.value()),
12432 background_color: None,
12433 underline: None,
12434 strikethrough: None,
12435 white_space: WhiteSpace::Normal,
12436 },
12437 EditorMode::Full => TextStyle {
12438 color: cx.theme().colors().editor_foreground,
12439 font_family: settings.buffer_font.family.clone(),
12440 font_features: settings.buffer_font.features.clone(),
12441 font_size: settings.buffer_font_size(cx).into(),
12442 font_weight: settings.buffer_font.weight,
12443 font_style: FontStyle::Normal,
12444 line_height: relative(settings.buffer_line_height.value()),
12445 background_color: None,
12446 underline: None,
12447 strikethrough: None,
12448 white_space: WhiteSpace::Normal,
12449 },
12450 };
12451
12452 let background = match self.mode {
12453 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12454 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12455 EditorMode::Full => cx.theme().colors().editor_background,
12456 };
12457
12458 EditorElement::new(
12459 cx.view(),
12460 EditorStyle {
12461 background,
12462 local_player: cx.theme().players().local(),
12463 text: text_style,
12464 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12465 syntax: cx.theme().syntax().clone(),
12466 status: cx.theme().status().clone(),
12467 inlay_hints_style: HighlightStyle {
12468 color: Some(cx.theme().status().hint),
12469 ..HighlightStyle::default()
12470 },
12471 suggestions_style: HighlightStyle {
12472 color: Some(cx.theme().status().predictive),
12473 ..HighlightStyle::default()
12474 },
12475 },
12476 )
12477 }
12478}
12479
12480impl ViewInputHandler for Editor {
12481 fn text_for_range(
12482 &mut self,
12483 range_utf16: Range<usize>,
12484 cx: &mut ViewContext<Self>,
12485 ) -> Option<String> {
12486 Some(
12487 self.buffer
12488 .read(cx)
12489 .read(cx)
12490 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12491 .collect(),
12492 )
12493 }
12494
12495 fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12496 // Prevent the IME menu from appearing when holding down an alphabetic key
12497 // while input is disabled.
12498 if !self.input_enabled {
12499 return None;
12500 }
12501
12502 let range = self.selections.newest::<OffsetUtf16>(cx).range();
12503 Some(range.start.0..range.end.0)
12504 }
12505
12506 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12507 let snapshot = self.buffer.read(cx).read(cx);
12508 let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
12509 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12510 }
12511
12512 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12513 self.clear_highlights::<InputComposition>(cx);
12514 self.ime_transaction.take();
12515 }
12516
12517 fn replace_text_in_range(
12518 &mut self,
12519 range_utf16: Option<Range<usize>>,
12520 text: &str,
12521 cx: &mut ViewContext<Self>,
12522 ) {
12523 if !self.input_enabled {
12524 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12525 return;
12526 }
12527
12528 self.transact(cx, |this, cx| {
12529 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12530 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12531 Some(this.selection_replacement_ranges(range_utf16, cx))
12532 } else {
12533 this.marked_text_ranges(cx)
12534 };
12535
12536 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12537 let newest_selection_id = this.selections.newest_anchor().id;
12538 this.selections
12539 .all::<OffsetUtf16>(cx)
12540 .iter()
12541 .zip(ranges_to_replace.iter())
12542 .find_map(|(selection, range)| {
12543 if selection.id == newest_selection_id {
12544 Some(
12545 (range.start.0 as isize - selection.head().0 as isize)
12546 ..(range.end.0 as isize - selection.head().0 as isize),
12547 )
12548 } else {
12549 None
12550 }
12551 })
12552 });
12553
12554 cx.emit(EditorEvent::InputHandled {
12555 utf16_range_to_replace: range_to_replace,
12556 text: text.into(),
12557 });
12558
12559 if let Some(new_selected_ranges) = new_selected_ranges {
12560 this.change_selections(None, cx, |selections| {
12561 selections.select_ranges(new_selected_ranges)
12562 });
12563 this.backspace(&Default::default(), cx);
12564 }
12565
12566 this.handle_input(text, cx);
12567 });
12568
12569 if let Some(transaction) = self.ime_transaction {
12570 self.buffer.update(cx, |buffer, cx| {
12571 buffer.group_until_transaction(transaction, cx);
12572 });
12573 }
12574
12575 self.unmark_text(cx);
12576 }
12577
12578 fn replace_and_mark_text_in_range(
12579 &mut self,
12580 range_utf16: Option<Range<usize>>,
12581 text: &str,
12582 new_selected_range_utf16: Option<Range<usize>>,
12583 cx: &mut ViewContext<Self>,
12584 ) {
12585 if !self.input_enabled {
12586 return;
12587 }
12588
12589 let transaction = self.transact(cx, |this, cx| {
12590 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12591 let snapshot = this.buffer.read(cx).read(cx);
12592 if let Some(relative_range_utf16) = range_utf16.as_ref() {
12593 for marked_range in &mut marked_ranges {
12594 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12595 marked_range.start.0 += relative_range_utf16.start;
12596 marked_range.start =
12597 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12598 marked_range.end =
12599 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12600 }
12601 }
12602 Some(marked_ranges)
12603 } else if let Some(range_utf16) = range_utf16 {
12604 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12605 Some(this.selection_replacement_ranges(range_utf16, cx))
12606 } else {
12607 None
12608 };
12609
12610 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12611 let newest_selection_id = this.selections.newest_anchor().id;
12612 this.selections
12613 .all::<OffsetUtf16>(cx)
12614 .iter()
12615 .zip(ranges_to_replace.iter())
12616 .find_map(|(selection, range)| {
12617 if selection.id == newest_selection_id {
12618 Some(
12619 (range.start.0 as isize - selection.head().0 as isize)
12620 ..(range.end.0 as isize - selection.head().0 as isize),
12621 )
12622 } else {
12623 None
12624 }
12625 })
12626 });
12627
12628 cx.emit(EditorEvent::InputHandled {
12629 utf16_range_to_replace: range_to_replace,
12630 text: text.into(),
12631 });
12632
12633 if let Some(ranges) = ranges_to_replace {
12634 this.change_selections(None, cx, |s| s.select_ranges(ranges));
12635 }
12636
12637 let marked_ranges = {
12638 let snapshot = this.buffer.read(cx).read(cx);
12639 this.selections
12640 .disjoint_anchors()
12641 .iter()
12642 .map(|selection| {
12643 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12644 })
12645 .collect::<Vec<_>>()
12646 };
12647
12648 if text.is_empty() {
12649 this.unmark_text(cx);
12650 } else {
12651 this.highlight_text::<InputComposition>(
12652 marked_ranges.clone(),
12653 HighlightStyle {
12654 underline: Some(UnderlineStyle {
12655 thickness: px(1.),
12656 color: None,
12657 wavy: false,
12658 }),
12659 ..Default::default()
12660 },
12661 cx,
12662 );
12663 }
12664
12665 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12666 let use_autoclose = this.use_autoclose;
12667 let use_auto_surround = this.use_auto_surround;
12668 this.set_use_autoclose(false);
12669 this.set_use_auto_surround(false);
12670 this.handle_input(text, cx);
12671 this.set_use_autoclose(use_autoclose);
12672 this.set_use_auto_surround(use_auto_surround);
12673
12674 if let Some(new_selected_range) = new_selected_range_utf16 {
12675 let snapshot = this.buffer.read(cx).read(cx);
12676 let new_selected_ranges = marked_ranges
12677 .into_iter()
12678 .map(|marked_range| {
12679 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
12680 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
12681 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
12682 snapshot.clip_offset_utf16(new_start, Bias::Left)
12683 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
12684 })
12685 .collect::<Vec<_>>();
12686
12687 drop(snapshot);
12688 this.change_selections(None, cx, |selections| {
12689 selections.select_ranges(new_selected_ranges)
12690 });
12691 }
12692 });
12693
12694 self.ime_transaction = self.ime_transaction.or(transaction);
12695 if let Some(transaction) = self.ime_transaction {
12696 self.buffer.update(cx, |buffer, cx| {
12697 buffer.group_until_transaction(transaction, cx);
12698 });
12699 }
12700
12701 if self.text_highlights::<InputComposition>(cx).is_none() {
12702 self.ime_transaction.take();
12703 }
12704 }
12705
12706 fn bounds_for_range(
12707 &mut self,
12708 range_utf16: Range<usize>,
12709 element_bounds: gpui::Bounds<Pixels>,
12710 cx: &mut ViewContext<Self>,
12711 ) -> Option<gpui::Bounds<Pixels>> {
12712 let text_layout_details = self.text_layout_details(cx);
12713 let style = &text_layout_details.editor_style;
12714 let font_id = cx.text_system().resolve_font(&style.text.font());
12715 let font_size = style.text.font_size.to_pixels(cx.rem_size());
12716 let line_height = style.text.line_height_in_pixels(cx.rem_size());
12717
12718 let em_width = cx
12719 .text_system()
12720 .typographic_bounds(font_id, font_size, 'm')
12721 .unwrap()
12722 .size
12723 .width;
12724
12725 let snapshot = self.snapshot(cx);
12726 let scroll_position = snapshot.scroll_position();
12727 let scroll_left = scroll_position.x * em_width;
12728
12729 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
12730 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
12731 + self.gutter_dimensions.width;
12732 let y = line_height * (start.row().as_f32() - scroll_position.y);
12733
12734 Some(Bounds {
12735 origin: element_bounds.origin + point(x, y),
12736 size: size(em_width, line_height),
12737 })
12738 }
12739}
12740
12741trait SelectionExt {
12742 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
12743 fn spanned_rows(
12744 &self,
12745 include_end_if_at_line_start: bool,
12746 map: &DisplaySnapshot,
12747 ) -> Range<MultiBufferRow>;
12748}
12749
12750impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
12751 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
12752 let start = self
12753 .start
12754 .to_point(&map.buffer_snapshot)
12755 .to_display_point(map);
12756 let end = self
12757 .end
12758 .to_point(&map.buffer_snapshot)
12759 .to_display_point(map);
12760 if self.reversed {
12761 end..start
12762 } else {
12763 start..end
12764 }
12765 }
12766
12767 fn spanned_rows(
12768 &self,
12769 include_end_if_at_line_start: bool,
12770 map: &DisplaySnapshot,
12771 ) -> Range<MultiBufferRow> {
12772 let start = self.start.to_point(&map.buffer_snapshot);
12773 let mut end = self.end.to_point(&map.buffer_snapshot);
12774 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
12775 end.row -= 1;
12776 }
12777
12778 let buffer_start = map.prev_line_boundary(start).0;
12779 let buffer_end = map.next_line_boundary(end).0;
12780 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
12781 }
12782}
12783
12784impl<T: InvalidationRegion> InvalidationStack<T> {
12785 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
12786 where
12787 S: Clone + ToOffset,
12788 {
12789 while let Some(region) = self.last() {
12790 let all_selections_inside_invalidation_ranges =
12791 if selections.len() == region.ranges().len() {
12792 selections
12793 .iter()
12794 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
12795 .all(|(selection, invalidation_range)| {
12796 let head = selection.head().to_offset(buffer);
12797 invalidation_range.start <= head && invalidation_range.end >= head
12798 })
12799 } else {
12800 false
12801 };
12802
12803 if all_selections_inside_invalidation_ranges {
12804 break;
12805 } else {
12806 self.pop();
12807 }
12808 }
12809 }
12810}
12811
12812impl<T> Default for InvalidationStack<T> {
12813 fn default() -> Self {
12814 Self(Default::default())
12815 }
12816}
12817
12818impl<T> Deref for InvalidationStack<T> {
12819 type Target = Vec<T>;
12820
12821 fn deref(&self) -> &Self::Target {
12822 &self.0
12823 }
12824}
12825
12826impl<T> DerefMut for InvalidationStack<T> {
12827 fn deref_mut(&mut self) -> &mut Self::Target {
12828 &mut self.0
12829 }
12830}
12831
12832impl InvalidationRegion for SnippetState {
12833 fn ranges(&self) -> &[Range<Anchor>] {
12834 &self.ranges[self.active_index]
12835 }
12836}
12837
12838pub fn diagnostic_block_renderer(
12839 diagnostic: Diagnostic,
12840 max_message_rows: Option<u8>,
12841 allow_closing: bool,
12842 _is_valid: bool,
12843) -> RenderBlock {
12844 let (text_without_backticks, code_ranges) =
12845 highlight_diagnostic_message(&diagnostic, max_message_rows);
12846
12847 Box::new(move |cx: &mut BlockContext| {
12848 let group_id: SharedString = cx.block_id.to_string().into();
12849
12850 let mut text_style = cx.text_style().clone();
12851 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
12852 let theme_settings = ThemeSettings::get_global(cx);
12853 text_style.font_family = theme_settings.buffer_font.family.clone();
12854 text_style.font_style = theme_settings.buffer_font.style;
12855 text_style.font_features = theme_settings.buffer_font.features.clone();
12856 text_style.font_weight = theme_settings.buffer_font.weight;
12857
12858 let multi_line_diagnostic = diagnostic.message.contains('\n');
12859
12860 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
12861 if multi_line_diagnostic {
12862 v_flex()
12863 } else {
12864 h_flex()
12865 }
12866 .when(allow_closing, |div| {
12867 div.children(diagnostic.is_primary.then(|| {
12868 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
12869 .icon_color(Color::Muted)
12870 .size(ButtonSize::Compact)
12871 .style(ButtonStyle::Transparent)
12872 .visible_on_hover(group_id.clone())
12873 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
12874 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
12875 }))
12876 })
12877 .child(
12878 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
12879 .icon_color(Color::Muted)
12880 .size(ButtonSize::Compact)
12881 .style(ButtonStyle::Transparent)
12882 .visible_on_hover(group_id.clone())
12883 .on_click({
12884 let message = diagnostic.message.clone();
12885 move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
12886 })
12887 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
12888 )
12889 };
12890
12891 let icon_size = buttons(&diagnostic, cx.block_id)
12892 .into_any_element()
12893 .layout_as_root(AvailableSpace::min_size(), cx);
12894
12895 h_flex()
12896 .id(cx.block_id)
12897 .group(group_id.clone())
12898 .relative()
12899 .size_full()
12900 .pl(cx.gutter_dimensions.width)
12901 .w(cx.max_width + cx.gutter_dimensions.width)
12902 .child(
12903 div()
12904 .flex()
12905 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
12906 .flex_shrink(),
12907 )
12908 .child(buttons(&diagnostic, cx.block_id))
12909 .child(div().flex().flex_shrink_0().child(
12910 StyledText::new(text_without_backticks.clone()).with_highlights(
12911 &text_style,
12912 code_ranges.iter().map(|range| {
12913 (
12914 range.clone(),
12915 HighlightStyle {
12916 font_weight: Some(FontWeight::BOLD),
12917 ..Default::default()
12918 },
12919 )
12920 }),
12921 ),
12922 ))
12923 .into_any_element()
12924 })
12925}
12926
12927pub fn highlight_diagnostic_message(
12928 diagnostic: &Diagnostic,
12929 mut max_message_rows: Option<u8>,
12930) -> (SharedString, Vec<Range<usize>>) {
12931 let mut text_without_backticks = String::new();
12932 let mut code_ranges = Vec::new();
12933
12934 if let Some(source) = &diagnostic.source {
12935 text_without_backticks.push_str(&source);
12936 code_ranges.push(0..source.len());
12937 text_without_backticks.push_str(": ");
12938 }
12939
12940 let mut prev_offset = 0;
12941 let mut in_code_block = false;
12942 let has_row_limit = max_message_rows.is_some();
12943 let mut newline_indices = diagnostic
12944 .message
12945 .match_indices('\n')
12946 .filter(|_| has_row_limit)
12947 .map(|(ix, _)| ix)
12948 .fuse()
12949 .peekable();
12950
12951 for (quote_ix, _) in diagnostic
12952 .message
12953 .match_indices('`')
12954 .chain([(diagnostic.message.len(), "")])
12955 {
12956 let mut first_newline_ix = None;
12957 let mut last_newline_ix = None;
12958 while let Some(newline_ix) = newline_indices.peek() {
12959 if *newline_ix < quote_ix {
12960 if first_newline_ix.is_none() {
12961 first_newline_ix = Some(*newline_ix);
12962 }
12963 last_newline_ix = Some(*newline_ix);
12964
12965 if let Some(rows_left) = &mut max_message_rows {
12966 if *rows_left == 0 {
12967 break;
12968 } else {
12969 *rows_left -= 1;
12970 }
12971 }
12972 let _ = newline_indices.next();
12973 } else {
12974 break;
12975 }
12976 }
12977 let prev_len = text_without_backticks.len();
12978 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
12979 text_without_backticks.push_str(new_text);
12980 if in_code_block {
12981 code_ranges.push(prev_len..text_without_backticks.len());
12982 }
12983 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
12984 in_code_block = !in_code_block;
12985 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
12986 text_without_backticks.push_str("...");
12987 break;
12988 }
12989 }
12990
12991 (text_without_backticks.into(), code_ranges)
12992}
12993
12994fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
12995 match severity {
12996 DiagnosticSeverity::ERROR => colors.error,
12997 DiagnosticSeverity::WARNING => colors.warning,
12998 DiagnosticSeverity::INFORMATION => colors.info,
12999 DiagnosticSeverity::HINT => colors.info,
13000 _ => colors.ignored,
13001 }
13002}
13003
13004pub fn styled_runs_for_code_label<'a>(
13005 label: &'a CodeLabel,
13006 syntax_theme: &'a theme::SyntaxTheme,
13007) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13008 let fade_out = HighlightStyle {
13009 fade_out: Some(0.35),
13010 ..Default::default()
13011 };
13012
13013 let mut prev_end = label.filter_range.end;
13014 label
13015 .runs
13016 .iter()
13017 .enumerate()
13018 .flat_map(move |(ix, (range, highlight_id))| {
13019 let style = if let Some(style) = highlight_id.style(syntax_theme) {
13020 style
13021 } else {
13022 return Default::default();
13023 };
13024 let mut muted_style = style;
13025 muted_style.highlight(fade_out);
13026
13027 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13028 if range.start >= label.filter_range.end {
13029 if range.start > prev_end {
13030 runs.push((prev_end..range.start, fade_out));
13031 }
13032 runs.push((range.clone(), muted_style));
13033 } else if range.end <= label.filter_range.end {
13034 runs.push((range.clone(), style));
13035 } else {
13036 runs.push((range.start..label.filter_range.end, style));
13037 runs.push((label.filter_range.end..range.end, muted_style));
13038 }
13039 prev_end = cmp::max(prev_end, range.end);
13040
13041 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13042 runs.push((prev_end..label.text.len(), fade_out));
13043 }
13044
13045 runs
13046 })
13047}
13048
13049pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13050 let mut prev_index = 0;
13051 let mut prev_codepoint: Option<char> = None;
13052 text.char_indices()
13053 .chain([(text.len(), '\0')])
13054 .filter_map(move |(index, codepoint)| {
13055 let prev_codepoint = prev_codepoint.replace(codepoint)?;
13056 let is_boundary = index == text.len()
13057 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13058 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13059 if is_boundary {
13060 let chunk = &text[prev_index..index];
13061 prev_index = index;
13062 Some(chunk)
13063 } else {
13064 None
13065 }
13066 })
13067}
13068
13069pub trait RangeToAnchorExt: Sized {
13070 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13071
13072 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13073 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13074 anchor_range.start.to_display_point(&snapshot)..anchor_range.end.to_display_point(&snapshot)
13075 }
13076}
13077
13078impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13079 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13080 let start_offset = self.start.to_offset(snapshot);
13081 let end_offset = self.end.to_offset(snapshot);
13082 if start_offset == end_offset {
13083 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13084 } else {
13085 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13086 }
13087 }
13088}
13089
13090pub trait RowExt {
13091 fn as_f32(&self) -> f32;
13092
13093 fn next_row(&self) -> Self;
13094
13095 fn previous_row(&self) -> Self;
13096
13097 fn minus(&self, other: Self) -> u32;
13098}
13099
13100impl RowExt for DisplayRow {
13101 fn as_f32(&self) -> f32 {
13102 self.0 as f32
13103 }
13104
13105 fn next_row(&self) -> Self {
13106 Self(self.0 + 1)
13107 }
13108
13109 fn previous_row(&self) -> Self {
13110 Self(self.0.saturating_sub(1))
13111 }
13112
13113 fn minus(&self, other: Self) -> u32 {
13114 self.0 - other.0
13115 }
13116}
13117
13118impl RowExt for MultiBufferRow {
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
13136trait RowRangeExt {
13137 type Row;
13138
13139 fn len(&self) -> usize;
13140
13141 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13142}
13143
13144impl RowRangeExt for Range<MultiBufferRow> {
13145 type Row = MultiBufferRow;
13146
13147 fn len(&self) -> usize {
13148 (self.end.0 - self.start.0) as usize
13149 }
13150
13151 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13152 (self.start.0..self.end.0).map(MultiBufferRow)
13153 }
13154}
13155
13156impl RowRangeExt for Range<DisplayRow> {
13157 type Row = DisplayRow;
13158
13159 fn len(&self) -> usize {
13160 (self.end.0 - self.start.0) as usize
13161 }
13162
13163 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13164 (self.start.0..self.end.0).map(DisplayRow)
13165 }
13166}
13167
13168fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13169 if hunk.diff_base_byte_range.is_empty() {
13170 DiffHunkStatus::Added
13171 } else if hunk.associated_range.is_empty() {
13172 DiffHunkStatus::Removed
13173 } else {
13174 DiffHunkStatus::Modified
13175 }
13176}