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;
18pub mod display_map;
19mod editor_settings;
20mod element;
21mod hunk_diff;
22mod inlay_hint_cache;
23
24mod debounced_delay;
25mod git;
26mod highlight_matching_bracket;
27mod hover_links;
28mod hover_popover;
29mod indent_guides;
30mod inline_completion_provider;
31pub mod items;
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;
42#[cfg(any(test, feature = "test-support"))]
43pub mod test;
44use ::git::diff::{DiffHunk, DiffHunkStatus};
45use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
46pub(crate) use actions::*;
47use aho_corasick::AhoCorasick;
48use anyhow::{anyhow, Context as _, Result};
49use blink_manager::BlinkManager;
50use client::{Collaborator, ParticipantIndex};
51use clock::ReplicaId;
52use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
53use convert_case::{Case, Casing};
54use debounced_delay::DebouncedDelay;
55use display_map::*;
56pub use display_map::{DisplayPoint, FoldPlaceholder};
57use editor_settings::CurrentLineHighlight;
58pub use editor_settings::EditorSettings;
59use element::LineWithInvisibles;
60pub use element::{
61 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
62};
63use futures::FutureExt;
64use fuzzy::{StringMatch, StringMatchCandidate};
65use git::blame::GitBlame;
66use git::diff_hunk_to_display;
67use gpui::{
68 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
69 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardItem,
70 Context, DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusableView, FontId, FontStyle,
71 FontWeight, HighlightStyle, Hsla, InteractiveText, KeyContext, ListSizingBehavior, Model,
72 MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, StrikethroughStyle,
73 Styled, StyledText, Subscription, Task, TextStyle, UnderlineStyle, UniformListScrollHandle,
74 View, ViewContext, ViewInputHandler, VisualContext, WeakView, WhiteSpace, WindowContext,
75};
76use highlight_matching_bracket::refresh_matching_bracket_highlights;
77use hover_popover::{hide_hover, HoverState};
78use hunk_diff::ExpandedHunks;
79pub(crate) use hunk_diff::HunkToExpand;
80use indent_guides::ActiveIndentGuidesState;
81use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
82pub use inline_completion_provider::*;
83pub use items::MAX_TAB_TITLE_LEN;
84use itertools::Itertools;
85use language::{
86 char_kind,
87 language_settings::{self, all_language_settings, InlayHintSettings},
88 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
89 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
90 Point, Selection, SelectionGoal, TransactionId,
91};
92use language::{BufferRow, Runnable, RunnableRange};
93use task::{ResolvedTask, TaskTemplate, TaskVariables};
94
95use hover_links::{HoverLink, HoveredLinkState, InlayHighlight};
96use lsp::{DiagnosticSeverity, LanguageServerId};
97use mouse_context_menu::MouseContextMenu;
98use movement::TextLayoutDetails;
99pub use multi_buffer::{
100 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
101 ToPoint,
102};
103use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
104use ordered_float::OrderedFloat;
105use parking_lot::{Mutex, RwLock};
106use project::project_settings::{GitGutterSetting, ProjectSettings};
107use project::{
108 CodeAction, Completion, FormatTrigger, Item, Location, Project, ProjectPath,
109 ProjectTransaction, TaskSourceKind, WorktreeId,
110};
111use rand::prelude::*;
112use rpc::{proto::*, ErrorExt};
113use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
114use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
115use serde::{Deserialize, Serialize};
116use settings::{Settings, SettingsStore};
117use smallvec::SmallVec;
118use snippet::Snippet;
119use std::ops::Not as _;
120use std::{
121 any::TypeId,
122 borrow::Cow,
123 cmp::{self, Ordering, Reverse},
124 mem,
125 num::NonZeroU32,
126 ops::{ControlFlow, Deref, DerefMut, Range, RangeInclusive},
127 path::Path,
128 sync::Arc,
129 time::{Duration, Instant},
130};
131pub use sum_tree::Bias;
132use sum_tree::TreeMap;
133use text::{BufferId, OffsetUtf16, Rope};
134use theme::{
135 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
136 ThemeColors, ThemeSettings,
137};
138use ui::{
139 h_flex, prelude::*, ButtonSize, ButtonStyle, IconButton, IconName, IconSize, ListItem, Popover,
140 Tooltip,
141};
142use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
143use workspace::item::{ItemHandle, PreviewTabsSettings};
144use workspace::notifications::{DetachAndPromptErr, NotificationId};
145use workspace::{
146 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
147};
148use workspace::{OpenInTerminal, OpenTerminal, Toast};
149
150use crate::hover_links::find_url;
151
152pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
153const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
154const MAX_LINE_LEN: usize = 1024;
155const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
156const MAX_SELECTION_HISTORY_LEN: usize = 1024;
157pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
158#[doc(hidden)]
159pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
160#[doc(hidden)]
161pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
162
163pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
164
165pub fn render_parsed_markdown(
166 element_id: impl Into<ElementId>,
167 parsed: &language::ParsedMarkdown,
168 editor_style: &EditorStyle,
169 workspace: Option<WeakView<Workspace>>,
170 cx: &mut WindowContext,
171) -> InteractiveText {
172 let code_span_background_color = cx
173 .theme()
174 .colors()
175 .editor_document_highlight_read_background;
176
177 let highlights = gpui::combine_highlights(
178 parsed.highlights.iter().filter_map(|(range, highlight)| {
179 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
180 Some((range.clone(), highlight))
181 }),
182 parsed
183 .regions
184 .iter()
185 .zip(&parsed.region_ranges)
186 .filter_map(|(region, range)| {
187 if region.code {
188 Some((
189 range.clone(),
190 HighlightStyle {
191 background_color: Some(code_span_background_color),
192 ..Default::default()
193 },
194 ))
195 } else {
196 None
197 }
198 }),
199 );
200
201 let mut links = Vec::new();
202 let mut link_ranges = Vec::new();
203 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
204 if let Some(link) = region.link.clone() {
205 links.push(link);
206 link_ranges.push(range.clone());
207 }
208 }
209
210 InteractiveText::new(
211 element_id,
212 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
213 )
214 .on_click(link_ranges, move |clicked_range_ix, cx| {
215 match &links[clicked_range_ix] {
216 markdown::Link::Web { url } => cx.open_url(url),
217 markdown::Link::Path { path } => {
218 if let Some(workspace) = &workspace {
219 _ = workspace.update(cx, |workspace, cx| {
220 workspace.open_abs_path(path.clone(), false, cx).detach();
221 });
222 }
223 }
224 }
225 })
226}
227
228#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
229pub(crate) enum InlayId {
230 Suggestion(usize),
231 Hint(usize),
232}
233
234impl InlayId {
235 fn id(&self) -> usize {
236 match self {
237 Self::Suggestion(id) => *id,
238 Self::Hint(id) => *id,
239 }
240 }
241}
242
243enum DiffRowHighlight {}
244enum DocumentHighlightRead {}
245enum DocumentHighlightWrite {}
246enum InputComposition {}
247
248#[derive(Copy, Clone, PartialEq, Eq)]
249pub enum Direction {
250 Prev,
251 Next,
252}
253
254pub fn init_settings(cx: &mut AppContext) {
255 EditorSettings::register(cx);
256}
257
258pub fn init(cx: &mut AppContext) {
259 init_settings(cx);
260
261 workspace::register_project_item::<Editor>(cx);
262 workspace::register_followable_item::<Editor>(cx);
263 workspace::register_deserializable_item::<Editor>(cx);
264 cx.observe_new_views(
265 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
266 workspace.register_action(Editor::new_file);
267 workspace.register_action(Editor::new_file_in_direction);
268 },
269 )
270 .detach();
271
272 cx.on_action(move |_: &workspace::NewFile, cx| {
273 let app_state = workspace::AppState::global(cx);
274 if let Some(app_state) = app_state.upgrade() {
275 workspace::open_new(app_state, cx, |workspace, cx| {
276 Editor::new_file(workspace, &Default::default(), cx)
277 })
278 .detach();
279 }
280 });
281 cx.on_action(move |_: &workspace::NewWindow, cx| {
282 let app_state = workspace::AppState::global(cx);
283 if let Some(app_state) = app_state.upgrade() {
284 workspace::open_new(app_state, cx, |workspace, cx| {
285 Editor::new_file(workspace, &Default::default(), cx)
286 })
287 .detach();
288 }
289 });
290}
291
292pub struct SearchWithinRange;
293
294trait InvalidationRegion {
295 fn ranges(&self) -> &[Range<Anchor>];
296}
297
298#[derive(Clone, Debug, PartialEq)]
299pub enum SelectPhase {
300 Begin {
301 position: DisplayPoint,
302 add: bool,
303 click_count: usize,
304 },
305 BeginColumnar {
306 position: DisplayPoint,
307 reset: bool,
308 goal_column: u32,
309 },
310 Extend {
311 position: DisplayPoint,
312 click_count: usize,
313 },
314 Update {
315 position: DisplayPoint,
316 goal_column: u32,
317 scroll_delta: gpui::Point<f32>,
318 },
319 End,
320}
321
322#[derive(Clone, Debug)]
323pub enum SelectMode {
324 Character,
325 Word(Range<Anchor>),
326 Line(Range<Anchor>),
327 All,
328}
329
330#[derive(Copy, Clone, PartialEq, Eq, Debug)]
331pub enum EditorMode {
332 SingleLine,
333 AutoHeight { max_lines: usize },
334 Full,
335}
336
337#[derive(Clone, Debug)]
338pub enum SoftWrap {
339 None,
340 PreferLine,
341 EditorWidth,
342 Column(u32),
343}
344
345#[derive(Clone)]
346pub struct EditorStyle {
347 pub background: Hsla,
348 pub local_player: PlayerColor,
349 pub text: TextStyle,
350 pub scrollbar_width: Pixels,
351 pub syntax: Arc<SyntaxTheme>,
352 pub status: StatusColors,
353 pub inlay_hints_style: HighlightStyle,
354 pub suggestions_style: HighlightStyle,
355}
356
357impl Default for EditorStyle {
358 fn default() -> Self {
359 Self {
360 background: Hsla::default(),
361 local_player: PlayerColor::default(),
362 text: TextStyle::default(),
363 scrollbar_width: Pixels::default(),
364 syntax: Default::default(),
365 // HACK: Status colors don't have a real default.
366 // We should look into removing the status colors from the editor
367 // style and retrieve them directly from the theme.
368 status: StatusColors::dark(),
369 inlay_hints_style: HighlightStyle::default(),
370 suggestions_style: HighlightStyle::default(),
371 }
372 }
373}
374
375type CompletionId = usize;
376
377// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
378// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
379
380type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
381
382struct ScrollbarMarkerState {
383 scrollbar_size: Size<Pixels>,
384 dirty: bool,
385 markers: Arc<[PaintQuad]>,
386 pending_refresh: Option<Task<Result<()>>>,
387}
388
389impl ScrollbarMarkerState {
390 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
391 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
392 }
393}
394
395impl Default for ScrollbarMarkerState {
396 fn default() -> Self {
397 Self {
398 scrollbar_size: Size::default(),
399 dirty: false,
400 markers: Arc::from([]),
401 pending_refresh: None,
402 }
403 }
404}
405
406#[derive(Clone, Debug)]
407struct RunnableTasks {
408 templates: Vec<(TaskSourceKind, TaskTemplate)>,
409 offset: MultiBufferOffset,
410 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
411 column: u32,
412 // Values of all named captures, including those starting with '_'
413 extra_variables: HashMap<String, String>,
414 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
415 context_range: Range<BufferOffset>,
416}
417
418#[derive(Clone)]
419struct ResolvedTasks {
420 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
421 position: Anchor,
422}
423#[derive(Copy, Clone, Debug)]
424struct MultiBufferOffset(usize);
425#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
426struct BufferOffset(usize);
427/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
428///
429/// See the [module level documentation](self) for more information.
430pub struct Editor {
431 focus_handle: FocusHandle,
432 /// The text buffer being edited
433 buffer: Model<MultiBuffer>,
434 /// Map of how text in the buffer should be displayed.
435 /// Handles soft wraps, folds, fake inlay text insertions, etc.
436 pub display_map: Model<DisplayMap>,
437 pub selections: SelectionsCollection,
438 pub scroll_manager: ScrollManager,
439 columnar_selection_tail: Option<Anchor>,
440 add_selections_state: Option<AddSelectionsState>,
441 select_next_state: Option<SelectNextState>,
442 select_prev_state: Option<SelectNextState>,
443 selection_history: SelectionHistory,
444 autoclose_regions: Vec<AutocloseRegion>,
445 snippet_stack: InvalidationStack<SnippetState>,
446 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
447 ime_transaction: Option<TransactionId>,
448 active_diagnostics: Option<ActiveDiagnosticGroup>,
449 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
450 project: Option<Model<Project>>,
451 completion_provider: Option<Box<dyn CompletionProvider>>,
452 collaboration_hub: Option<Box<dyn CollaborationHub>>,
453 blink_manager: Model<BlinkManager>,
454 show_cursor_names: bool,
455 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
456 pub show_local_selections: bool,
457 mode: EditorMode,
458 show_breadcrumbs: bool,
459 show_gutter: bool,
460 show_line_numbers: Option<bool>,
461 show_git_diff_gutter: Option<bool>,
462 show_code_actions: Option<bool>,
463 show_wrap_guides: Option<bool>,
464 show_indent_guides: Option<bool>,
465 placeholder_text: Option<Arc<str>>,
466 highlight_order: usize,
467 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
468 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
469 scrollbar_marker_state: ScrollbarMarkerState,
470 active_indent_guides_state: ActiveIndentGuidesState,
471 nav_history: Option<ItemNavHistory>,
472 context_menu: RwLock<Option<ContextMenu>>,
473 mouse_context_menu: Option<MouseContextMenu>,
474 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
475 find_all_references_task_sources: Vec<Anchor>,
476 next_completion_id: CompletionId,
477 completion_documentation_pre_resolve_debounce: DebouncedDelay,
478 available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
479 code_actions_task: Option<Task<()>>,
480 document_highlights_task: Option<Task<()>>,
481 pending_rename: Option<RenameState>,
482 searchable: bool,
483 cursor_shape: CursorShape,
484 current_line_highlight: CurrentLineHighlight,
485 collapse_matches: bool,
486 autoindent_mode: Option<AutoindentMode>,
487 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
488 keymap_context_layers: BTreeMap<TypeId, KeyContext>,
489 input_enabled: bool,
490 use_modal_editing: bool,
491 read_only: bool,
492 leader_peer_id: Option<PeerId>,
493 remote_id: Option<ViewId>,
494 hover_state: HoverState,
495 gutter_hovered: bool,
496 hovered_link_state: Option<HoveredLinkState>,
497 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
498 active_inline_completion: Option<Inlay>,
499 show_inline_completions: bool,
500 inlay_hint_cache: InlayHintCache,
501 expanded_hunks: ExpandedHunks,
502 next_inlay_id: usize,
503 _subscriptions: Vec<Subscription>,
504 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
505 gutter_dimensions: GutterDimensions,
506 pub vim_replace_map: HashMap<Range<usize>, String>,
507 style: Option<EditorStyle>,
508 editor_actions: Vec<Box<dyn Fn(&mut ViewContext<Self>)>>,
509 use_autoclose: bool,
510 auto_replace_emoji_shortcode: bool,
511 show_git_blame_gutter: bool,
512 show_git_blame_inline: bool,
513 show_git_blame_inline_delay_task: Option<Task<()>>,
514 git_blame_inline_enabled: bool,
515 blame: Option<Model<GitBlame>>,
516 blame_subscription: Option<Subscription>,
517 custom_context_menu: Option<
518 Box<
519 dyn 'static
520 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
521 >,
522 >,
523 last_bounds: Option<Bounds<Pixels>>,
524 expect_bounds_change: Option<Bounds<Pixels>>,
525 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
526 tasks_update_task: Option<Task<()>>,
527}
528
529#[derive(Clone)]
530pub struct EditorSnapshot {
531 pub mode: EditorMode,
532 show_gutter: bool,
533 show_line_numbers: Option<bool>,
534 show_git_diff_gutter: Option<bool>,
535 show_code_actions: Option<bool>,
536 render_git_blame_gutter: bool,
537 pub display_snapshot: DisplaySnapshot,
538 pub placeholder_text: Option<Arc<str>>,
539 is_focused: bool,
540 scroll_anchor: ScrollAnchor,
541 ongoing_scroll: OngoingScroll,
542 current_line_highlight: CurrentLineHighlight,
543 gutter_hovered: bool,
544}
545
546const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
547
548#[derive(Debug, Clone, Copy)]
549pub struct GutterDimensions {
550 pub left_padding: Pixels,
551 pub right_padding: Pixels,
552 pub width: Pixels,
553 pub margin: Pixels,
554 pub git_blame_entries_width: Option<Pixels>,
555}
556
557impl Default for GutterDimensions {
558 fn default() -> Self {
559 Self {
560 left_padding: Pixels::ZERO,
561 right_padding: Pixels::ZERO,
562 width: Pixels::ZERO,
563 margin: Pixels::ZERO,
564 git_blame_entries_width: None,
565 }
566 }
567}
568
569#[derive(Debug)]
570pub struct RemoteSelection {
571 pub replica_id: ReplicaId,
572 pub selection: Selection<Anchor>,
573 pub cursor_shape: CursorShape,
574 pub peer_id: PeerId,
575 pub line_mode: bool,
576 pub participant_index: Option<ParticipantIndex>,
577 pub user_name: Option<SharedString>,
578}
579
580#[derive(Clone, Debug)]
581struct SelectionHistoryEntry {
582 selections: Arc<[Selection<Anchor>]>,
583 select_next_state: Option<SelectNextState>,
584 select_prev_state: Option<SelectNextState>,
585 add_selections_state: Option<AddSelectionsState>,
586}
587
588enum SelectionHistoryMode {
589 Normal,
590 Undoing,
591 Redoing,
592}
593
594#[derive(Clone, PartialEq, Eq, Hash)]
595struct HoveredCursor {
596 replica_id: u16,
597 selection_id: usize,
598}
599
600impl Default for SelectionHistoryMode {
601 fn default() -> Self {
602 Self::Normal
603 }
604}
605
606#[derive(Default)]
607struct SelectionHistory {
608 #[allow(clippy::type_complexity)]
609 selections_by_transaction:
610 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
611 mode: SelectionHistoryMode,
612 undo_stack: VecDeque<SelectionHistoryEntry>,
613 redo_stack: VecDeque<SelectionHistoryEntry>,
614}
615
616impl SelectionHistory {
617 fn insert_transaction(
618 &mut self,
619 transaction_id: TransactionId,
620 selections: Arc<[Selection<Anchor>]>,
621 ) {
622 self.selections_by_transaction
623 .insert(transaction_id, (selections, None));
624 }
625
626 #[allow(clippy::type_complexity)]
627 fn transaction(
628 &self,
629 transaction_id: TransactionId,
630 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
631 self.selections_by_transaction.get(&transaction_id)
632 }
633
634 #[allow(clippy::type_complexity)]
635 fn transaction_mut(
636 &mut self,
637 transaction_id: TransactionId,
638 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
639 self.selections_by_transaction.get_mut(&transaction_id)
640 }
641
642 fn push(&mut self, entry: SelectionHistoryEntry) {
643 if !entry.selections.is_empty() {
644 match self.mode {
645 SelectionHistoryMode::Normal => {
646 self.push_undo(entry);
647 self.redo_stack.clear();
648 }
649 SelectionHistoryMode::Undoing => self.push_redo(entry),
650 SelectionHistoryMode::Redoing => self.push_undo(entry),
651 }
652 }
653 }
654
655 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
656 if self
657 .undo_stack
658 .back()
659 .map_or(true, |e| e.selections != entry.selections)
660 {
661 self.undo_stack.push_back(entry);
662 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
663 self.undo_stack.pop_front();
664 }
665 }
666 }
667
668 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
669 if self
670 .redo_stack
671 .back()
672 .map_or(true, |e| e.selections != entry.selections)
673 {
674 self.redo_stack.push_back(entry);
675 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
676 self.redo_stack.pop_front();
677 }
678 }
679 }
680}
681
682struct RowHighlight {
683 index: usize,
684 range: RangeInclusive<Anchor>,
685 color: Option<Hsla>,
686 should_autoscroll: bool,
687}
688
689#[derive(Clone, Debug)]
690struct AddSelectionsState {
691 above: bool,
692 stack: Vec<usize>,
693}
694
695#[derive(Clone)]
696struct SelectNextState {
697 query: AhoCorasick,
698 wordwise: bool,
699 done: bool,
700}
701
702impl std::fmt::Debug for SelectNextState {
703 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
704 f.debug_struct(std::any::type_name::<Self>())
705 .field("wordwise", &self.wordwise)
706 .field("done", &self.done)
707 .finish()
708 }
709}
710
711#[derive(Debug)]
712struct AutocloseRegion {
713 selection_id: usize,
714 range: Range<Anchor>,
715 pair: BracketPair,
716}
717
718#[derive(Debug)]
719struct SnippetState {
720 ranges: Vec<Vec<Range<Anchor>>>,
721 active_index: usize,
722}
723
724#[doc(hidden)]
725pub struct RenameState {
726 pub range: Range<Anchor>,
727 pub old_name: Arc<str>,
728 pub editor: View<Editor>,
729 block_id: BlockId,
730}
731
732struct InvalidationStack<T>(Vec<T>);
733
734struct RegisteredInlineCompletionProvider {
735 provider: Arc<dyn InlineCompletionProviderHandle>,
736 _subscription: Subscription,
737}
738
739enum ContextMenu {
740 Completions(CompletionsMenu),
741 CodeActions(CodeActionsMenu),
742}
743
744impl ContextMenu {
745 fn select_first(
746 &mut self,
747 project: Option<&Model<Project>>,
748 cx: &mut ViewContext<Editor>,
749 ) -> bool {
750 if self.visible() {
751 match self {
752 ContextMenu::Completions(menu) => menu.select_first(project, cx),
753 ContextMenu::CodeActions(menu) => menu.select_first(cx),
754 }
755 true
756 } else {
757 false
758 }
759 }
760
761 fn select_prev(
762 &mut self,
763 project: Option<&Model<Project>>,
764 cx: &mut ViewContext<Editor>,
765 ) -> bool {
766 if self.visible() {
767 match self {
768 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
769 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
770 }
771 true
772 } else {
773 false
774 }
775 }
776
777 fn select_next(
778 &mut self,
779 project: Option<&Model<Project>>,
780 cx: &mut ViewContext<Editor>,
781 ) -> bool {
782 if self.visible() {
783 match self {
784 ContextMenu::Completions(menu) => menu.select_next(project, cx),
785 ContextMenu::CodeActions(menu) => menu.select_next(cx),
786 }
787 true
788 } else {
789 false
790 }
791 }
792
793 fn select_last(
794 &mut self,
795 project: Option<&Model<Project>>,
796 cx: &mut ViewContext<Editor>,
797 ) -> bool {
798 if self.visible() {
799 match self {
800 ContextMenu::Completions(menu) => menu.select_last(project, cx),
801 ContextMenu::CodeActions(menu) => menu.select_last(cx),
802 }
803 true
804 } else {
805 false
806 }
807 }
808
809 fn visible(&self) -> bool {
810 match self {
811 ContextMenu::Completions(menu) => menu.visible(),
812 ContextMenu::CodeActions(menu) => menu.visible(),
813 }
814 }
815
816 fn render(
817 &self,
818 cursor_position: DisplayPoint,
819 style: &EditorStyle,
820 max_height: Pixels,
821 workspace: Option<WeakView<Workspace>>,
822 cx: &mut ViewContext<Editor>,
823 ) -> (ContextMenuOrigin, AnyElement) {
824 match self {
825 ContextMenu::Completions(menu) => (
826 ContextMenuOrigin::EditorPoint(cursor_position),
827 menu.render(style, max_height, workspace, cx),
828 ),
829 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
830 }
831 }
832}
833
834enum ContextMenuOrigin {
835 EditorPoint(DisplayPoint),
836 GutterIndicator(DisplayRow),
837}
838
839#[derive(Clone)]
840struct CompletionsMenu {
841 id: CompletionId,
842 initial_position: Anchor,
843 buffer: Model<Buffer>,
844 completions: Arc<RwLock<Box<[Completion]>>>,
845 match_candidates: Arc<[StringMatchCandidate]>,
846 matches: Arc<[StringMatch]>,
847 selected_item: usize,
848 scroll_handle: UniformListScrollHandle,
849 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
850}
851
852impl CompletionsMenu {
853 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
854 self.selected_item = 0;
855 self.scroll_handle.scroll_to_item(self.selected_item);
856 self.attempt_resolve_selected_completion_documentation(project, cx);
857 cx.notify();
858 }
859
860 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
861 if self.selected_item > 0 {
862 self.selected_item -= 1;
863 } else {
864 self.selected_item = self.matches.len() - 1;
865 }
866 self.scroll_handle.scroll_to_item(self.selected_item);
867 self.attempt_resolve_selected_completion_documentation(project, cx);
868 cx.notify();
869 }
870
871 fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
872 if self.selected_item + 1 < self.matches.len() {
873 self.selected_item += 1;
874 } else {
875 self.selected_item = 0;
876 }
877 self.scroll_handle.scroll_to_item(self.selected_item);
878 self.attempt_resolve_selected_completion_documentation(project, cx);
879 cx.notify();
880 }
881
882 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
883 self.selected_item = self.matches.len() - 1;
884 self.scroll_handle.scroll_to_item(self.selected_item);
885 self.attempt_resolve_selected_completion_documentation(project, cx);
886 cx.notify();
887 }
888
889 fn pre_resolve_completion_documentation(
890 buffer: Model<Buffer>,
891 completions: Arc<RwLock<Box<[Completion]>>>,
892 matches: Arc<[StringMatch]>,
893 editor: &Editor,
894 cx: &mut ViewContext<Editor>,
895 ) -> Task<()> {
896 let settings = EditorSettings::get_global(cx);
897 if !settings.show_completion_documentation {
898 return Task::ready(());
899 }
900
901 let Some(provider) = editor.completion_provider.as_ref() else {
902 return Task::ready(());
903 };
904
905 let resolve_task = provider.resolve_completions(
906 buffer,
907 matches.iter().map(|m| m.candidate_id).collect(),
908 completions.clone(),
909 cx,
910 );
911
912 return cx.spawn(move |this, mut cx| async move {
913 if let Some(true) = resolve_task.await.log_err() {
914 this.update(&mut cx, |_, cx| cx.notify()).ok();
915 }
916 });
917 }
918
919 fn attempt_resolve_selected_completion_documentation(
920 &mut self,
921 project: Option<&Model<Project>>,
922 cx: &mut ViewContext<Editor>,
923 ) {
924 let settings = EditorSettings::get_global(cx);
925 if !settings.show_completion_documentation {
926 return;
927 }
928
929 let completion_index = self.matches[self.selected_item].candidate_id;
930 let Some(project) = project else {
931 return;
932 };
933
934 let resolve_task = project.update(cx, |project, cx| {
935 project.resolve_completions(
936 self.buffer.clone(),
937 vec![completion_index],
938 self.completions.clone(),
939 cx,
940 )
941 });
942
943 let delay_ms =
944 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
945 let delay = Duration::from_millis(delay_ms);
946
947 self.selected_completion_documentation_resolve_debounce
948 .lock()
949 .fire_new(delay, cx, |_, cx| {
950 cx.spawn(move |this, mut cx| async move {
951 if let Some(true) = resolve_task.await.log_err() {
952 this.update(&mut cx, |_, cx| cx.notify()).ok();
953 }
954 })
955 });
956 }
957
958 fn visible(&self) -> bool {
959 !self.matches.is_empty()
960 }
961
962 fn render(
963 &self,
964 style: &EditorStyle,
965 max_height: Pixels,
966 workspace: Option<WeakView<Workspace>>,
967 cx: &mut ViewContext<Editor>,
968 ) -> AnyElement {
969 let settings = EditorSettings::get_global(cx);
970 let show_completion_documentation = settings.show_completion_documentation;
971
972 let widest_completion_ix = self
973 .matches
974 .iter()
975 .enumerate()
976 .max_by_key(|(_, mat)| {
977 let completions = self.completions.read();
978 let completion = &completions[mat.candidate_id];
979 let documentation = &completion.documentation;
980
981 let mut len = completion.label.text.chars().count();
982 if let Some(Documentation::SingleLine(text)) = documentation {
983 if show_completion_documentation {
984 len += text.chars().count();
985 }
986 }
987
988 len
989 })
990 .map(|(ix, _)| ix);
991
992 let completions = self.completions.clone();
993 let matches = self.matches.clone();
994 let selected_item = self.selected_item;
995 let style = style.clone();
996
997 let multiline_docs = if show_completion_documentation {
998 let mat = &self.matches[selected_item];
999 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1000 Some(Documentation::MultiLinePlainText(text)) => {
1001 Some(div().child(SharedString::from(text.clone())))
1002 }
1003 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1004 Some(div().child(render_parsed_markdown(
1005 "completions_markdown",
1006 parsed,
1007 &style,
1008 workspace,
1009 cx,
1010 )))
1011 }
1012 _ => None,
1013 };
1014 multiline_docs.map(|div| {
1015 div.id("multiline_docs")
1016 .max_h(max_height)
1017 .flex_1()
1018 .px_1p5()
1019 .py_1()
1020 .min_w(px(260.))
1021 .max_w(px(640.))
1022 .w(px(500.))
1023 .overflow_y_scroll()
1024 .occlude()
1025 })
1026 } else {
1027 None
1028 };
1029
1030 let list = uniform_list(
1031 cx.view().clone(),
1032 "completions",
1033 matches.len(),
1034 move |_editor, range, cx| {
1035 let start_ix = range.start;
1036 let completions_guard = completions.read();
1037
1038 matches[range]
1039 .iter()
1040 .enumerate()
1041 .map(|(ix, mat)| {
1042 let item_ix = start_ix + ix;
1043 let candidate_id = mat.candidate_id;
1044 let completion = &completions_guard[candidate_id];
1045
1046 let documentation = if show_completion_documentation {
1047 &completion.documentation
1048 } else {
1049 &None
1050 };
1051
1052 let highlights = gpui::combine_highlights(
1053 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1054 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1055 |(range, mut highlight)| {
1056 // Ignore font weight for syntax highlighting, as we'll use it
1057 // for fuzzy matches.
1058 highlight.font_weight = None;
1059
1060 if completion.lsp_completion.deprecated.unwrap_or(false) {
1061 highlight.strikethrough = Some(StrikethroughStyle {
1062 thickness: 1.0.into(),
1063 ..Default::default()
1064 });
1065 highlight.color = Some(cx.theme().colors().text_muted);
1066 }
1067
1068 (range, highlight)
1069 },
1070 ),
1071 );
1072 let completion_label = StyledText::new(completion.label.text.clone())
1073 .with_highlights(&style.text, highlights);
1074 let documentation_label =
1075 if let Some(Documentation::SingleLine(text)) = documentation {
1076 if text.trim().is_empty() {
1077 None
1078 } else {
1079 Some(
1080 h_flex().ml_4().child(
1081 Label::new(text.clone())
1082 .size(LabelSize::Small)
1083 .color(Color::Muted),
1084 ),
1085 )
1086 }
1087 } else {
1088 None
1089 };
1090
1091 div().min_w(px(220.)).max_w(px(540.)).child(
1092 ListItem::new(mat.candidate_id)
1093 .inset(true)
1094 .selected(item_ix == selected_item)
1095 .on_click(cx.listener(move |editor, _event, cx| {
1096 cx.stop_propagation();
1097 if let Some(task) = editor.confirm_completion(
1098 &ConfirmCompletion {
1099 item_ix: Some(item_ix),
1100 },
1101 cx,
1102 ) {
1103 task.detach_and_log_err(cx)
1104 }
1105 }))
1106 .child(h_flex().overflow_hidden().child(completion_label))
1107 .end_slot::<Div>(documentation_label),
1108 )
1109 })
1110 .collect()
1111 },
1112 )
1113 .occlude()
1114 .max_h(max_height)
1115 .track_scroll(self.scroll_handle.clone())
1116 .with_width_from_item(widest_completion_ix)
1117 .with_sizing_behavior(ListSizingBehavior::Infer);
1118
1119 Popover::new()
1120 .child(list)
1121 .when_some(multiline_docs, |popover, multiline_docs| {
1122 popover.aside(multiline_docs)
1123 })
1124 .into_any_element()
1125 }
1126
1127 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1128 let mut matches = if let Some(query) = query {
1129 fuzzy::match_strings(
1130 &self.match_candidates,
1131 query,
1132 query.chars().any(|c| c.is_uppercase()),
1133 100,
1134 &Default::default(),
1135 executor,
1136 )
1137 .await
1138 } else {
1139 self.match_candidates
1140 .iter()
1141 .enumerate()
1142 .map(|(candidate_id, candidate)| StringMatch {
1143 candidate_id,
1144 score: Default::default(),
1145 positions: Default::default(),
1146 string: candidate.string.clone(),
1147 })
1148 .collect()
1149 };
1150
1151 // Remove all candidates where the query's start does not match the start of any word in the candidate
1152 if let Some(query) = query {
1153 if let Some(query_start) = query.chars().next() {
1154 matches.retain(|string_match| {
1155 split_words(&string_match.string).any(|word| {
1156 // Check that the first codepoint of the word as lowercase matches the first
1157 // codepoint of the query as lowercase
1158 word.chars()
1159 .flat_map(|codepoint| codepoint.to_lowercase())
1160 .zip(query_start.to_lowercase())
1161 .all(|(word_cp, query_cp)| word_cp == query_cp)
1162 })
1163 });
1164 }
1165 }
1166
1167 let completions = self.completions.read();
1168 matches.sort_unstable_by_key(|mat| {
1169 // We do want to strike a balance here between what the language server tells us
1170 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1171 // `Creat` and there is a local variable called `CreateComponent`).
1172 // So what we do is: we bucket all matches into two buckets
1173 // - Strong matches
1174 // - Weak matches
1175 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1176 // and the Weak matches are the rest.
1177 //
1178 // For the strong matches, we sort by the language-servers score first and for the weak
1179 // matches, we prefer our fuzzy finder first.
1180 //
1181 // The thinking behind that: it's useless to take the sort_text the language-server gives
1182 // us into account when it's obviously a bad match.
1183
1184 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1185 enum MatchScore<'a> {
1186 Strong {
1187 sort_text: Option<&'a str>,
1188 score: Reverse<OrderedFloat<f64>>,
1189 sort_key: (usize, &'a str),
1190 },
1191 Weak {
1192 score: Reverse<OrderedFloat<f64>>,
1193 sort_text: Option<&'a str>,
1194 sort_key: (usize, &'a str),
1195 },
1196 }
1197
1198 let completion = &completions[mat.candidate_id];
1199 let sort_key = completion.sort_key();
1200 let sort_text = completion.lsp_completion.sort_text.as_deref();
1201 let score = Reverse(OrderedFloat(mat.score));
1202
1203 if mat.score >= 0.2 {
1204 MatchScore::Strong {
1205 sort_text,
1206 score,
1207 sort_key,
1208 }
1209 } else {
1210 MatchScore::Weak {
1211 score,
1212 sort_text,
1213 sort_key,
1214 }
1215 }
1216 });
1217
1218 for mat in &mut matches {
1219 let completion = &completions[mat.candidate_id];
1220 mat.string.clone_from(&completion.label.text);
1221 for position in &mut mat.positions {
1222 *position += completion.label.filter_range.start;
1223 }
1224 }
1225 drop(completions);
1226
1227 self.matches = matches.into();
1228 self.selected_item = 0;
1229 }
1230}
1231
1232#[derive(Clone)]
1233struct CodeActionContents {
1234 tasks: Option<Arc<ResolvedTasks>>,
1235 actions: Option<Arc<[CodeAction]>>,
1236}
1237
1238impl CodeActionContents {
1239 fn len(&self) -> usize {
1240 match (&self.tasks, &self.actions) {
1241 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1242 (Some(tasks), None) => tasks.templates.len(),
1243 (None, Some(actions)) => actions.len(),
1244 (None, None) => 0,
1245 }
1246 }
1247
1248 fn is_empty(&self) -> bool {
1249 match (&self.tasks, &self.actions) {
1250 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1251 (Some(tasks), None) => tasks.templates.is_empty(),
1252 (None, Some(actions)) => actions.is_empty(),
1253 (None, None) => true,
1254 }
1255 }
1256
1257 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1258 self.tasks
1259 .iter()
1260 .flat_map(|tasks| {
1261 tasks
1262 .templates
1263 .iter()
1264 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1265 })
1266 .chain(self.actions.iter().flat_map(|actions| {
1267 actions
1268 .iter()
1269 .map(|action| CodeActionsItem::CodeAction(action.clone()))
1270 }))
1271 }
1272 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1273 match (&self.tasks, &self.actions) {
1274 (Some(tasks), Some(actions)) => {
1275 if index < tasks.templates.len() {
1276 tasks
1277 .templates
1278 .get(index)
1279 .cloned()
1280 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1281 } else {
1282 actions
1283 .get(index - tasks.templates.len())
1284 .cloned()
1285 .map(CodeActionsItem::CodeAction)
1286 }
1287 }
1288 (Some(tasks), None) => tasks
1289 .templates
1290 .get(index)
1291 .cloned()
1292 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1293 (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
1294 (None, None) => None,
1295 }
1296 }
1297}
1298
1299#[allow(clippy::large_enum_variant)]
1300#[derive(Clone)]
1301enum CodeActionsItem {
1302 Task(TaskSourceKind, ResolvedTask),
1303 CodeAction(CodeAction),
1304}
1305
1306impl CodeActionsItem {
1307 fn as_task(&self) -> Option<&ResolvedTask> {
1308 let Self::Task(_, task) = self else {
1309 return None;
1310 };
1311 Some(task)
1312 }
1313 fn as_code_action(&self) -> Option<&CodeAction> {
1314 let Self::CodeAction(action) = self else {
1315 return None;
1316 };
1317 Some(action)
1318 }
1319 fn label(&self) -> String {
1320 match self {
1321 Self::CodeAction(action) => action.lsp_action.title.clone(),
1322 Self::Task(_, task) => task.resolved_label.clone(),
1323 }
1324 }
1325}
1326
1327struct CodeActionsMenu {
1328 actions: CodeActionContents,
1329 buffer: Model<Buffer>,
1330 selected_item: usize,
1331 scroll_handle: UniformListScrollHandle,
1332 deployed_from_indicator: Option<DisplayRow>,
1333}
1334
1335impl CodeActionsMenu {
1336 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1337 self.selected_item = 0;
1338 self.scroll_handle.scroll_to_item(self.selected_item);
1339 cx.notify()
1340 }
1341
1342 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1343 if self.selected_item > 0 {
1344 self.selected_item -= 1;
1345 } else {
1346 self.selected_item = self.actions.len() - 1;
1347 }
1348 self.scroll_handle.scroll_to_item(self.selected_item);
1349 cx.notify();
1350 }
1351
1352 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1353 if self.selected_item + 1 < self.actions.len() {
1354 self.selected_item += 1;
1355 } else {
1356 self.selected_item = 0;
1357 }
1358 self.scroll_handle.scroll_to_item(self.selected_item);
1359 cx.notify();
1360 }
1361
1362 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1363 self.selected_item = self.actions.len() - 1;
1364 self.scroll_handle.scroll_to_item(self.selected_item);
1365 cx.notify()
1366 }
1367
1368 fn visible(&self) -> bool {
1369 !self.actions.is_empty()
1370 }
1371
1372 fn render(
1373 &self,
1374 cursor_position: DisplayPoint,
1375 _style: &EditorStyle,
1376 max_height: Pixels,
1377 cx: &mut ViewContext<Editor>,
1378 ) -> (ContextMenuOrigin, AnyElement) {
1379 let actions = self.actions.clone();
1380 let selected_item = self.selected_item;
1381 let element = uniform_list(
1382 cx.view().clone(),
1383 "code_actions_menu",
1384 self.actions.len(),
1385 move |_this, range, cx| {
1386 actions
1387 .iter()
1388 .skip(range.start)
1389 .take(range.end - range.start)
1390 .enumerate()
1391 .map(|(ix, action)| {
1392 let item_ix = range.start + ix;
1393 let selected = selected_item == item_ix;
1394 let colors = cx.theme().colors();
1395 div()
1396 .px_2()
1397 .text_color(colors.text)
1398 .when(selected, |style| {
1399 style
1400 .bg(colors.element_active)
1401 .text_color(colors.text_accent)
1402 })
1403 .hover(|style| {
1404 style
1405 .bg(colors.element_hover)
1406 .text_color(colors.text_accent)
1407 })
1408 .whitespace_nowrap()
1409 .when_some(action.as_code_action(), |this, action| {
1410 this.on_mouse_down(
1411 MouseButton::Left,
1412 cx.listener(move |editor, _, cx| {
1413 cx.stop_propagation();
1414 if let Some(task) = editor.confirm_code_action(
1415 &ConfirmCodeAction {
1416 item_ix: Some(item_ix),
1417 },
1418 cx,
1419 ) {
1420 task.detach_and_log_err(cx)
1421 }
1422 }),
1423 )
1424 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1425 .child(SharedString::from(action.lsp_action.title.clone()))
1426 })
1427 .when_some(action.as_task(), |this, task| {
1428 this.on_mouse_down(
1429 MouseButton::Left,
1430 cx.listener(move |editor, _, cx| {
1431 cx.stop_propagation();
1432 if let Some(task) = editor.confirm_code_action(
1433 &ConfirmCodeAction {
1434 item_ix: Some(item_ix),
1435 },
1436 cx,
1437 ) {
1438 task.detach_and_log_err(cx)
1439 }
1440 }),
1441 )
1442 .child(SharedString::from(task.resolved_label.clone()))
1443 })
1444 })
1445 .collect()
1446 },
1447 )
1448 .elevation_1(cx)
1449 .px_2()
1450 .py_1()
1451 .max_h(max_height)
1452 .occlude()
1453 .track_scroll(self.scroll_handle.clone())
1454 .with_width_from_item(
1455 self.actions
1456 .iter()
1457 .enumerate()
1458 .max_by_key(|(_, action)| match action {
1459 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1460 CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
1461 })
1462 .map(|(ix, _)| ix),
1463 )
1464 .with_sizing_behavior(ListSizingBehavior::Infer)
1465 .into_any_element();
1466
1467 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1468 ContextMenuOrigin::GutterIndicator(row)
1469 } else {
1470 ContextMenuOrigin::EditorPoint(cursor_position)
1471 };
1472
1473 (cursor_position, element)
1474 }
1475}
1476
1477#[derive(Debug)]
1478struct ActiveDiagnosticGroup {
1479 primary_range: Range<Anchor>,
1480 primary_message: String,
1481 group_id: usize,
1482 blocks: HashMap<BlockId, Diagnostic>,
1483 is_valid: bool,
1484}
1485
1486#[derive(Serialize, Deserialize)]
1487pub struct ClipboardSelection {
1488 pub len: usize,
1489 pub is_entire_line: bool,
1490 pub first_line_indent: u32,
1491}
1492
1493#[derive(Debug)]
1494pub(crate) struct NavigationData {
1495 cursor_anchor: Anchor,
1496 cursor_position: Point,
1497 scroll_anchor: ScrollAnchor,
1498 scroll_top_row: u32,
1499}
1500
1501enum GotoDefinitionKind {
1502 Symbol,
1503 Type,
1504 Implementation,
1505}
1506
1507#[derive(Debug, Clone)]
1508enum InlayHintRefreshReason {
1509 Toggle(bool),
1510 SettingsChange(InlayHintSettings),
1511 NewLinesShown,
1512 BufferEdited(HashSet<Arc<Language>>),
1513 RefreshRequested,
1514 ExcerptsRemoved(Vec<ExcerptId>),
1515}
1516
1517impl InlayHintRefreshReason {
1518 fn description(&self) -> &'static str {
1519 match self {
1520 Self::Toggle(_) => "toggle",
1521 Self::SettingsChange(_) => "settings change",
1522 Self::NewLinesShown => "new lines shown",
1523 Self::BufferEdited(_) => "buffer edited",
1524 Self::RefreshRequested => "refresh requested",
1525 Self::ExcerptsRemoved(_) => "excerpts removed",
1526 }
1527 }
1528}
1529
1530impl Editor {
1531 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1532 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1533 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1534 Self::new(EditorMode::SingleLine, buffer, None, false, cx)
1535 }
1536
1537 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1538 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1539 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1540 Self::new(EditorMode::Full, buffer, None, false, cx)
1541 }
1542
1543 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1544 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1545 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1546 Self::new(
1547 EditorMode::AutoHeight { max_lines },
1548 buffer,
1549 None,
1550 false,
1551 cx,
1552 )
1553 }
1554
1555 pub fn for_buffer(
1556 buffer: Model<Buffer>,
1557 project: Option<Model<Project>>,
1558 cx: &mut ViewContext<Self>,
1559 ) -> Self {
1560 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1561 Self::new(EditorMode::Full, buffer, project, false, cx)
1562 }
1563
1564 pub fn for_multibuffer(
1565 buffer: Model<MultiBuffer>,
1566 project: Option<Model<Project>>,
1567 show_excerpt_controls: bool,
1568 cx: &mut ViewContext<Self>,
1569 ) -> Self {
1570 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1571 }
1572
1573 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1574 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1575 let mut clone = Self::new(
1576 self.mode,
1577 self.buffer.clone(),
1578 self.project.clone(),
1579 show_excerpt_controls,
1580 cx,
1581 );
1582 self.display_map.update(cx, |display_map, cx| {
1583 let snapshot = display_map.snapshot(cx);
1584 clone.display_map.update(cx, |display_map, cx| {
1585 display_map.set_state(&snapshot, cx);
1586 });
1587 });
1588 clone.selections.clone_state(&self.selections);
1589 clone.scroll_manager.clone_state(&self.scroll_manager);
1590 clone.searchable = self.searchable;
1591 clone
1592 }
1593
1594 fn new(
1595 mode: EditorMode,
1596 buffer: Model<MultiBuffer>,
1597 project: Option<Model<Project>>,
1598 show_excerpt_controls: bool,
1599 cx: &mut ViewContext<Self>,
1600 ) -> Self {
1601 let style = cx.text_style();
1602 let font_size = style.font_size.to_pixels(cx.rem_size());
1603 let editor = cx.view().downgrade();
1604 let fold_placeholder = FoldPlaceholder {
1605 constrain_width: true,
1606 render: Arc::new(move |fold_id, fold_range, cx| {
1607 let editor = editor.clone();
1608 div()
1609 .id(fold_id)
1610 .bg(cx.theme().colors().ghost_element_background)
1611 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1612 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1613 .rounded_sm()
1614 .size_full()
1615 .cursor_pointer()
1616 .child("⋯")
1617 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1618 .on_click(move |_, cx| {
1619 editor
1620 .update(cx, |editor, cx| {
1621 editor.unfold_ranges(
1622 [fold_range.start..fold_range.end],
1623 true,
1624 false,
1625 cx,
1626 );
1627 cx.stop_propagation();
1628 })
1629 .ok();
1630 })
1631 .into_any()
1632 }),
1633 merge_adjacent: true,
1634 };
1635 let display_map = cx.new_model(|cx| {
1636 let file_header_size = if show_excerpt_controls { 3 } else { 2 };
1637
1638 DisplayMap::new(
1639 buffer.clone(),
1640 style.font(),
1641 font_size,
1642 None,
1643 show_excerpt_controls,
1644 file_header_size,
1645 1,
1646 1,
1647 fold_placeholder,
1648 cx,
1649 )
1650 });
1651
1652 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1653
1654 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1655
1656 let soft_wrap_mode_override =
1657 (mode == EditorMode::SingleLine).then(|| language_settings::SoftWrap::PreferLine);
1658
1659 let mut project_subscriptions = Vec::new();
1660 if mode == EditorMode::Full {
1661 if let Some(project) = project.as_ref() {
1662 if buffer.read(cx).is_singleton() {
1663 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1664 cx.emit(EditorEvent::TitleChanged);
1665 }));
1666 }
1667 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1668 if let project::Event::RefreshInlayHints = event {
1669 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1670 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1671 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1672 let focus_handle = editor.focus_handle(cx);
1673 if focus_handle.is_focused(cx) {
1674 let snapshot = buffer.read(cx).snapshot();
1675 for (range, snippet) in snippet_edits {
1676 let editor_range =
1677 language::range_from_lsp(*range).to_offset(&snapshot);
1678 editor
1679 .insert_snippet(&[editor_range], snippet.clone(), cx)
1680 .ok();
1681 }
1682 }
1683 }
1684 }
1685 }));
1686 let task_inventory = project.read(cx).task_inventory().clone();
1687 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1688 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1689 }));
1690 }
1691 }
1692
1693 let inlay_hint_settings = inlay_hint_settings(
1694 selections.newest_anchor().head(),
1695 &buffer.read(cx).snapshot(cx),
1696 cx,
1697 );
1698 let focus_handle = cx.focus_handle();
1699 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1700 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1701
1702 let show_indent_guides = if mode == EditorMode::SingleLine {
1703 Some(false)
1704 } else {
1705 None
1706 };
1707
1708 let mut this = Self {
1709 focus_handle,
1710 buffer: buffer.clone(),
1711 display_map: display_map.clone(),
1712 selections,
1713 scroll_manager: ScrollManager::new(cx),
1714 columnar_selection_tail: None,
1715 add_selections_state: None,
1716 select_next_state: None,
1717 select_prev_state: None,
1718 selection_history: Default::default(),
1719 autoclose_regions: Default::default(),
1720 snippet_stack: Default::default(),
1721 select_larger_syntax_node_stack: Vec::new(),
1722 ime_transaction: Default::default(),
1723 active_diagnostics: None,
1724 soft_wrap_mode_override,
1725 completion_provider: project.clone().map(|project| Box::new(project) as _),
1726 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1727 project,
1728 blink_manager: blink_manager.clone(),
1729 show_local_selections: true,
1730 mode,
1731 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1732 show_gutter: mode == EditorMode::Full,
1733 show_line_numbers: None,
1734 show_git_diff_gutter: None,
1735 show_code_actions: None,
1736 show_wrap_guides: None,
1737 show_indent_guides,
1738 placeholder_text: None,
1739 highlight_order: 0,
1740 highlighted_rows: HashMap::default(),
1741 background_highlights: Default::default(),
1742 scrollbar_marker_state: ScrollbarMarkerState::default(),
1743 active_indent_guides_state: ActiveIndentGuidesState::default(),
1744 nav_history: None,
1745 context_menu: RwLock::new(None),
1746 mouse_context_menu: None,
1747 completion_tasks: Default::default(),
1748 find_all_references_task_sources: Vec::new(),
1749 next_completion_id: 0,
1750 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1751 next_inlay_id: 0,
1752 available_code_actions: Default::default(),
1753 code_actions_task: Default::default(),
1754 document_highlights_task: Default::default(),
1755 pending_rename: Default::default(),
1756 searchable: true,
1757 cursor_shape: Default::default(),
1758 current_line_highlight: EditorSettings::get_global(cx).current_line_highlight,
1759 autoindent_mode: Some(AutoindentMode::EachLine),
1760 collapse_matches: false,
1761 workspace: None,
1762 keymap_context_layers: Default::default(),
1763 input_enabled: true,
1764 use_modal_editing: mode == EditorMode::Full,
1765 read_only: false,
1766 use_autoclose: true,
1767 auto_replace_emoji_shortcode: false,
1768 leader_peer_id: None,
1769 remote_id: None,
1770 hover_state: Default::default(),
1771 hovered_link_state: Default::default(),
1772 inline_completion_provider: None,
1773 active_inline_completion: None,
1774 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1775 expanded_hunks: ExpandedHunks::default(),
1776 gutter_hovered: false,
1777 pixel_position_of_newest_cursor: None,
1778 last_bounds: None,
1779 expect_bounds_change: None,
1780 gutter_dimensions: GutterDimensions::default(),
1781 style: None,
1782 show_cursor_names: false,
1783 hovered_cursors: Default::default(),
1784 editor_actions: Default::default(),
1785 vim_replace_map: Default::default(),
1786 show_inline_completions: mode == EditorMode::Full,
1787 custom_context_menu: None,
1788 show_git_blame_gutter: false,
1789 show_git_blame_inline: false,
1790 show_git_blame_inline_delay_task: None,
1791 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1792 blame: None,
1793 blame_subscription: None,
1794 tasks: Default::default(),
1795 _subscriptions: vec![
1796 cx.observe(&buffer, Self::on_buffer_changed),
1797 cx.subscribe(&buffer, Self::on_buffer_event),
1798 cx.observe(&display_map, Self::on_display_map_changed),
1799 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1800 cx.observe_global::<SettingsStore>(Self::settings_changed),
1801 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1802 cx.observe_window_activation(|editor, cx| {
1803 let active = cx.is_window_active();
1804 editor.blink_manager.update(cx, |blink_manager, cx| {
1805 if active {
1806 blink_manager.enable(cx);
1807 } else {
1808 blink_manager.show_cursor(cx);
1809 blink_manager.disable(cx);
1810 }
1811 });
1812 }),
1813 ],
1814 tasks_update_task: None,
1815 };
1816 this.tasks_update_task = Some(this.refresh_runnables(cx));
1817 this._subscriptions.extend(project_subscriptions);
1818
1819 this.end_selection(cx);
1820 this.scroll_manager.show_scrollbar(cx);
1821
1822 if mode == EditorMode::Full {
1823 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1824 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1825
1826 if this.git_blame_inline_enabled {
1827 this.git_blame_inline_enabled = true;
1828 this.start_git_blame_inline(false, cx);
1829 }
1830 }
1831
1832 this.report_editor_event("open", None, cx);
1833 this
1834 }
1835
1836 pub fn mouse_menu_is_focused(&self, cx: &mut WindowContext) -> bool {
1837 self.mouse_context_menu
1838 .as_ref()
1839 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1840 }
1841
1842 fn key_context(&self, cx: &AppContext) -> KeyContext {
1843 let mut key_context = KeyContext::new_with_defaults();
1844 key_context.add("Editor");
1845 let mode = match self.mode {
1846 EditorMode::SingleLine => "single_line",
1847 EditorMode::AutoHeight { .. } => "auto_height",
1848 EditorMode::Full => "full",
1849 };
1850 key_context.set("mode", mode);
1851 if self.pending_rename.is_some() {
1852 key_context.add("renaming");
1853 }
1854 if self.context_menu_visible() {
1855 match self.context_menu.read().as_ref() {
1856 Some(ContextMenu::Completions(_)) => {
1857 key_context.add("menu");
1858 key_context.add("showing_completions")
1859 }
1860 Some(ContextMenu::CodeActions(_)) => {
1861 key_context.add("menu");
1862 key_context.add("showing_code_actions")
1863 }
1864 None => {}
1865 }
1866 }
1867
1868 for layer in self.keymap_context_layers.values() {
1869 key_context.extend(layer);
1870 }
1871
1872 if let Some(extension) = self
1873 .buffer
1874 .read(cx)
1875 .as_singleton()
1876 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1877 {
1878 key_context.set("extension", extension.to_string());
1879 }
1880
1881 if self.has_active_inline_completion(cx) {
1882 key_context.add("copilot_suggestion");
1883 key_context.add("inline_completion");
1884 }
1885
1886 key_context
1887 }
1888
1889 pub fn new_file(
1890 workspace: &mut Workspace,
1891 _: &workspace::NewFile,
1892 cx: &mut ViewContext<Workspace>,
1893 ) {
1894 let project = workspace.project().clone();
1895 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1896
1897 cx.spawn(|workspace, mut cx| async move {
1898 let buffer = create.await?;
1899 workspace.update(&mut cx, |workspace, cx| {
1900 workspace.add_item_to_active_pane(
1901 Box::new(
1902 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
1903 ),
1904 None,
1905 cx,
1906 )
1907 })
1908 })
1909 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
1910 ErrorCode::RemoteUpgradeRequired => Some(format!(
1911 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1912 e.error_tag("required").unwrap_or("the latest version")
1913 )),
1914 _ => None,
1915 });
1916 }
1917
1918 pub fn new_file_in_direction(
1919 workspace: &mut Workspace,
1920 action: &workspace::NewFileInDirection,
1921 cx: &mut ViewContext<Workspace>,
1922 ) {
1923 let project = workspace.project().clone();
1924 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1925 let direction = action.0;
1926
1927 cx.spawn(|workspace, mut cx| async move {
1928 let buffer = create.await?;
1929 workspace.update(&mut cx, move |workspace, cx| {
1930 workspace.split_item(
1931 direction,
1932 Box::new(
1933 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
1934 ),
1935 cx,
1936 )
1937 })?;
1938 anyhow::Ok(())
1939 })
1940 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
1941 ErrorCode::RemoteUpgradeRequired => Some(format!(
1942 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1943 e.error_tag("required").unwrap_or("the latest version")
1944 )),
1945 _ => None,
1946 });
1947 }
1948
1949 pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
1950 self.buffer.read(cx).replica_id()
1951 }
1952
1953 pub fn leader_peer_id(&self) -> Option<PeerId> {
1954 self.leader_peer_id
1955 }
1956
1957 pub fn buffer(&self) -> &Model<MultiBuffer> {
1958 &self.buffer
1959 }
1960
1961 pub fn workspace(&self) -> Option<View<Workspace>> {
1962 self.workspace.as_ref()?.0.upgrade()
1963 }
1964
1965 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
1966 self.buffer().read(cx).title(cx)
1967 }
1968
1969 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
1970 EditorSnapshot {
1971 mode: self.mode,
1972 show_gutter: self.show_gutter,
1973 show_line_numbers: self.show_line_numbers,
1974 show_git_diff_gutter: self.show_git_diff_gutter,
1975 show_code_actions: self.show_code_actions,
1976 render_git_blame_gutter: self.render_git_blame_gutter(cx),
1977 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1978 scroll_anchor: self.scroll_manager.anchor(),
1979 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1980 placeholder_text: self.placeholder_text.clone(),
1981 is_focused: self.focus_handle.is_focused(cx),
1982 current_line_highlight: self.current_line_highlight,
1983 gutter_hovered: self.gutter_hovered,
1984 }
1985 }
1986
1987 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
1988 self.buffer.read(cx).language_at(point, cx)
1989 }
1990
1991 pub fn file_at<T: ToOffset>(
1992 &self,
1993 point: T,
1994 cx: &AppContext,
1995 ) -> Option<Arc<dyn language::File>> {
1996 self.buffer.read(cx).read(cx).file_at(point).cloned()
1997 }
1998
1999 pub fn active_excerpt(
2000 &self,
2001 cx: &AppContext,
2002 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2003 self.buffer
2004 .read(cx)
2005 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2006 }
2007
2008 pub fn mode(&self) -> EditorMode {
2009 self.mode
2010 }
2011
2012 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2013 self.collaboration_hub.as_deref()
2014 }
2015
2016 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2017 self.collaboration_hub = Some(hub);
2018 }
2019
2020 pub fn set_custom_context_menu(
2021 &mut self,
2022 f: impl 'static
2023 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2024 ) {
2025 self.custom_context_menu = Some(Box::new(f))
2026 }
2027
2028 pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
2029 self.completion_provider = Some(provider);
2030 }
2031
2032 pub fn set_inline_completion_provider<T>(
2033 &mut self,
2034 provider: Option<Model<T>>,
2035 cx: &mut ViewContext<Self>,
2036 ) where
2037 T: InlineCompletionProvider,
2038 {
2039 self.inline_completion_provider =
2040 provider.map(|provider| RegisteredInlineCompletionProvider {
2041 _subscription: cx.observe(&provider, |this, _, cx| {
2042 if this.focus_handle.is_focused(cx) {
2043 this.update_visible_inline_completion(cx);
2044 }
2045 }),
2046 provider: Arc::new(provider),
2047 });
2048 self.refresh_inline_completion(false, cx);
2049 }
2050
2051 pub fn placeholder_text(&self, _cx: &mut WindowContext) -> Option<&str> {
2052 self.placeholder_text.as_deref()
2053 }
2054
2055 pub fn set_placeholder_text(
2056 &mut self,
2057 placeholder_text: impl Into<Arc<str>>,
2058 cx: &mut ViewContext<Self>,
2059 ) {
2060 let placeholder_text = Some(placeholder_text.into());
2061 if self.placeholder_text != placeholder_text {
2062 self.placeholder_text = placeholder_text;
2063 cx.notify();
2064 }
2065 }
2066
2067 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2068 self.cursor_shape = cursor_shape;
2069 cx.notify();
2070 }
2071
2072 pub fn set_current_line_highlight(&mut self, current_line_highlight: CurrentLineHighlight) {
2073 self.current_line_highlight = current_line_highlight;
2074 }
2075
2076 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2077 self.collapse_matches = collapse_matches;
2078 }
2079
2080 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2081 if self.collapse_matches {
2082 return range.start..range.start;
2083 }
2084 range.clone()
2085 }
2086
2087 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2088 if self.display_map.read(cx).clip_at_line_ends != clip {
2089 self.display_map
2090 .update(cx, |map, _| map.clip_at_line_ends = clip);
2091 }
2092 }
2093
2094 pub fn set_keymap_context_layer<Tag: 'static>(
2095 &mut self,
2096 context: KeyContext,
2097 cx: &mut ViewContext<Self>,
2098 ) {
2099 self.keymap_context_layers
2100 .insert(TypeId::of::<Tag>(), context);
2101 cx.notify();
2102 }
2103
2104 pub fn remove_keymap_context_layer<Tag: 'static>(&mut self, cx: &mut ViewContext<Self>) {
2105 self.keymap_context_layers.remove(&TypeId::of::<Tag>());
2106 cx.notify();
2107 }
2108
2109 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2110 self.input_enabled = input_enabled;
2111 }
2112
2113 pub fn set_autoindent(&mut self, autoindent: bool) {
2114 if autoindent {
2115 self.autoindent_mode = Some(AutoindentMode::EachLine);
2116 } else {
2117 self.autoindent_mode = None;
2118 }
2119 }
2120
2121 pub fn read_only(&self, cx: &AppContext) -> bool {
2122 self.read_only || self.buffer.read(cx).read_only()
2123 }
2124
2125 pub fn set_read_only(&mut self, read_only: bool) {
2126 self.read_only = read_only;
2127 }
2128
2129 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2130 self.use_autoclose = autoclose;
2131 }
2132
2133 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2134 self.auto_replace_emoji_shortcode = auto_replace;
2135 }
2136
2137 pub fn set_show_inline_completions(&mut self, show_inline_completions: bool) {
2138 self.show_inline_completions = show_inline_completions;
2139 }
2140
2141 pub fn set_use_modal_editing(&mut self, to: bool) {
2142 self.use_modal_editing = to;
2143 }
2144
2145 pub fn use_modal_editing(&self) -> bool {
2146 self.use_modal_editing
2147 }
2148
2149 fn selections_did_change(
2150 &mut self,
2151 local: bool,
2152 old_cursor_position: &Anchor,
2153 show_completions: bool,
2154 cx: &mut ViewContext<Self>,
2155 ) {
2156 // Copy selections to primary selection buffer
2157 #[cfg(target_os = "linux")]
2158 if local {
2159 let selections = self.selections.all::<usize>(cx);
2160 let buffer_handle = self.buffer.read(cx).read(cx);
2161
2162 let mut text = String::new();
2163 for (index, selection) in selections.iter().enumerate() {
2164 let text_for_selection = buffer_handle
2165 .text_for_range(selection.start..selection.end)
2166 .collect::<String>();
2167
2168 text.push_str(&text_for_selection);
2169 if index != selections.len() - 1 {
2170 text.push('\n');
2171 }
2172 }
2173
2174 if !text.is_empty() {
2175 cx.write_to_primary(ClipboardItem::new(text));
2176 }
2177 }
2178
2179 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2180 self.buffer.update(cx, |buffer, cx| {
2181 buffer.set_active_selections(
2182 &self.selections.disjoint_anchors(),
2183 self.selections.line_mode,
2184 self.cursor_shape,
2185 cx,
2186 )
2187 });
2188 }
2189
2190 let display_map = self
2191 .display_map
2192 .update(cx, |display_map, cx| display_map.snapshot(cx));
2193 let buffer = &display_map.buffer_snapshot;
2194 self.add_selections_state = None;
2195 self.select_next_state = None;
2196 self.select_prev_state = None;
2197 self.select_larger_syntax_node_stack.clear();
2198 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2199 self.snippet_stack
2200 .invalidate(&self.selections.disjoint_anchors(), buffer);
2201 self.take_rename(false, cx);
2202
2203 let new_cursor_position = self.selections.newest_anchor().head();
2204
2205 self.push_to_nav_history(
2206 *old_cursor_position,
2207 Some(new_cursor_position.to_point(buffer)),
2208 cx,
2209 );
2210
2211 if local {
2212 let new_cursor_position = self.selections.newest_anchor().head();
2213 let mut context_menu = self.context_menu.write();
2214 let completion_menu = match context_menu.as_ref() {
2215 Some(ContextMenu::Completions(menu)) => Some(menu),
2216
2217 _ => {
2218 *context_menu = None;
2219 None
2220 }
2221 };
2222
2223 if let Some(completion_menu) = completion_menu {
2224 let cursor_position = new_cursor_position.to_offset(buffer);
2225 let (word_range, kind) = buffer.surrounding_word(completion_menu.initial_position);
2226 if kind == Some(CharKind::Word)
2227 && word_range.to_inclusive().contains(&cursor_position)
2228 {
2229 let mut completion_menu = completion_menu.clone();
2230 drop(context_menu);
2231
2232 let query = Self::completion_query(buffer, cursor_position);
2233 cx.spawn(move |this, mut cx| async move {
2234 completion_menu
2235 .filter(query.as_deref(), cx.background_executor().clone())
2236 .await;
2237
2238 this.update(&mut cx, |this, cx| {
2239 let mut context_menu = this.context_menu.write();
2240 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2241 return;
2242 };
2243
2244 if menu.id > completion_menu.id {
2245 return;
2246 }
2247
2248 *context_menu = Some(ContextMenu::Completions(completion_menu));
2249 drop(context_menu);
2250 cx.notify();
2251 })
2252 })
2253 .detach();
2254
2255 if show_completions {
2256 self.show_completions(&ShowCompletions, cx);
2257 }
2258 } else {
2259 drop(context_menu);
2260 self.hide_context_menu(cx);
2261 }
2262 } else {
2263 drop(context_menu);
2264 }
2265
2266 hide_hover(self, cx);
2267
2268 if old_cursor_position.to_display_point(&display_map).row()
2269 != new_cursor_position.to_display_point(&display_map).row()
2270 {
2271 self.available_code_actions.take();
2272 }
2273 self.refresh_code_actions(cx);
2274 self.refresh_document_highlights(cx);
2275 refresh_matching_bracket_highlights(self, cx);
2276 self.discard_inline_completion(false, cx);
2277 if self.git_blame_inline_enabled {
2278 self.start_inline_blame_timer(cx);
2279 }
2280 }
2281
2282 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2283 cx.emit(EditorEvent::SelectionsChanged { local });
2284
2285 if self.selections.disjoint_anchors().len() == 1 {
2286 cx.emit(SearchEvent::ActiveMatchChanged)
2287 }
2288
2289 cx.notify();
2290 }
2291
2292 pub fn change_selections<R>(
2293 &mut self,
2294 autoscroll: Option<Autoscroll>,
2295 cx: &mut ViewContext<Self>,
2296 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2297 ) -> R {
2298 self.change_selections_inner(autoscroll, true, cx, change)
2299 }
2300
2301 pub fn change_selections_inner<R>(
2302 &mut self,
2303 autoscroll: Option<Autoscroll>,
2304 request_completions: bool,
2305 cx: &mut ViewContext<Self>,
2306 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2307 ) -> R {
2308 let old_cursor_position = self.selections.newest_anchor().head();
2309 self.push_to_selection_history();
2310
2311 let (changed, result) = self.selections.change_with(cx, change);
2312
2313 if changed {
2314 if let Some(autoscroll) = autoscroll {
2315 self.request_autoscroll(autoscroll, cx);
2316 }
2317 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2318 }
2319
2320 result
2321 }
2322
2323 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2324 where
2325 I: IntoIterator<Item = (Range<S>, T)>,
2326 S: ToOffset,
2327 T: Into<Arc<str>>,
2328 {
2329 if self.read_only(cx) {
2330 return;
2331 }
2332
2333 self.buffer
2334 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2335 }
2336
2337 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2338 where
2339 I: IntoIterator<Item = (Range<S>, T)>,
2340 S: ToOffset,
2341 T: Into<Arc<str>>,
2342 {
2343 if self.read_only(cx) {
2344 return;
2345 }
2346
2347 self.buffer.update(cx, |buffer, cx| {
2348 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2349 });
2350 }
2351
2352 pub fn edit_with_block_indent<I, S, T>(
2353 &mut self,
2354 edits: I,
2355 original_indent_columns: Vec<u32>,
2356 cx: &mut ViewContext<Self>,
2357 ) where
2358 I: IntoIterator<Item = (Range<S>, T)>,
2359 S: ToOffset,
2360 T: Into<Arc<str>>,
2361 {
2362 if self.read_only(cx) {
2363 return;
2364 }
2365
2366 self.buffer.update(cx, |buffer, cx| {
2367 buffer.edit(
2368 edits,
2369 Some(AutoindentMode::Block {
2370 original_indent_columns,
2371 }),
2372 cx,
2373 )
2374 });
2375 }
2376
2377 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2378 self.hide_context_menu(cx);
2379
2380 match phase {
2381 SelectPhase::Begin {
2382 position,
2383 add,
2384 click_count,
2385 } => self.begin_selection(position, add, click_count, cx),
2386 SelectPhase::BeginColumnar {
2387 position,
2388 goal_column,
2389 reset,
2390 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2391 SelectPhase::Extend {
2392 position,
2393 click_count,
2394 } => self.extend_selection(position, click_count, cx),
2395 SelectPhase::Update {
2396 position,
2397 goal_column,
2398 scroll_delta,
2399 } => self.update_selection(position, goal_column, scroll_delta, cx),
2400 SelectPhase::End => self.end_selection(cx),
2401 }
2402 }
2403
2404 fn extend_selection(
2405 &mut self,
2406 position: DisplayPoint,
2407 click_count: usize,
2408 cx: &mut ViewContext<Self>,
2409 ) {
2410 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2411 let tail = self.selections.newest::<usize>(cx).tail();
2412 self.begin_selection(position, false, click_count, cx);
2413
2414 let position = position.to_offset(&display_map, Bias::Left);
2415 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2416
2417 let mut pending_selection = self
2418 .selections
2419 .pending_anchor()
2420 .expect("extend_selection not called with pending selection");
2421 if position >= tail {
2422 pending_selection.start = tail_anchor;
2423 } else {
2424 pending_selection.end = tail_anchor;
2425 pending_selection.reversed = true;
2426 }
2427
2428 let mut pending_mode = self.selections.pending_mode().unwrap();
2429 match &mut pending_mode {
2430 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2431 _ => {}
2432 }
2433
2434 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2435 s.set_pending(pending_selection, pending_mode)
2436 });
2437 }
2438
2439 fn begin_selection(
2440 &mut self,
2441 position: DisplayPoint,
2442 add: bool,
2443 click_count: usize,
2444 cx: &mut ViewContext<Self>,
2445 ) {
2446 if !self.focus_handle.is_focused(cx) {
2447 cx.focus(&self.focus_handle);
2448 }
2449
2450 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2451 let buffer = &display_map.buffer_snapshot;
2452 let newest_selection = self.selections.newest_anchor().clone();
2453 let position = display_map.clip_point(position, Bias::Left);
2454
2455 let start;
2456 let end;
2457 let mode;
2458 let auto_scroll;
2459 match click_count {
2460 1 => {
2461 start = buffer.anchor_before(position.to_point(&display_map));
2462 end = start;
2463 mode = SelectMode::Character;
2464 auto_scroll = true;
2465 }
2466 2 => {
2467 let range = movement::surrounding_word(&display_map, position);
2468 start = buffer.anchor_before(range.start.to_point(&display_map));
2469 end = buffer.anchor_before(range.end.to_point(&display_map));
2470 mode = SelectMode::Word(start..end);
2471 auto_scroll = true;
2472 }
2473 3 => {
2474 let position = display_map
2475 .clip_point(position, Bias::Left)
2476 .to_point(&display_map);
2477 let line_start = display_map.prev_line_boundary(position).0;
2478 let next_line_start = buffer.clip_point(
2479 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2480 Bias::Left,
2481 );
2482 start = buffer.anchor_before(line_start);
2483 end = buffer.anchor_before(next_line_start);
2484 mode = SelectMode::Line(start..end);
2485 auto_scroll = true;
2486 }
2487 _ => {
2488 start = buffer.anchor_before(0);
2489 end = buffer.anchor_before(buffer.len());
2490 mode = SelectMode::All;
2491 auto_scroll = false;
2492 }
2493 }
2494
2495 self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
2496 if !add {
2497 s.clear_disjoint();
2498 } else if click_count > 1 {
2499 s.delete(newest_selection.id)
2500 }
2501
2502 s.set_pending_anchor_range(start..end, mode);
2503 });
2504 }
2505
2506 fn begin_columnar_selection(
2507 &mut self,
2508 position: DisplayPoint,
2509 goal_column: u32,
2510 reset: bool,
2511 cx: &mut ViewContext<Self>,
2512 ) {
2513 if !self.focus_handle.is_focused(cx) {
2514 cx.focus(&self.focus_handle);
2515 }
2516
2517 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2518
2519 if reset {
2520 let pointer_position = display_map
2521 .buffer_snapshot
2522 .anchor_before(position.to_point(&display_map));
2523
2524 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2525 s.clear_disjoint();
2526 s.set_pending_anchor_range(
2527 pointer_position..pointer_position,
2528 SelectMode::Character,
2529 );
2530 });
2531 }
2532
2533 let tail = self.selections.newest::<Point>(cx).tail();
2534 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2535
2536 if !reset {
2537 self.select_columns(
2538 tail.to_display_point(&display_map),
2539 position,
2540 goal_column,
2541 &display_map,
2542 cx,
2543 );
2544 }
2545 }
2546
2547 fn update_selection(
2548 &mut self,
2549 position: DisplayPoint,
2550 goal_column: u32,
2551 scroll_delta: gpui::Point<f32>,
2552 cx: &mut ViewContext<Self>,
2553 ) {
2554 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2555
2556 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2557 let tail = tail.to_display_point(&display_map);
2558 self.select_columns(tail, position, goal_column, &display_map, cx);
2559 } else if let Some(mut pending) = self.selections.pending_anchor() {
2560 let buffer = self.buffer.read(cx).snapshot(cx);
2561 let head;
2562 let tail;
2563 let mode = self.selections.pending_mode().unwrap();
2564 match &mode {
2565 SelectMode::Character => {
2566 head = position.to_point(&display_map);
2567 tail = pending.tail().to_point(&buffer);
2568 }
2569 SelectMode::Word(original_range) => {
2570 let original_display_range = original_range.start.to_display_point(&display_map)
2571 ..original_range.end.to_display_point(&display_map);
2572 let original_buffer_range = original_display_range.start.to_point(&display_map)
2573 ..original_display_range.end.to_point(&display_map);
2574 if movement::is_inside_word(&display_map, position)
2575 || original_display_range.contains(&position)
2576 {
2577 let word_range = movement::surrounding_word(&display_map, position);
2578 if word_range.start < original_display_range.start {
2579 head = word_range.start.to_point(&display_map);
2580 } else {
2581 head = word_range.end.to_point(&display_map);
2582 }
2583 } else {
2584 head = position.to_point(&display_map);
2585 }
2586
2587 if head <= original_buffer_range.start {
2588 tail = original_buffer_range.end;
2589 } else {
2590 tail = original_buffer_range.start;
2591 }
2592 }
2593 SelectMode::Line(original_range) => {
2594 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2595
2596 let position = display_map
2597 .clip_point(position, Bias::Left)
2598 .to_point(&display_map);
2599 let line_start = display_map.prev_line_boundary(position).0;
2600 let next_line_start = buffer.clip_point(
2601 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2602 Bias::Left,
2603 );
2604
2605 if line_start < original_range.start {
2606 head = line_start
2607 } else {
2608 head = next_line_start
2609 }
2610
2611 if head <= original_range.start {
2612 tail = original_range.end;
2613 } else {
2614 tail = original_range.start;
2615 }
2616 }
2617 SelectMode::All => {
2618 return;
2619 }
2620 };
2621
2622 if head < tail {
2623 pending.start = buffer.anchor_before(head);
2624 pending.end = buffer.anchor_before(tail);
2625 pending.reversed = true;
2626 } else {
2627 pending.start = buffer.anchor_before(tail);
2628 pending.end = buffer.anchor_before(head);
2629 pending.reversed = false;
2630 }
2631
2632 self.change_selections(None, cx, |s| {
2633 s.set_pending(pending, mode);
2634 });
2635 } else {
2636 log::error!("update_selection dispatched with no pending selection");
2637 return;
2638 }
2639
2640 self.apply_scroll_delta(scroll_delta, cx);
2641 cx.notify();
2642 }
2643
2644 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2645 self.columnar_selection_tail.take();
2646 if self.selections.pending_anchor().is_some() {
2647 let selections = self.selections.all::<usize>(cx);
2648 self.change_selections(None, cx, |s| {
2649 s.select(selections);
2650 s.clear_pending();
2651 });
2652 }
2653 }
2654
2655 fn select_columns(
2656 &mut self,
2657 tail: DisplayPoint,
2658 head: DisplayPoint,
2659 goal_column: u32,
2660 display_map: &DisplaySnapshot,
2661 cx: &mut ViewContext<Self>,
2662 ) {
2663 let start_row = cmp::min(tail.row(), head.row());
2664 let end_row = cmp::max(tail.row(), head.row());
2665 let start_column = cmp::min(tail.column(), goal_column);
2666 let end_column = cmp::max(tail.column(), goal_column);
2667 let reversed = start_column < tail.column();
2668
2669 let selection_ranges = (start_row.0..=end_row.0)
2670 .map(DisplayRow)
2671 .filter_map(|row| {
2672 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2673 let start = display_map
2674 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2675 .to_point(display_map);
2676 let end = display_map
2677 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2678 .to_point(display_map);
2679 if reversed {
2680 Some(end..start)
2681 } else {
2682 Some(start..end)
2683 }
2684 } else {
2685 None
2686 }
2687 })
2688 .collect::<Vec<_>>();
2689
2690 self.change_selections(None, cx, |s| {
2691 s.select_ranges(selection_ranges);
2692 });
2693 cx.notify();
2694 }
2695
2696 pub fn has_pending_nonempty_selection(&self) -> bool {
2697 let pending_nonempty_selection = match self.selections.pending_anchor() {
2698 Some(Selection { start, end, .. }) => start != end,
2699 None => false,
2700 };
2701 pending_nonempty_selection || self.columnar_selection_tail.is_some()
2702 }
2703
2704 pub fn has_pending_selection(&self) -> bool {
2705 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2706 }
2707
2708 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2709 self.clear_expanded_diff_hunks(cx);
2710 if self.dismiss_menus_and_popups(true, cx) {
2711 return;
2712 }
2713
2714 if self.mode == EditorMode::Full {
2715 if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
2716 return;
2717 }
2718 }
2719
2720 cx.propagate();
2721 }
2722
2723 pub fn dismiss_menus_and_popups(
2724 &mut self,
2725 should_report_inline_completion_event: bool,
2726 cx: &mut ViewContext<Self>,
2727 ) -> bool {
2728 if self.take_rename(false, cx).is_some() {
2729 return true;
2730 }
2731
2732 if hide_hover(self, cx) {
2733 return true;
2734 }
2735
2736 if self.hide_context_menu(cx).is_some() {
2737 return true;
2738 }
2739
2740 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2741 return true;
2742 }
2743
2744 if self.snippet_stack.pop().is_some() {
2745 return true;
2746 }
2747
2748 if self.mode == EditorMode::Full {
2749 if self.active_diagnostics.is_some() {
2750 self.dismiss_diagnostics(cx);
2751 return true;
2752 }
2753 }
2754
2755 false
2756 }
2757
2758 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2759 let text: Arc<str> = text.into();
2760
2761 if self.read_only(cx) {
2762 return;
2763 }
2764
2765 let selections = self.selections.all_adjusted(cx);
2766 let mut brace_inserted = false;
2767 let mut edits = Vec::new();
2768 let mut new_selections = Vec::with_capacity(selections.len());
2769 let mut new_autoclose_regions = Vec::new();
2770 let snapshot = self.buffer.read(cx).read(cx);
2771
2772 for (selection, autoclose_region) in
2773 self.selections_with_autoclose_regions(selections, &snapshot)
2774 {
2775 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2776 // Determine if the inserted text matches the opening or closing
2777 // bracket of any of this language's bracket pairs.
2778 let mut bracket_pair = None;
2779 let mut is_bracket_pair_start = false;
2780 let mut is_bracket_pair_end = false;
2781 if !text.is_empty() {
2782 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2783 // and they are removing the character that triggered IME popup.
2784 for (pair, enabled) in scope.brackets() {
2785 if !pair.close {
2786 continue;
2787 }
2788
2789 if enabled && pair.start.ends_with(text.as_ref()) {
2790 bracket_pair = Some(pair.clone());
2791 is_bracket_pair_start = true;
2792 break;
2793 }
2794 if pair.end.as_str() == text.as_ref() {
2795 bracket_pair = Some(pair.clone());
2796 is_bracket_pair_end = true;
2797 break;
2798 }
2799 }
2800 }
2801
2802 if let Some(bracket_pair) = bracket_pair {
2803 if selection.is_empty() {
2804 if is_bracket_pair_start {
2805 let prefix_len = bracket_pair.start.len() - text.len();
2806
2807 // If the inserted text is a suffix of an opening bracket and the
2808 // selection is preceded by the rest of the opening bracket, then
2809 // insert the closing bracket.
2810 let following_text_allows_autoclose = snapshot
2811 .chars_at(selection.start)
2812 .next()
2813 .map_or(true, |c| scope.should_autoclose_before(c));
2814 let preceding_text_matches_prefix = prefix_len == 0
2815 || (selection.start.column >= (prefix_len as u32)
2816 && snapshot.contains_str_at(
2817 Point::new(
2818 selection.start.row,
2819 selection.start.column - (prefix_len as u32),
2820 ),
2821 &bracket_pair.start[..prefix_len],
2822 ));
2823 let autoclose = self.use_autoclose
2824 && snapshot.settings_at(selection.start, cx).use_autoclose;
2825 if autoclose
2826 && following_text_allows_autoclose
2827 && preceding_text_matches_prefix
2828 {
2829 let anchor = snapshot.anchor_before(selection.end);
2830 new_selections.push((selection.map(|_| anchor), text.len()));
2831 new_autoclose_regions.push((
2832 anchor,
2833 text.len(),
2834 selection.id,
2835 bracket_pair.clone(),
2836 ));
2837 edits.push((
2838 selection.range(),
2839 format!("{}{}", text, bracket_pair.end).into(),
2840 ));
2841 brace_inserted = true;
2842 continue;
2843 }
2844 }
2845
2846 if let Some(region) = autoclose_region {
2847 // If the selection is followed by an auto-inserted closing bracket,
2848 // then don't insert that closing bracket again; just move the selection
2849 // past the closing bracket.
2850 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2851 && text.as_ref() == region.pair.end.as_str();
2852 if should_skip {
2853 let anchor = snapshot.anchor_after(selection.end);
2854 new_selections
2855 .push((selection.map(|_| anchor), region.pair.end.len()));
2856 continue;
2857 }
2858 }
2859
2860 let always_treat_brackets_as_autoclosed = snapshot
2861 .settings_at(selection.start, cx)
2862 .always_treat_brackets_as_autoclosed;
2863 if always_treat_brackets_as_autoclosed
2864 && is_bracket_pair_end
2865 && snapshot.contains_str_at(selection.end, text.as_ref())
2866 {
2867 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2868 // and the inserted text is a closing bracket and the selection is followed
2869 // by the closing bracket then move the selection past the closing bracket.
2870 let anchor = snapshot.anchor_after(selection.end);
2871 new_selections.push((selection.map(|_| anchor), text.len()));
2872 continue;
2873 }
2874 }
2875 // If an opening bracket is 1 character long and is typed while
2876 // text is selected, then surround that text with the bracket pair.
2877 else if is_bracket_pair_start && bracket_pair.start.chars().count() == 1 {
2878 edits.push((selection.start..selection.start, text.clone()));
2879 edits.push((
2880 selection.end..selection.end,
2881 bracket_pair.end.as_str().into(),
2882 ));
2883 brace_inserted = true;
2884 new_selections.push((
2885 Selection {
2886 id: selection.id,
2887 start: snapshot.anchor_after(selection.start),
2888 end: snapshot.anchor_before(selection.end),
2889 reversed: selection.reversed,
2890 goal: selection.goal,
2891 },
2892 0,
2893 ));
2894 continue;
2895 }
2896 }
2897 }
2898
2899 if self.auto_replace_emoji_shortcode
2900 && selection.is_empty()
2901 && text.as_ref().ends_with(':')
2902 {
2903 if let Some(possible_emoji_short_code) =
2904 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2905 {
2906 if !possible_emoji_short_code.is_empty() {
2907 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2908 let emoji_shortcode_start = Point::new(
2909 selection.start.row,
2910 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2911 );
2912
2913 // Remove shortcode from buffer
2914 edits.push((
2915 emoji_shortcode_start..selection.start,
2916 "".to_string().into(),
2917 ));
2918 new_selections.push((
2919 Selection {
2920 id: selection.id,
2921 start: snapshot.anchor_after(emoji_shortcode_start),
2922 end: snapshot.anchor_before(selection.start),
2923 reversed: selection.reversed,
2924 goal: selection.goal,
2925 },
2926 0,
2927 ));
2928
2929 // Insert emoji
2930 let selection_start_anchor = snapshot.anchor_after(selection.start);
2931 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2932 edits.push((selection.start..selection.end, emoji.to_string().into()));
2933
2934 continue;
2935 }
2936 }
2937 }
2938 }
2939
2940 // If not handling any auto-close operation, then just replace the selected
2941 // text with the given input and move the selection to the end of the
2942 // newly inserted text.
2943 let anchor = snapshot.anchor_after(selection.end);
2944 new_selections.push((selection.map(|_| anchor), 0));
2945 edits.push((selection.start..selection.end, text.clone()));
2946 }
2947
2948 drop(snapshot);
2949 self.transact(cx, |this, cx| {
2950 this.buffer.update(cx, |buffer, cx| {
2951 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2952 });
2953
2954 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2955 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2956 let snapshot = this.buffer.read(cx).read(cx);
2957 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
2958 .zip(new_selection_deltas)
2959 .map(|(selection, delta)| Selection {
2960 id: selection.id,
2961 start: selection.start + delta,
2962 end: selection.end + delta,
2963 reversed: selection.reversed,
2964 goal: SelectionGoal::None,
2965 })
2966 .collect::<Vec<_>>();
2967
2968 let mut i = 0;
2969 for (position, delta, selection_id, pair) in new_autoclose_regions {
2970 let position = position.to_offset(&snapshot) + delta;
2971 let start = snapshot.anchor_before(position);
2972 let end = snapshot.anchor_after(position);
2973 while let Some(existing_state) = this.autoclose_regions.get(i) {
2974 match existing_state.range.start.cmp(&start, &snapshot) {
2975 Ordering::Less => i += 1,
2976 Ordering::Greater => break,
2977 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
2978 Ordering::Less => i += 1,
2979 Ordering::Equal => break,
2980 Ordering::Greater => break,
2981 },
2982 }
2983 }
2984 this.autoclose_regions.insert(
2985 i,
2986 AutocloseRegion {
2987 selection_id,
2988 range: start..end,
2989 pair,
2990 },
2991 );
2992 }
2993
2994 drop(snapshot);
2995 let had_active_inline_completion = this.has_active_inline_completion(cx);
2996 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
2997 s.select(new_selections)
2998 });
2999
3000 if brace_inserted {
3001 // If we inserted a brace while composing text (i.e. typing `"` on a
3002 // Brazilian keyboard), exit the composing state because most likely
3003 // the user wanted to surround the selection.
3004 this.unmark_text(cx);
3005 } else if EditorSettings::get_global(cx).use_on_type_format {
3006 if let Some(on_type_format_task) =
3007 this.trigger_on_type_formatting(text.to_string(), cx)
3008 {
3009 on_type_format_task.detach_and_log_err(cx);
3010 }
3011 }
3012
3013 let trigger_in_words = !had_active_inline_completion;
3014 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3015 this.refresh_inline_completion(true, cx);
3016 });
3017 }
3018
3019 fn find_possible_emoji_shortcode_at_position(
3020 snapshot: &MultiBufferSnapshot,
3021 position: Point,
3022 ) -> Option<String> {
3023 let mut chars = Vec::new();
3024 let mut found_colon = false;
3025 for char in snapshot.reversed_chars_at(position).take(100) {
3026 // Found a possible emoji shortcode in the middle of the buffer
3027 if found_colon {
3028 if char.is_whitespace() {
3029 chars.reverse();
3030 return Some(chars.iter().collect());
3031 }
3032 // If the previous character is not a whitespace, we are in the middle of a word
3033 // and we only want to complete the shortcode if the word is made up of other emojis
3034 let mut containing_word = String::new();
3035 for ch in snapshot
3036 .reversed_chars_at(position)
3037 .skip(chars.len() + 1)
3038 .take(100)
3039 {
3040 if ch.is_whitespace() {
3041 break;
3042 }
3043 containing_word.push(ch);
3044 }
3045 let containing_word = containing_word.chars().rev().collect::<String>();
3046 if util::word_consists_of_emojis(containing_word.as_str()) {
3047 chars.reverse();
3048 return Some(chars.iter().collect());
3049 }
3050 }
3051
3052 if char.is_whitespace() || !char.is_ascii() {
3053 return None;
3054 }
3055 if char == ':' {
3056 found_colon = true;
3057 } else {
3058 chars.push(char);
3059 }
3060 }
3061 // Found a possible emoji shortcode at the beginning of the buffer
3062 chars.reverse();
3063 Some(chars.iter().collect())
3064 }
3065
3066 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3067 self.transact(cx, |this, cx| {
3068 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3069 let selections = this.selections.all::<usize>(cx);
3070 let multi_buffer = this.buffer.read(cx);
3071 let buffer = multi_buffer.snapshot(cx);
3072 selections
3073 .iter()
3074 .map(|selection| {
3075 let start_point = selection.start.to_point(&buffer);
3076 let mut indent =
3077 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3078 indent.len = cmp::min(indent.len, start_point.column);
3079 let start = selection.start;
3080 let end = selection.end;
3081 let selection_is_empty = start == end;
3082 let language_scope = buffer.language_scope_at(start);
3083 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3084 &language_scope
3085 {
3086 let leading_whitespace_len = buffer
3087 .reversed_chars_at(start)
3088 .take_while(|c| c.is_whitespace() && *c != '\n')
3089 .map(|c| c.len_utf8())
3090 .sum::<usize>();
3091
3092 let trailing_whitespace_len = buffer
3093 .chars_at(end)
3094 .take_while(|c| c.is_whitespace() && *c != '\n')
3095 .map(|c| c.len_utf8())
3096 .sum::<usize>();
3097
3098 let insert_extra_newline =
3099 language.brackets().any(|(pair, enabled)| {
3100 let pair_start = pair.start.trim_end();
3101 let pair_end = pair.end.trim_start();
3102
3103 enabled
3104 && pair.newline
3105 && buffer.contains_str_at(
3106 end + trailing_whitespace_len,
3107 pair_end,
3108 )
3109 && buffer.contains_str_at(
3110 (start - leading_whitespace_len)
3111 .saturating_sub(pair_start.len()),
3112 pair_start,
3113 )
3114 });
3115
3116 // Comment extension on newline is allowed only for cursor selections
3117 let comment_delimiter = maybe!({
3118 if !selection_is_empty {
3119 return None;
3120 }
3121
3122 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3123 return None;
3124 }
3125
3126 let delimiters = language.line_comment_prefixes();
3127 let max_len_of_delimiter =
3128 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3129 let (snapshot, range) =
3130 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3131
3132 let mut index_of_first_non_whitespace = 0;
3133 let comment_candidate = snapshot
3134 .chars_for_range(range)
3135 .skip_while(|c| {
3136 let should_skip = c.is_whitespace();
3137 if should_skip {
3138 index_of_first_non_whitespace += 1;
3139 }
3140 should_skip
3141 })
3142 .take(max_len_of_delimiter)
3143 .collect::<String>();
3144 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3145 comment_candidate.starts_with(comment_prefix.as_ref())
3146 })?;
3147 let cursor_is_placed_after_comment_marker =
3148 index_of_first_non_whitespace + comment_prefix.len()
3149 <= start_point.column as usize;
3150 if cursor_is_placed_after_comment_marker {
3151 Some(comment_prefix.clone())
3152 } else {
3153 None
3154 }
3155 });
3156 (comment_delimiter, insert_extra_newline)
3157 } else {
3158 (None, false)
3159 };
3160
3161 let capacity_for_delimiter = comment_delimiter
3162 .as_deref()
3163 .map(str::len)
3164 .unwrap_or_default();
3165 let mut new_text =
3166 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3167 new_text.push_str("\n");
3168 new_text.extend(indent.chars());
3169 if let Some(delimiter) = &comment_delimiter {
3170 new_text.push_str(&delimiter);
3171 }
3172 if insert_extra_newline {
3173 new_text = new_text.repeat(2);
3174 }
3175
3176 let anchor = buffer.anchor_after(end);
3177 let new_selection = selection.map(|_| anchor);
3178 (
3179 (start..end, new_text),
3180 (insert_extra_newline, new_selection),
3181 )
3182 })
3183 .unzip()
3184 };
3185
3186 this.edit_with_autoindent(edits, cx);
3187 let buffer = this.buffer.read(cx).snapshot(cx);
3188 let new_selections = selection_fixup_info
3189 .into_iter()
3190 .map(|(extra_newline_inserted, new_selection)| {
3191 let mut cursor = new_selection.end.to_point(&buffer);
3192 if extra_newline_inserted {
3193 cursor.row -= 1;
3194 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3195 }
3196 new_selection.map(|_| cursor)
3197 })
3198 .collect();
3199
3200 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3201 this.refresh_inline_completion(true, cx);
3202 });
3203 }
3204
3205 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3206 let buffer = self.buffer.read(cx);
3207 let snapshot = buffer.snapshot(cx);
3208
3209 let mut edits = Vec::new();
3210 let mut rows = Vec::new();
3211
3212 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3213 let cursor = selection.head();
3214 let row = cursor.row;
3215
3216 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3217
3218 let newline = "\n".to_string();
3219 edits.push((start_of_line..start_of_line, newline));
3220
3221 rows.push(row + rows_inserted as u32);
3222 }
3223
3224 self.transact(cx, |editor, cx| {
3225 editor.edit(edits, cx);
3226
3227 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3228 let mut index = 0;
3229 s.move_cursors_with(|map, _, _| {
3230 let row = rows[index];
3231 index += 1;
3232
3233 let point = Point::new(row, 0);
3234 let boundary = map.next_line_boundary(point).1;
3235 let clipped = map.clip_point(boundary, Bias::Left);
3236
3237 (clipped, SelectionGoal::None)
3238 });
3239 });
3240
3241 let mut indent_edits = Vec::new();
3242 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3243 for row in rows {
3244 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3245 for (row, indent) in indents {
3246 if indent.len == 0 {
3247 continue;
3248 }
3249
3250 let text = match indent.kind {
3251 IndentKind::Space => " ".repeat(indent.len as usize),
3252 IndentKind::Tab => "\t".repeat(indent.len as usize),
3253 };
3254 let point = Point::new(row.0, 0);
3255 indent_edits.push((point..point, text));
3256 }
3257 }
3258 editor.edit(indent_edits, cx);
3259 });
3260 }
3261
3262 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3263 let buffer = self.buffer.read(cx);
3264 let snapshot = buffer.snapshot(cx);
3265
3266 let mut edits = Vec::new();
3267 let mut rows = Vec::new();
3268 let mut rows_inserted = 0;
3269
3270 for selection in self.selections.all_adjusted(cx) {
3271 let cursor = selection.head();
3272 let row = cursor.row;
3273
3274 let point = Point::new(row + 1, 0);
3275 let start_of_line = snapshot.clip_point(point, Bias::Left);
3276
3277 let newline = "\n".to_string();
3278 edits.push((start_of_line..start_of_line, newline));
3279
3280 rows_inserted += 1;
3281 rows.push(row + rows_inserted);
3282 }
3283
3284 self.transact(cx, |editor, cx| {
3285 editor.edit(edits, cx);
3286
3287 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3288 let mut index = 0;
3289 s.move_cursors_with(|map, _, _| {
3290 let row = rows[index];
3291 index += 1;
3292
3293 let point = Point::new(row, 0);
3294 let boundary = map.next_line_boundary(point).1;
3295 let clipped = map.clip_point(boundary, Bias::Left);
3296
3297 (clipped, SelectionGoal::None)
3298 });
3299 });
3300
3301 let mut indent_edits = Vec::new();
3302 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3303 for row in rows {
3304 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3305 for (row, indent) in indents {
3306 if indent.len == 0 {
3307 continue;
3308 }
3309
3310 let text = match indent.kind {
3311 IndentKind::Space => " ".repeat(indent.len as usize),
3312 IndentKind::Tab => "\t".repeat(indent.len as usize),
3313 };
3314 let point = Point::new(row.0, 0);
3315 indent_edits.push((point..point, text));
3316 }
3317 }
3318 editor.edit(indent_edits, cx);
3319 });
3320 }
3321
3322 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3323 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3324 original_indent_columns: Vec::new(),
3325 });
3326 self.insert_with_autoindent_mode(text, autoindent, cx);
3327 }
3328
3329 fn insert_with_autoindent_mode(
3330 &mut self,
3331 text: &str,
3332 autoindent_mode: Option<AutoindentMode>,
3333 cx: &mut ViewContext<Self>,
3334 ) {
3335 if self.read_only(cx) {
3336 return;
3337 }
3338
3339 let text: Arc<str> = text.into();
3340 self.transact(cx, |this, cx| {
3341 let old_selections = this.selections.all_adjusted(cx);
3342 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3343 let anchors = {
3344 let snapshot = buffer.read(cx);
3345 old_selections
3346 .iter()
3347 .map(|s| {
3348 let anchor = snapshot.anchor_after(s.head());
3349 s.map(|_| anchor)
3350 })
3351 .collect::<Vec<_>>()
3352 };
3353 buffer.edit(
3354 old_selections
3355 .iter()
3356 .map(|s| (s.start..s.end, text.clone())),
3357 autoindent_mode,
3358 cx,
3359 );
3360 anchors
3361 });
3362
3363 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3364 s.select_anchors(selection_anchors);
3365 })
3366 });
3367 }
3368
3369 fn trigger_completion_on_input(
3370 &mut self,
3371 text: &str,
3372 trigger_in_words: bool,
3373 cx: &mut ViewContext<Self>,
3374 ) {
3375 if self.is_completion_trigger(text, trigger_in_words, cx) {
3376 self.show_completions(&ShowCompletions, cx);
3377 } else {
3378 self.hide_context_menu(cx);
3379 }
3380 }
3381
3382 fn is_completion_trigger(
3383 &self,
3384 text: &str,
3385 trigger_in_words: bool,
3386 cx: &mut ViewContext<Self>,
3387 ) -> bool {
3388 let position = self.selections.newest_anchor().head();
3389 let multibuffer = self.buffer.read(cx);
3390 let Some(buffer) = position
3391 .buffer_id
3392 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3393 else {
3394 return false;
3395 };
3396
3397 if let Some(completion_provider) = &self.completion_provider {
3398 completion_provider.is_completion_trigger(
3399 &buffer,
3400 position.text_anchor,
3401 text,
3402 trigger_in_words,
3403 cx,
3404 )
3405 } else {
3406 false
3407 }
3408 }
3409
3410 /// If any empty selections is touching the start of its innermost containing autoclose
3411 /// region, expand it to select the brackets.
3412 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3413 let selections = self.selections.all::<usize>(cx);
3414 let buffer = self.buffer.read(cx).read(cx);
3415 let new_selections = self
3416 .selections_with_autoclose_regions(selections, &buffer)
3417 .map(|(mut selection, region)| {
3418 if !selection.is_empty() {
3419 return selection;
3420 }
3421
3422 if let Some(region) = region {
3423 let mut range = region.range.to_offset(&buffer);
3424 if selection.start == range.start && range.start >= region.pair.start.len() {
3425 range.start -= region.pair.start.len();
3426 if buffer.contains_str_at(range.start, ®ion.pair.start)
3427 && buffer.contains_str_at(range.end, ®ion.pair.end)
3428 {
3429 range.end += region.pair.end.len();
3430 selection.start = range.start;
3431 selection.end = range.end;
3432
3433 return selection;
3434 }
3435 }
3436 }
3437
3438 let always_treat_brackets_as_autoclosed = buffer
3439 .settings_at(selection.start, cx)
3440 .always_treat_brackets_as_autoclosed;
3441
3442 if !always_treat_brackets_as_autoclosed {
3443 return selection;
3444 }
3445
3446 if let Some(scope) = buffer.language_scope_at(selection.start) {
3447 for (pair, enabled) in scope.brackets() {
3448 if !enabled || !pair.close {
3449 continue;
3450 }
3451
3452 if buffer.contains_str_at(selection.start, &pair.end) {
3453 let pair_start_len = pair.start.len();
3454 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3455 {
3456 selection.start -= pair_start_len;
3457 selection.end += pair.end.len();
3458
3459 return selection;
3460 }
3461 }
3462 }
3463 }
3464
3465 selection
3466 })
3467 .collect();
3468
3469 drop(buffer);
3470 self.change_selections(None, cx, |selections| selections.select(new_selections));
3471 }
3472
3473 /// Iterate the given selections, and for each one, find the smallest surrounding
3474 /// autoclose region. This uses the ordering of the selections and the autoclose
3475 /// regions to avoid repeated comparisons.
3476 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3477 &'a self,
3478 selections: impl IntoIterator<Item = Selection<D>>,
3479 buffer: &'a MultiBufferSnapshot,
3480 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3481 let mut i = 0;
3482 let mut regions = self.autoclose_regions.as_slice();
3483 selections.into_iter().map(move |selection| {
3484 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3485
3486 let mut enclosing = None;
3487 while let Some(pair_state) = regions.get(i) {
3488 if pair_state.range.end.to_offset(buffer) < range.start {
3489 regions = ®ions[i + 1..];
3490 i = 0;
3491 } else if pair_state.range.start.to_offset(buffer) > range.end {
3492 break;
3493 } else {
3494 if pair_state.selection_id == selection.id {
3495 enclosing = Some(pair_state);
3496 }
3497 i += 1;
3498 }
3499 }
3500
3501 (selection.clone(), enclosing)
3502 })
3503 }
3504
3505 /// Remove any autoclose regions that no longer contain their selection.
3506 fn invalidate_autoclose_regions(
3507 &mut self,
3508 mut selections: &[Selection<Anchor>],
3509 buffer: &MultiBufferSnapshot,
3510 ) {
3511 self.autoclose_regions.retain(|state| {
3512 let mut i = 0;
3513 while let Some(selection) = selections.get(i) {
3514 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3515 selections = &selections[1..];
3516 continue;
3517 }
3518 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3519 break;
3520 }
3521 if selection.id == state.selection_id {
3522 return true;
3523 } else {
3524 i += 1;
3525 }
3526 }
3527 false
3528 });
3529 }
3530
3531 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3532 let offset = position.to_offset(buffer);
3533 let (word_range, kind) = buffer.surrounding_word(offset);
3534 if offset > word_range.start && kind == Some(CharKind::Word) {
3535 Some(
3536 buffer
3537 .text_for_range(word_range.start..offset)
3538 .collect::<String>(),
3539 )
3540 } else {
3541 None
3542 }
3543 }
3544
3545 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3546 self.refresh_inlay_hints(
3547 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3548 cx,
3549 );
3550 }
3551
3552 pub fn inlay_hints_enabled(&self) -> bool {
3553 self.inlay_hint_cache.enabled
3554 }
3555
3556 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3557 if self.project.is_none() || self.mode != EditorMode::Full {
3558 return;
3559 }
3560
3561 let reason_description = reason.description();
3562 let ignore_debounce = matches!(
3563 reason,
3564 InlayHintRefreshReason::SettingsChange(_)
3565 | InlayHintRefreshReason::Toggle(_)
3566 | InlayHintRefreshReason::ExcerptsRemoved(_)
3567 );
3568 let (invalidate_cache, required_languages) = match reason {
3569 InlayHintRefreshReason::Toggle(enabled) => {
3570 self.inlay_hint_cache.enabled = enabled;
3571 if enabled {
3572 (InvalidationStrategy::RefreshRequested, None)
3573 } else {
3574 self.inlay_hint_cache.clear();
3575 self.splice_inlays(
3576 self.visible_inlay_hints(cx)
3577 .iter()
3578 .map(|inlay| inlay.id)
3579 .collect(),
3580 Vec::new(),
3581 cx,
3582 );
3583 return;
3584 }
3585 }
3586 InlayHintRefreshReason::SettingsChange(new_settings) => {
3587 match self.inlay_hint_cache.update_settings(
3588 &self.buffer,
3589 new_settings,
3590 self.visible_inlay_hints(cx),
3591 cx,
3592 ) {
3593 ControlFlow::Break(Some(InlaySplice {
3594 to_remove,
3595 to_insert,
3596 })) => {
3597 self.splice_inlays(to_remove, to_insert, cx);
3598 return;
3599 }
3600 ControlFlow::Break(None) => return,
3601 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3602 }
3603 }
3604 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3605 if let Some(InlaySplice {
3606 to_remove,
3607 to_insert,
3608 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3609 {
3610 self.splice_inlays(to_remove, to_insert, cx);
3611 }
3612 return;
3613 }
3614 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3615 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3616 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3617 }
3618 InlayHintRefreshReason::RefreshRequested => {
3619 (InvalidationStrategy::RefreshRequested, None)
3620 }
3621 };
3622
3623 if let Some(InlaySplice {
3624 to_remove,
3625 to_insert,
3626 }) = self.inlay_hint_cache.spawn_hint_refresh(
3627 reason_description,
3628 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3629 invalidate_cache,
3630 ignore_debounce,
3631 cx,
3632 ) {
3633 self.splice_inlays(to_remove, to_insert, cx);
3634 }
3635 }
3636
3637 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
3638 self.display_map
3639 .read(cx)
3640 .current_inlays()
3641 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3642 .cloned()
3643 .collect()
3644 }
3645
3646 pub fn excerpts_for_inlay_hints_query(
3647 &self,
3648 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3649 cx: &mut ViewContext<Editor>,
3650 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3651 let Some(project) = self.project.as_ref() else {
3652 return HashMap::default();
3653 };
3654 let project = project.read(cx);
3655 let multi_buffer = self.buffer().read(cx);
3656 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3657 let multi_buffer_visible_start = self
3658 .scroll_manager
3659 .anchor()
3660 .anchor
3661 .to_point(&multi_buffer_snapshot);
3662 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3663 multi_buffer_visible_start
3664 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3665 Bias::Left,
3666 );
3667 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3668 multi_buffer
3669 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
3670 .into_iter()
3671 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3672 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
3673 let buffer = buffer_handle.read(cx);
3674 let buffer_file = project::File::from_dyn(buffer.file())?;
3675 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3676 let worktree_entry = buffer_worktree
3677 .read(cx)
3678 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3679 if worktree_entry.is_ignored {
3680 return None;
3681 }
3682
3683 let language = buffer.language()?;
3684 if let Some(restrict_to_languages) = restrict_to_languages {
3685 if !restrict_to_languages.contains(language) {
3686 return None;
3687 }
3688 }
3689 Some((
3690 excerpt_id,
3691 (
3692 buffer_handle,
3693 buffer.version().clone(),
3694 excerpt_visible_range,
3695 ),
3696 ))
3697 })
3698 .collect()
3699 }
3700
3701 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3702 TextLayoutDetails {
3703 text_system: cx.text_system().clone(),
3704 editor_style: self.style.clone().unwrap(),
3705 rem_size: cx.rem_size(),
3706 scroll_anchor: self.scroll_manager.anchor(),
3707 visible_rows: self.visible_line_count(),
3708 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3709 }
3710 }
3711
3712 fn splice_inlays(
3713 &self,
3714 to_remove: Vec<InlayId>,
3715 to_insert: Vec<Inlay>,
3716 cx: &mut ViewContext<Self>,
3717 ) {
3718 self.display_map.update(cx, |display_map, cx| {
3719 display_map.splice_inlays(to_remove, to_insert, cx);
3720 });
3721 cx.notify();
3722 }
3723
3724 fn trigger_on_type_formatting(
3725 &self,
3726 input: String,
3727 cx: &mut ViewContext<Self>,
3728 ) -> Option<Task<Result<()>>> {
3729 if input.len() != 1 {
3730 return None;
3731 }
3732
3733 let project = self.project.as_ref()?;
3734 let position = self.selections.newest_anchor().head();
3735 let (buffer, buffer_position) = self
3736 .buffer
3737 .read(cx)
3738 .text_anchor_for_position(position, cx)?;
3739
3740 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3741 // hence we do LSP request & edit on host side only — add formats to host's history.
3742 let push_to_lsp_host_history = true;
3743 // If this is not the host, append its history with new edits.
3744 let push_to_client_history = project.read(cx).is_remote();
3745
3746 let on_type_formatting = project.update(cx, |project, cx| {
3747 project.on_type_format(
3748 buffer.clone(),
3749 buffer_position,
3750 input,
3751 push_to_lsp_host_history,
3752 cx,
3753 )
3754 });
3755 Some(cx.spawn(|editor, mut cx| async move {
3756 if let Some(transaction) = on_type_formatting.await? {
3757 if push_to_client_history {
3758 buffer
3759 .update(&mut cx, |buffer, _| {
3760 buffer.push_transaction(transaction, Instant::now());
3761 })
3762 .ok();
3763 }
3764 editor.update(&mut cx, |editor, cx| {
3765 editor.refresh_document_highlights(cx);
3766 })?;
3767 }
3768 Ok(())
3769 }))
3770 }
3771
3772 pub fn show_completions(&mut self, _: &ShowCompletions, cx: &mut ViewContext<Self>) {
3773 if self.pending_rename.is_some() {
3774 return;
3775 }
3776
3777 let Some(provider) = self.completion_provider.as_ref() else {
3778 return;
3779 };
3780
3781 let position = self.selections.newest_anchor().head();
3782 let (buffer, buffer_position) =
3783 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3784 output
3785 } else {
3786 return;
3787 };
3788
3789 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3790 let completions = provider.completions(&buffer, buffer_position, cx);
3791
3792 let id = post_inc(&mut self.next_completion_id);
3793 let task = cx.spawn(|this, mut cx| {
3794 async move {
3795 let completions = completions.await.log_err();
3796 let menu = if let Some(completions) = completions {
3797 let mut menu = CompletionsMenu {
3798 id,
3799 initial_position: position,
3800 match_candidates: completions
3801 .iter()
3802 .enumerate()
3803 .map(|(id, completion)| {
3804 StringMatchCandidate::new(
3805 id,
3806 completion.label.text[completion.label.filter_range.clone()]
3807 .into(),
3808 )
3809 })
3810 .collect(),
3811 buffer: buffer.clone(),
3812 completions: Arc::new(RwLock::new(completions.into())),
3813 matches: Vec::new().into(),
3814 selected_item: 0,
3815 scroll_handle: UniformListScrollHandle::new(),
3816 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
3817 DebouncedDelay::new(),
3818 )),
3819 };
3820 menu.filter(query.as_deref(), cx.background_executor().clone())
3821 .await;
3822
3823 if menu.matches.is_empty() {
3824 None
3825 } else {
3826 this.update(&mut cx, |editor, cx| {
3827 let completions = menu.completions.clone();
3828 let matches = menu.matches.clone();
3829
3830 let delay_ms = EditorSettings::get_global(cx)
3831 .completion_documentation_secondary_query_debounce;
3832 let delay = Duration::from_millis(delay_ms);
3833
3834 editor
3835 .completion_documentation_pre_resolve_debounce
3836 .fire_new(delay, cx, |editor, cx| {
3837 CompletionsMenu::pre_resolve_completion_documentation(
3838 buffer,
3839 completions,
3840 matches,
3841 editor,
3842 cx,
3843 )
3844 });
3845 })
3846 .ok();
3847 Some(menu)
3848 }
3849 } else {
3850 None
3851 };
3852
3853 this.update(&mut cx, |this, cx| {
3854 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3855
3856 let mut context_menu = this.context_menu.write();
3857 match context_menu.as_ref() {
3858 None => {}
3859
3860 Some(ContextMenu::Completions(prev_menu)) => {
3861 if prev_menu.id > id {
3862 return;
3863 }
3864 }
3865
3866 _ => return,
3867 }
3868
3869 if this.focus_handle.is_focused(cx) && menu.is_some() {
3870 let menu = menu.unwrap();
3871 *context_menu = Some(ContextMenu::Completions(menu));
3872 drop(context_menu);
3873 this.discard_inline_completion(false, cx);
3874 cx.notify();
3875 } else if this.completion_tasks.len() <= 1 {
3876 // If there are no more completion tasks and the last menu was
3877 // empty, we should hide it. If it was already hidden, we should
3878 // also show the copilot completion when available.
3879 drop(context_menu);
3880 if this.hide_context_menu(cx).is_none() {
3881 this.update_visible_inline_completion(cx);
3882 }
3883 }
3884 })?;
3885
3886 Ok::<_, anyhow::Error>(())
3887 }
3888 .log_err()
3889 });
3890
3891 self.completion_tasks.push((id, task));
3892 }
3893
3894 pub fn confirm_completion(
3895 &mut self,
3896 action: &ConfirmCompletion,
3897 cx: &mut ViewContext<Self>,
3898 ) -> Option<Task<Result<()>>> {
3899 use language::ToOffset as _;
3900
3901 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3902 menu
3903 } else {
3904 return None;
3905 };
3906
3907 let mat = completions_menu
3908 .matches
3909 .get(action.item_ix.unwrap_or(completions_menu.selected_item))?;
3910 let buffer_handle = completions_menu.buffer;
3911 let completions = completions_menu.completions.read();
3912 let completion = completions.get(mat.candidate_id)?;
3913 cx.stop_propagation();
3914
3915 let snippet;
3916 let text;
3917
3918 if completion.is_snippet() {
3919 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3920 text = snippet.as_ref().unwrap().text.clone();
3921 } else {
3922 snippet = None;
3923 text = completion.new_text.clone();
3924 };
3925 let selections = self.selections.all::<usize>(cx);
3926 let buffer = buffer_handle.read(cx);
3927 let old_range = completion.old_range.to_offset(buffer);
3928 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3929
3930 let newest_selection = self.selections.newest_anchor();
3931 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3932 return None;
3933 }
3934
3935 let lookbehind = newest_selection
3936 .start
3937 .text_anchor
3938 .to_offset(buffer)
3939 .saturating_sub(old_range.start);
3940 let lookahead = old_range
3941 .end
3942 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3943 let mut common_prefix_len = old_text
3944 .bytes()
3945 .zip(text.bytes())
3946 .take_while(|(a, b)| a == b)
3947 .count();
3948
3949 let snapshot = self.buffer.read(cx).snapshot(cx);
3950 let mut range_to_replace: Option<Range<isize>> = None;
3951 let mut ranges = Vec::new();
3952 for selection in &selections {
3953 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3954 let start = selection.start.saturating_sub(lookbehind);
3955 let end = selection.end + lookahead;
3956 if selection.id == newest_selection.id {
3957 range_to_replace = Some(
3958 ((start + common_prefix_len) as isize - selection.start as isize)
3959 ..(end as isize - selection.start as isize),
3960 );
3961 }
3962 ranges.push(start + common_prefix_len..end);
3963 } else {
3964 common_prefix_len = 0;
3965 ranges.clear();
3966 ranges.extend(selections.iter().map(|s| {
3967 if s.id == newest_selection.id {
3968 range_to_replace = Some(
3969 old_range.start.to_offset_utf16(&snapshot).0 as isize
3970 - selection.start as isize
3971 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3972 - selection.start as isize,
3973 );
3974 old_range.clone()
3975 } else {
3976 s.start..s.end
3977 }
3978 }));
3979 break;
3980 }
3981 }
3982 let text = &text[common_prefix_len..];
3983
3984 cx.emit(EditorEvent::InputHandled {
3985 utf16_range_to_replace: range_to_replace,
3986 text: text.into(),
3987 });
3988
3989 self.transact(cx, |this, cx| {
3990 if let Some(mut snippet) = snippet {
3991 snippet.text = text.to_string();
3992 for tabstop in snippet.tabstops.iter_mut().flatten() {
3993 tabstop.start -= common_prefix_len as isize;
3994 tabstop.end -= common_prefix_len as isize;
3995 }
3996
3997 this.insert_snippet(&ranges, snippet, cx).log_err();
3998 } else {
3999 this.buffer.update(cx, |buffer, cx| {
4000 buffer.edit(
4001 ranges.iter().map(|range| (range.clone(), text)),
4002 this.autoindent_mode.clone(),
4003 cx,
4004 );
4005 });
4006 }
4007
4008 this.refresh_inline_completion(true, cx);
4009 });
4010
4011 if let Some(confirm) = completion.confirm.as_ref() {
4012 (confirm)(cx);
4013 }
4014
4015 if completion.show_new_completions_on_confirm {
4016 self.show_completions(&ShowCompletions, cx);
4017 }
4018
4019 let provider = self.completion_provider.as_ref()?;
4020 let apply_edits = provider.apply_additional_edits_for_completion(
4021 buffer_handle,
4022 completion.clone(),
4023 true,
4024 cx,
4025 );
4026 Some(cx.foreground_executor().spawn(async move {
4027 apply_edits.await?;
4028 Ok(())
4029 }))
4030 }
4031
4032 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4033 let mut context_menu = self.context_menu.write();
4034 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4035 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4036 // Toggle if we're selecting the same one
4037 *context_menu = None;
4038 cx.notify();
4039 return;
4040 } else {
4041 // Otherwise, clear it and start a new one
4042 *context_menu = None;
4043 cx.notify();
4044 }
4045 }
4046 drop(context_menu);
4047 let snapshot = self.snapshot(cx);
4048 let deployed_from_indicator = action.deployed_from_indicator;
4049 let mut task = self.code_actions_task.take();
4050 let action = action.clone();
4051 cx.spawn(|editor, mut cx| async move {
4052 while let Some(prev_task) = task {
4053 prev_task.await;
4054 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4055 }
4056
4057 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4058 if editor.focus_handle.is_focused(cx) {
4059 let multibuffer_point = action
4060 .deployed_from_indicator
4061 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4062 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4063 let (buffer, buffer_row) = snapshot
4064 .buffer_snapshot
4065 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4066 .and_then(|(buffer_snapshot, range)| {
4067 editor
4068 .buffer
4069 .read(cx)
4070 .buffer(buffer_snapshot.remote_id())
4071 .map(|buffer| (buffer, range.start.row))
4072 })?;
4073 let (_, code_actions) = editor
4074 .available_code_actions
4075 .clone()
4076 .and_then(|(location, code_actions)| {
4077 let snapshot = location.buffer.read(cx).snapshot();
4078 let point_range = location.range.to_point(&snapshot);
4079 let point_range = point_range.start.row..=point_range.end.row;
4080 if point_range.contains(&buffer_row) {
4081 Some((location, code_actions))
4082 } else {
4083 None
4084 }
4085 })
4086 .unzip();
4087 let buffer_id = buffer.read(cx).remote_id();
4088 let tasks = editor
4089 .tasks
4090 .get(&(buffer_id, buffer_row))
4091 .map(|t| Arc::new(t.to_owned()));
4092 if tasks.is_none() && code_actions.is_none() {
4093 return None;
4094 }
4095
4096 editor.completion_tasks.clear();
4097 editor.discard_inline_completion(false, cx);
4098 let task_context =
4099 tasks
4100 .as_ref()
4101 .zip(editor.project.clone())
4102 .map(|(tasks, project)| {
4103 let position = Point::new(buffer_row, tasks.column);
4104 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4105 let location = Location {
4106 buffer: buffer.clone(),
4107 range: range_start..range_start,
4108 };
4109 // Fill in the environmental variables from the tree-sitter captures
4110 let mut captured_task_variables = TaskVariables::default();
4111 for (capture_name, value) in tasks.extra_variables.clone() {
4112 captured_task_variables.insert(
4113 task::VariableName::Custom(capture_name.into()),
4114 value.clone(),
4115 );
4116 }
4117 project.update(cx, |project, cx| {
4118 project.task_context_for_location(
4119 captured_task_variables,
4120 location,
4121 cx,
4122 )
4123 })
4124 });
4125
4126 Some(cx.spawn(|editor, mut cx| async move {
4127 let task_context = match task_context {
4128 Some(task_context) => task_context.await,
4129 None => None,
4130 };
4131 let resolved_tasks =
4132 tasks.zip(task_context).map(|(tasks, task_context)| {
4133 Arc::new(ResolvedTasks {
4134 templates: tasks
4135 .templates
4136 .iter()
4137 .filter_map(|(kind, template)| {
4138 template
4139 .resolve_task(&kind.to_id_base(), &task_context)
4140 .map(|task| (kind.clone(), task))
4141 })
4142 .collect(),
4143 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4144 multibuffer_point.row,
4145 tasks.column,
4146 )),
4147 })
4148 });
4149 let spawn_straight_away = resolved_tasks
4150 .as_ref()
4151 .map_or(false, |tasks| tasks.templates.len() == 1)
4152 && code_actions
4153 .as_ref()
4154 .map_or(true, |actions| actions.is_empty());
4155 if let Some(task) = editor
4156 .update(&mut cx, |editor, cx| {
4157 *editor.context_menu.write() =
4158 Some(ContextMenu::CodeActions(CodeActionsMenu {
4159 buffer,
4160 actions: CodeActionContents {
4161 tasks: resolved_tasks,
4162 actions: code_actions,
4163 },
4164 selected_item: Default::default(),
4165 scroll_handle: UniformListScrollHandle::default(),
4166 deployed_from_indicator,
4167 }));
4168 if spawn_straight_away {
4169 if let Some(task) = editor.confirm_code_action(
4170 &ConfirmCodeAction { item_ix: Some(0) },
4171 cx,
4172 ) {
4173 cx.notify();
4174 return task;
4175 }
4176 }
4177 cx.notify();
4178 Task::ready(Ok(()))
4179 })
4180 .ok()
4181 {
4182 task.await
4183 } else {
4184 Ok(())
4185 }
4186 }))
4187 } else {
4188 Some(Task::ready(Ok(())))
4189 }
4190 })?;
4191 if let Some(task) = spawned_test_task {
4192 task.await?;
4193 }
4194
4195 Ok::<_, anyhow::Error>(())
4196 })
4197 .detach_and_log_err(cx);
4198 }
4199
4200 pub fn confirm_code_action(
4201 &mut self,
4202 action: &ConfirmCodeAction,
4203 cx: &mut ViewContext<Self>,
4204 ) -> Option<Task<Result<()>>> {
4205 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4206 menu
4207 } else {
4208 return None;
4209 };
4210 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4211 let action = actions_menu.actions.get(action_ix)?;
4212 let title = action.label();
4213 let buffer = actions_menu.buffer;
4214 let workspace = self.workspace()?;
4215
4216 match action {
4217 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4218 workspace.update(cx, |workspace, cx| {
4219 workspace::tasks::schedule_resolved_task(
4220 workspace,
4221 task_source_kind,
4222 resolved_task,
4223 false,
4224 cx,
4225 );
4226
4227 Some(Task::ready(Ok(())))
4228 })
4229 }
4230 CodeActionsItem::CodeAction(action) => {
4231 let apply_code_actions = workspace
4232 .read(cx)
4233 .project()
4234 .clone()
4235 .update(cx, |project, cx| {
4236 project.apply_code_action(buffer, action, true, cx)
4237 });
4238 let workspace = workspace.downgrade();
4239 Some(cx.spawn(|editor, cx| async move {
4240 let project_transaction = apply_code_actions.await?;
4241 Self::open_project_transaction(
4242 &editor,
4243 workspace,
4244 project_transaction,
4245 title,
4246 cx,
4247 )
4248 .await
4249 }))
4250 }
4251 }
4252 }
4253
4254 pub async fn open_project_transaction(
4255 this: &WeakView<Editor>,
4256 workspace: WeakView<Workspace>,
4257 transaction: ProjectTransaction,
4258 title: String,
4259 mut cx: AsyncWindowContext,
4260 ) -> Result<()> {
4261 let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
4262
4263 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4264 cx.update(|cx| {
4265 entries.sort_unstable_by_key(|(buffer, _)| {
4266 buffer.read(cx).file().map(|f| f.path().clone())
4267 });
4268 })?;
4269
4270 // If the project transaction's edits are all contained within this editor, then
4271 // avoid opening a new editor to display them.
4272
4273 if let Some((buffer, transaction)) = entries.first() {
4274 if entries.len() == 1 {
4275 let excerpt = this.update(&mut cx, |editor, cx| {
4276 editor
4277 .buffer()
4278 .read(cx)
4279 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4280 })?;
4281 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4282 if excerpted_buffer == *buffer {
4283 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4284 let excerpt_range = excerpt_range.to_offset(buffer);
4285 buffer
4286 .edited_ranges_for_transaction::<usize>(transaction)
4287 .all(|range| {
4288 excerpt_range.start <= range.start
4289 && excerpt_range.end >= range.end
4290 })
4291 })?;
4292
4293 if all_edits_within_excerpt {
4294 return Ok(());
4295 }
4296 }
4297 }
4298 }
4299 } else {
4300 return Ok(());
4301 }
4302
4303 let mut ranges_to_highlight = Vec::new();
4304 let excerpt_buffer = cx.new_model(|cx| {
4305 let mut multibuffer =
4306 MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
4307 for (buffer_handle, transaction) in &entries {
4308 let buffer = buffer_handle.read(cx);
4309 ranges_to_highlight.extend(
4310 multibuffer.push_excerpts_with_context_lines(
4311 buffer_handle.clone(),
4312 buffer
4313 .edited_ranges_for_transaction::<usize>(transaction)
4314 .collect(),
4315 DEFAULT_MULTIBUFFER_CONTEXT,
4316 cx,
4317 ),
4318 );
4319 }
4320 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4321 multibuffer
4322 })?;
4323
4324 workspace.update(&mut cx, |workspace, cx| {
4325 let project = workspace.project().clone();
4326 let editor =
4327 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4328 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, cx);
4329 editor.update(cx, |editor, cx| {
4330 editor.highlight_background::<Self>(
4331 &ranges_to_highlight,
4332 |theme| theme.editor_highlighted_line_background,
4333 cx,
4334 );
4335 });
4336 })?;
4337
4338 Ok(())
4339 }
4340
4341 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4342 let project = self.project.clone()?;
4343 let buffer = self.buffer.read(cx);
4344 let newest_selection = self.selections.newest_anchor().clone();
4345 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4346 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4347 if start_buffer != end_buffer {
4348 return None;
4349 }
4350
4351 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4352 cx.background_executor()
4353 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4354 .await;
4355
4356 let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
4357 project.code_actions(&start_buffer, start..end, cx)
4358 }) {
4359 code_actions.await
4360 } else {
4361 Vec::new()
4362 };
4363
4364 this.update(&mut cx, |this, cx| {
4365 this.available_code_actions = if actions.is_empty() {
4366 None
4367 } else {
4368 Some((
4369 Location {
4370 buffer: start_buffer,
4371 range: start..end,
4372 },
4373 actions.into(),
4374 ))
4375 };
4376 cx.notify();
4377 })
4378 .log_err();
4379 }));
4380 None
4381 }
4382
4383 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4384 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4385 self.show_git_blame_inline = false;
4386
4387 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4388 cx.background_executor().timer(delay).await;
4389
4390 this.update(&mut cx, |this, cx| {
4391 this.show_git_blame_inline = true;
4392 cx.notify();
4393 })
4394 .log_err();
4395 }));
4396 }
4397 }
4398
4399 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4400 if self.pending_rename.is_some() {
4401 return None;
4402 }
4403
4404 let project = self.project.clone()?;
4405 let buffer = self.buffer.read(cx);
4406 let newest_selection = self.selections.newest_anchor().clone();
4407 let cursor_position = newest_selection.head();
4408 let (cursor_buffer, cursor_buffer_position) =
4409 buffer.text_anchor_for_position(cursor_position, cx)?;
4410 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4411 if cursor_buffer != tail_buffer {
4412 return None;
4413 }
4414
4415 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4416 cx.background_executor()
4417 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
4418 .await;
4419
4420 let highlights = if let Some(highlights) = project
4421 .update(&mut cx, |project, cx| {
4422 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4423 })
4424 .log_err()
4425 {
4426 highlights.await.log_err()
4427 } else {
4428 None
4429 };
4430
4431 if let Some(highlights) = highlights {
4432 this.update(&mut cx, |this, cx| {
4433 if this.pending_rename.is_some() {
4434 return;
4435 }
4436
4437 let buffer_id = cursor_position.buffer_id;
4438 let buffer = this.buffer.read(cx);
4439 if !buffer
4440 .text_anchor_for_position(cursor_position, cx)
4441 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4442 {
4443 return;
4444 }
4445
4446 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4447 let mut write_ranges = Vec::new();
4448 let mut read_ranges = Vec::new();
4449 for highlight in highlights {
4450 for (excerpt_id, excerpt_range) in
4451 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4452 {
4453 let start = highlight
4454 .range
4455 .start
4456 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4457 let end = highlight
4458 .range
4459 .end
4460 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4461 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4462 continue;
4463 }
4464
4465 let range = Anchor {
4466 buffer_id,
4467 excerpt_id: excerpt_id,
4468 text_anchor: start,
4469 }..Anchor {
4470 buffer_id,
4471 excerpt_id,
4472 text_anchor: end,
4473 };
4474 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4475 write_ranges.push(range);
4476 } else {
4477 read_ranges.push(range);
4478 }
4479 }
4480 }
4481
4482 this.highlight_background::<DocumentHighlightRead>(
4483 &read_ranges,
4484 |theme| theme.editor_document_highlight_read_background,
4485 cx,
4486 );
4487 this.highlight_background::<DocumentHighlightWrite>(
4488 &write_ranges,
4489 |theme| theme.editor_document_highlight_write_background,
4490 cx,
4491 );
4492 cx.notify();
4493 })
4494 .log_err();
4495 }
4496 }));
4497 None
4498 }
4499
4500 fn refresh_inline_completion(
4501 &mut self,
4502 debounce: bool,
4503 cx: &mut ViewContext<Self>,
4504 ) -> Option<()> {
4505 let provider = self.inline_completion_provider()?;
4506 let cursor = self.selections.newest_anchor().head();
4507 let (buffer, cursor_buffer_position) =
4508 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4509 if !self.show_inline_completions
4510 || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
4511 {
4512 self.discard_inline_completion(false, cx);
4513 return None;
4514 }
4515
4516 self.update_visible_inline_completion(cx);
4517 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4518 Some(())
4519 }
4520
4521 fn cycle_inline_completion(
4522 &mut self,
4523 direction: Direction,
4524 cx: &mut ViewContext<Self>,
4525 ) -> Option<()> {
4526 let provider = self.inline_completion_provider()?;
4527 let cursor = self.selections.newest_anchor().head();
4528 let (buffer, cursor_buffer_position) =
4529 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4530 if !self.show_inline_completions
4531 || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
4532 {
4533 return None;
4534 }
4535
4536 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4537 self.update_visible_inline_completion(cx);
4538
4539 Some(())
4540 }
4541
4542 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4543 if !self.has_active_inline_completion(cx) {
4544 self.refresh_inline_completion(false, cx);
4545 return;
4546 }
4547
4548 self.update_visible_inline_completion(cx);
4549 }
4550
4551 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4552 self.show_cursor_names(cx);
4553 }
4554
4555 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4556 self.show_cursor_names = true;
4557 cx.notify();
4558 cx.spawn(|this, mut cx| async move {
4559 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4560 this.update(&mut cx, |this, cx| {
4561 this.show_cursor_names = false;
4562 cx.notify()
4563 })
4564 .ok()
4565 })
4566 .detach();
4567 }
4568
4569 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4570 if self.has_active_inline_completion(cx) {
4571 self.cycle_inline_completion(Direction::Next, cx);
4572 } else {
4573 let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
4574 if is_copilot_disabled {
4575 cx.propagate();
4576 }
4577 }
4578 }
4579
4580 pub fn previous_inline_completion(
4581 &mut self,
4582 _: &PreviousInlineCompletion,
4583 cx: &mut ViewContext<Self>,
4584 ) {
4585 if self.has_active_inline_completion(cx) {
4586 self.cycle_inline_completion(Direction::Prev, cx);
4587 } else {
4588 let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
4589 if is_copilot_disabled {
4590 cx.propagate();
4591 }
4592 }
4593 }
4594
4595 pub fn accept_inline_completion(
4596 &mut self,
4597 _: &AcceptInlineCompletion,
4598 cx: &mut ViewContext<Self>,
4599 ) {
4600 let Some(completion) = self.take_active_inline_completion(cx) else {
4601 return;
4602 };
4603 if let Some(provider) = self.inline_completion_provider() {
4604 provider.accept(cx);
4605 }
4606
4607 cx.emit(EditorEvent::InputHandled {
4608 utf16_range_to_replace: None,
4609 text: completion.text.to_string().into(),
4610 });
4611 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
4612 self.refresh_inline_completion(true, cx);
4613 cx.notify();
4614 }
4615
4616 pub fn accept_partial_inline_completion(
4617 &mut self,
4618 _: &AcceptPartialInlineCompletion,
4619 cx: &mut ViewContext<Self>,
4620 ) {
4621 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
4622 if let Some(completion) = self.take_active_inline_completion(cx) {
4623 let mut partial_completion = completion
4624 .text
4625 .chars()
4626 .by_ref()
4627 .take_while(|c| c.is_alphabetic())
4628 .collect::<String>();
4629 if partial_completion.is_empty() {
4630 partial_completion = completion
4631 .text
4632 .chars()
4633 .by_ref()
4634 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4635 .collect::<String>();
4636 }
4637
4638 cx.emit(EditorEvent::InputHandled {
4639 utf16_range_to_replace: None,
4640 text: partial_completion.clone().into(),
4641 });
4642 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4643 self.refresh_inline_completion(true, cx);
4644 cx.notify();
4645 }
4646 }
4647 }
4648
4649 fn discard_inline_completion(
4650 &mut self,
4651 should_report_inline_completion_event: bool,
4652 cx: &mut ViewContext<Self>,
4653 ) -> bool {
4654 if let Some(provider) = self.inline_completion_provider() {
4655 provider.discard(should_report_inline_completion_event, cx);
4656 }
4657
4658 self.take_active_inline_completion(cx).is_some()
4659 }
4660
4661 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
4662 if let Some(completion) = self.active_inline_completion.as_ref() {
4663 let buffer = self.buffer.read(cx).read(cx);
4664 completion.position.is_valid(&buffer)
4665 } else {
4666 false
4667 }
4668 }
4669
4670 fn take_active_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<Inlay> {
4671 let completion = self.active_inline_completion.take()?;
4672 self.display_map.update(cx, |map, cx| {
4673 map.splice_inlays(vec![completion.id], Default::default(), cx);
4674 });
4675 let buffer = self.buffer.read(cx).read(cx);
4676
4677 if completion.position.is_valid(&buffer) {
4678 Some(completion)
4679 } else {
4680 None
4681 }
4682 }
4683
4684 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
4685 let selection = self.selections.newest_anchor();
4686 let cursor = selection.head();
4687
4688 if self.context_menu.read().is_none()
4689 && self.completion_tasks.is_empty()
4690 && selection.start == selection.end
4691 {
4692 if let Some(provider) = self.inline_completion_provider() {
4693 if let Some((buffer, cursor_buffer_position)) =
4694 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
4695 {
4696 if let Some(text) =
4697 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
4698 {
4699 let text = Rope::from(text);
4700 let mut to_remove = Vec::new();
4701 if let Some(completion) = self.active_inline_completion.take() {
4702 to_remove.push(completion.id);
4703 }
4704
4705 let completion_inlay =
4706 Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
4707 self.active_inline_completion = Some(completion_inlay.clone());
4708 self.display_map.update(cx, move |map, cx| {
4709 map.splice_inlays(to_remove, vec![completion_inlay], cx)
4710 });
4711 cx.notify();
4712 return;
4713 }
4714 }
4715 }
4716 }
4717
4718 self.discard_inline_completion(false, cx);
4719 }
4720
4721 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
4722 Some(self.inline_completion_provider.as_ref()?.provider.clone())
4723 }
4724
4725 fn render_code_actions_indicator(
4726 &self,
4727 _style: &EditorStyle,
4728 row: DisplayRow,
4729 is_active: bool,
4730 cx: &mut ViewContext<Self>,
4731 ) -> Option<IconButton> {
4732 if self.available_code_actions.is_some() {
4733 Some(
4734 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
4735 .icon_size(IconSize::XSmall)
4736 .size(ui::ButtonSize::None)
4737 .icon_color(Color::Muted)
4738 .selected(is_active)
4739 .on_click(cx.listener(move |editor, _e, cx| {
4740 editor.focus(cx);
4741 editor.toggle_code_actions(
4742 &ToggleCodeActions {
4743 deployed_from_indicator: Some(row),
4744 },
4745 cx,
4746 );
4747 })),
4748 )
4749 } else {
4750 None
4751 }
4752 }
4753
4754 fn clear_tasks(&mut self) {
4755 self.tasks.clear()
4756 }
4757
4758 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
4759 if let Some(_) = self.tasks.insert(key, value) {
4760 // This case should hopefully be rare, but just in case...
4761 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
4762 }
4763 }
4764
4765 fn render_run_indicator(
4766 &self,
4767 _style: &EditorStyle,
4768 is_active: bool,
4769 row: DisplayRow,
4770 cx: &mut ViewContext<Self>,
4771 ) -> IconButton {
4772 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
4773 .icon_size(IconSize::XSmall)
4774 .size(ui::ButtonSize::None)
4775 .icon_color(Color::Muted)
4776 .selected(is_active)
4777 .on_click(cx.listener(move |editor, _e, cx| {
4778 editor.focus(cx);
4779 editor.toggle_code_actions(
4780 &ToggleCodeActions {
4781 deployed_from_indicator: Some(row),
4782 },
4783 cx,
4784 );
4785 }))
4786 }
4787
4788 pub fn context_menu_visible(&self) -> bool {
4789 self.context_menu
4790 .read()
4791 .as_ref()
4792 .map_or(false, |menu| menu.visible())
4793 }
4794
4795 fn render_context_menu(
4796 &self,
4797 cursor_position: DisplayPoint,
4798 style: &EditorStyle,
4799 max_height: Pixels,
4800 cx: &mut ViewContext<Editor>,
4801 ) -> Option<(ContextMenuOrigin, AnyElement)> {
4802 self.context_menu.read().as_ref().map(|menu| {
4803 menu.render(
4804 cursor_position,
4805 style,
4806 max_height,
4807 self.workspace.as_ref().map(|(w, _)| w.clone()),
4808 cx,
4809 )
4810 })
4811 }
4812
4813 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
4814 cx.notify();
4815 self.completion_tasks.clear();
4816 let context_menu = self.context_menu.write().take();
4817 if context_menu.is_some() {
4818 self.update_visible_inline_completion(cx);
4819 }
4820 context_menu
4821 }
4822
4823 pub fn insert_snippet(
4824 &mut self,
4825 insertion_ranges: &[Range<usize>],
4826 snippet: Snippet,
4827 cx: &mut ViewContext<Self>,
4828 ) -> Result<()> {
4829 struct Tabstop<T> {
4830 is_end_tabstop: bool,
4831 ranges: Vec<Range<T>>,
4832 }
4833
4834 let tabstops = self.buffer.update(cx, |buffer, cx| {
4835 let snippet_text: Arc<str> = snippet.text.clone().into();
4836 buffer.edit(
4837 insertion_ranges
4838 .iter()
4839 .cloned()
4840 .map(|range| (range, snippet_text.clone())),
4841 Some(AutoindentMode::EachLine),
4842 cx,
4843 );
4844
4845 let snapshot = &*buffer.read(cx);
4846 let snippet = &snippet;
4847 snippet
4848 .tabstops
4849 .iter()
4850 .map(|tabstop| {
4851 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
4852 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
4853 });
4854 let mut tabstop_ranges = tabstop
4855 .iter()
4856 .flat_map(|tabstop_range| {
4857 let mut delta = 0_isize;
4858 insertion_ranges.iter().map(move |insertion_range| {
4859 let insertion_start = insertion_range.start as isize + delta;
4860 delta +=
4861 snippet.text.len() as isize - insertion_range.len() as isize;
4862
4863 let start = ((insertion_start + tabstop_range.start) as usize)
4864 .min(snapshot.len());
4865 let end = ((insertion_start + tabstop_range.end) as usize)
4866 .min(snapshot.len());
4867 snapshot.anchor_before(start)..snapshot.anchor_after(end)
4868 })
4869 })
4870 .collect::<Vec<_>>();
4871 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
4872
4873 Tabstop {
4874 is_end_tabstop,
4875 ranges: tabstop_ranges,
4876 }
4877 })
4878 .collect::<Vec<_>>()
4879 });
4880
4881 if let Some(tabstop) = tabstops.first() {
4882 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
4883 s.select_ranges(tabstop.ranges.iter().cloned());
4884 });
4885
4886 // If we're already at the last tabstop and it's at the end of the snippet,
4887 // we're done, we don't need to keep the state around.
4888 if !tabstop.is_end_tabstop {
4889 let ranges = tabstops
4890 .into_iter()
4891 .map(|tabstop| tabstop.ranges)
4892 .collect::<Vec<_>>();
4893 self.snippet_stack.push(SnippetState {
4894 active_index: 0,
4895 ranges,
4896 });
4897 }
4898
4899 // Check whether the just-entered snippet ends with an auto-closable bracket.
4900 if self.autoclose_regions.is_empty() {
4901 let snapshot = self.buffer.read(cx).snapshot(cx);
4902 for selection in &mut self.selections.all::<Point>(cx) {
4903 let selection_head = selection.head();
4904 let Some(scope) = snapshot.language_scope_at(selection_head) else {
4905 continue;
4906 };
4907
4908 let mut bracket_pair = None;
4909 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
4910 let prev_chars = snapshot
4911 .reversed_chars_at(selection_head)
4912 .collect::<String>();
4913 for (pair, enabled) in scope.brackets() {
4914 if enabled
4915 && pair.close
4916 && prev_chars.starts_with(pair.start.as_str())
4917 && next_chars.starts_with(pair.end.as_str())
4918 {
4919 bracket_pair = Some(pair.clone());
4920 break;
4921 }
4922 }
4923 if let Some(pair) = bracket_pair {
4924 let start = snapshot.anchor_after(selection_head);
4925 let end = snapshot.anchor_after(selection_head);
4926 self.autoclose_regions.push(AutocloseRegion {
4927 selection_id: selection.id,
4928 range: start..end,
4929 pair,
4930 });
4931 }
4932 }
4933 }
4934 }
4935 Ok(())
4936 }
4937
4938 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
4939 self.move_to_snippet_tabstop(Bias::Right, cx)
4940 }
4941
4942 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
4943 self.move_to_snippet_tabstop(Bias::Left, cx)
4944 }
4945
4946 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
4947 if let Some(mut snippet) = self.snippet_stack.pop() {
4948 match bias {
4949 Bias::Left => {
4950 if snippet.active_index > 0 {
4951 snippet.active_index -= 1;
4952 } else {
4953 self.snippet_stack.push(snippet);
4954 return false;
4955 }
4956 }
4957 Bias::Right => {
4958 if snippet.active_index + 1 < snippet.ranges.len() {
4959 snippet.active_index += 1;
4960 } else {
4961 self.snippet_stack.push(snippet);
4962 return false;
4963 }
4964 }
4965 }
4966 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
4967 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
4968 s.select_anchor_ranges(current_ranges.iter().cloned())
4969 });
4970 // If snippet state is not at the last tabstop, push it back on the stack
4971 if snippet.active_index + 1 < snippet.ranges.len() {
4972 self.snippet_stack.push(snippet);
4973 }
4974 return true;
4975 }
4976 }
4977
4978 false
4979 }
4980
4981 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
4982 self.transact(cx, |this, cx| {
4983 this.select_all(&SelectAll, cx);
4984 this.insert("", cx);
4985 });
4986 }
4987
4988 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
4989 self.transact(cx, |this, cx| {
4990 this.select_autoclose_pair(cx);
4991 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
4992 if !this.selections.line_mode {
4993 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
4994 for selection in &mut selections {
4995 if selection.is_empty() {
4996 let old_head = selection.head();
4997 let mut new_head =
4998 movement::left(&display_map, old_head.to_display_point(&display_map))
4999 .to_point(&display_map);
5000 if let Some((buffer, line_buffer_range)) = display_map
5001 .buffer_snapshot
5002 .buffer_line_for_row(MultiBufferRow(old_head.row))
5003 {
5004 let indent_size =
5005 buffer.indent_size_for_line(line_buffer_range.start.row);
5006 let indent_len = match indent_size.kind {
5007 IndentKind::Space => {
5008 buffer.settings_at(line_buffer_range.start, cx).tab_size
5009 }
5010 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5011 };
5012 if old_head.column <= indent_size.len && old_head.column > 0 {
5013 let indent_len = indent_len.get();
5014 new_head = cmp::min(
5015 new_head,
5016 MultiBufferPoint::new(
5017 old_head.row,
5018 ((old_head.column - 1) / indent_len) * indent_len,
5019 ),
5020 );
5021 }
5022 }
5023
5024 selection.set_head(new_head, SelectionGoal::None);
5025 }
5026 }
5027 }
5028
5029 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5030 this.insert("", cx);
5031 this.refresh_inline_completion(true, cx);
5032 });
5033 }
5034
5035 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5036 self.transact(cx, |this, cx| {
5037 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5038 let line_mode = s.line_mode;
5039 s.move_with(|map, selection| {
5040 if selection.is_empty() && !line_mode {
5041 let cursor = movement::right(map, selection.head());
5042 selection.end = cursor;
5043 selection.reversed = true;
5044 selection.goal = SelectionGoal::None;
5045 }
5046 })
5047 });
5048 this.insert("", cx);
5049 this.refresh_inline_completion(true, cx);
5050 });
5051 }
5052
5053 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5054 if self.move_to_prev_snippet_tabstop(cx) {
5055 return;
5056 }
5057
5058 self.outdent(&Outdent, cx);
5059 }
5060
5061 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5062 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5063 return;
5064 }
5065
5066 let mut selections = self.selections.all_adjusted(cx);
5067 let buffer = self.buffer.read(cx);
5068 let snapshot = buffer.snapshot(cx);
5069 let rows_iter = selections.iter().map(|s| s.head().row);
5070 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5071
5072 let mut edits = Vec::new();
5073 let mut prev_edited_row = 0;
5074 let mut row_delta = 0;
5075 for selection in &mut selections {
5076 if selection.start.row != prev_edited_row {
5077 row_delta = 0;
5078 }
5079 prev_edited_row = selection.end.row;
5080
5081 // If the selection is non-empty, then increase the indentation of the selected lines.
5082 if !selection.is_empty() {
5083 row_delta =
5084 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5085 continue;
5086 }
5087
5088 // If the selection is empty and the cursor is in the leading whitespace before the
5089 // suggested indentation, then auto-indent the line.
5090 let cursor = selection.head();
5091 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5092 if let Some(suggested_indent) =
5093 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5094 {
5095 if cursor.column < suggested_indent.len
5096 && cursor.column <= current_indent.len
5097 && current_indent.len <= suggested_indent.len
5098 {
5099 selection.start = Point::new(cursor.row, suggested_indent.len);
5100 selection.end = selection.start;
5101 if row_delta == 0 {
5102 edits.extend(Buffer::edit_for_indent_size_adjustment(
5103 cursor.row,
5104 current_indent,
5105 suggested_indent,
5106 ));
5107 row_delta = suggested_indent.len - current_indent.len;
5108 }
5109 continue;
5110 }
5111 }
5112
5113 // Otherwise, insert a hard or soft tab.
5114 let settings = buffer.settings_at(cursor, cx);
5115 let tab_size = if settings.hard_tabs {
5116 IndentSize::tab()
5117 } else {
5118 let tab_size = settings.tab_size.get();
5119 let char_column = snapshot
5120 .text_for_range(Point::new(cursor.row, 0)..cursor)
5121 .flat_map(str::chars)
5122 .count()
5123 + row_delta as usize;
5124 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5125 IndentSize::spaces(chars_to_next_tab_stop)
5126 };
5127 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5128 selection.end = selection.start;
5129 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5130 row_delta += tab_size.len;
5131 }
5132
5133 self.transact(cx, |this, cx| {
5134 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5135 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5136 this.refresh_inline_completion(true, cx);
5137 });
5138 }
5139
5140 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5141 if self.read_only(cx) {
5142 return;
5143 }
5144 let mut selections = self.selections.all::<Point>(cx);
5145 let mut prev_edited_row = 0;
5146 let mut row_delta = 0;
5147 let mut edits = Vec::new();
5148 let buffer = self.buffer.read(cx);
5149 let snapshot = buffer.snapshot(cx);
5150 for selection in &mut selections {
5151 if selection.start.row != prev_edited_row {
5152 row_delta = 0;
5153 }
5154 prev_edited_row = selection.end.row;
5155
5156 row_delta =
5157 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5158 }
5159
5160 self.transact(cx, |this, cx| {
5161 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5162 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5163 });
5164 }
5165
5166 fn indent_selection(
5167 buffer: &MultiBuffer,
5168 snapshot: &MultiBufferSnapshot,
5169 selection: &mut Selection<Point>,
5170 edits: &mut Vec<(Range<Point>, String)>,
5171 delta_for_start_row: u32,
5172 cx: &AppContext,
5173 ) -> u32 {
5174 let settings = buffer.settings_at(selection.start, cx);
5175 let tab_size = settings.tab_size.get();
5176 let indent_kind = if settings.hard_tabs {
5177 IndentKind::Tab
5178 } else {
5179 IndentKind::Space
5180 };
5181 let mut start_row = selection.start.row;
5182 let mut end_row = selection.end.row + 1;
5183
5184 // If a selection ends at the beginning of a line, don't indent
5185 // that last line.
5186 if selection.end.column == 0 && selection.end.row > selection.start.row {
5187 end_row -= 1;
5188 }
5189
5190 // Avoid re-indenting a row that has already been indented by a
5191 // previous selection, but still update this selection's column
5192 // to reflect that indentation.
5193 if delta_for_start_row > 0 {
5194 start_row += 1;
5195 selection.start.column += delta_for_start_row;
5196 if selection.end.row == selection.start.row {
5197 selection.end.column += delta_for_start_row;
5198 }
5199 }
5200
5201 let mut delta_for_end_row = 0;
5202 let has_multiple_rows = start_row + 1 != end_row;
5203 for row in start_row..end_row {
5204 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5205 let indent_delta = match (current_indent.kind, indent_kind) {
5206 (IndentKind::Space, IndentKind::Space) => {
5207 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5208 IndentSize::spaces(columns_to_next_tab_stop)
5209 }
5210 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5211 (_, IndentKind::Tab) => IndentSize::tab(),
5212 };
5213
5214 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5215 0
5216 } else {
5217 selection.start.column
5218 };
5219 let row_start = Point::new(row, start);
5220 edits.push((
5221 row_start..row_start,
5222 indent_delta.chars().collect::<String>(),
5223 ));
5224
5225 // Update this selection's endpoints to reflect the indentation.
5226 if row == selection.start.row {
5227 selection.start.column += indent_delta.len;
5228 }
5229 if row == selection.end.row {
5230 selection.end.column += indent_delta.len;
5231 delta_for_end_row = indent_delta.len;
5232 }
5233 }
5234
5235 if selection.start.row == selection.end.row {
5236 delta_for_start_row + delta_for_end_row
5237 } else {
5238 delta_for_end_row
5239 }
5240 }
5241
5242 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5243 if self.read_only(cx) {
5244 return;
5245 }
5246 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5247 let selections = self.selections.all::<Point>(cx);
5248 let mut deletion_ranges = Vec::new();
5249 let mut last_outdent = None;
5250 {
5251 let buffer = self.buffer.read(cx);
5252 let snapshot = buffer.snapshot(cx);
5253 for selection in &selections {
5254 let settings = buffer.settings_at(selection.start, cx);
5255 let tab_size = settings.tab_size.get();
5256 let mut rows = selection.spanned_rows(false, &display_map);
5257
5258 // Avoid re-outdenting a row that has already been outdented by a
5259 // previous selection.
5260 if let Some(last_row) = last_outdent {
5261 if last_row == rows.start {
5262 rows.start = rows.start.next_row();
5263 }
5264 }
5265 let has_multiple_rows = rows.len() > 1;
5266 for row in rows.iter_rows() {
5267 let indent_size = snapshot.indent_size_for_line(row);
5268 if indent_size.len > 0 {
5269 let deletion_len = match indent_size.kind {
5270 IndentKind::Space => {
5271 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5272 if columns_to_prev_tab_stop == 0 {
5273 tab_size
5274 } else {
5275 columns_to_prev_tab_stop
5276 }
5277 }
5278 IndentKind::Tab => 1,
5279 };
5280 let start = if has_multiple_rows
5281 || deletion_len > selection.start.column
5282 || indent_size.len < selection.start.column
5283 {
5284 0
5285 } else {
5286 selection.start.column - deletion_len
5287 };
5288 deletion_ranges.push(
5289 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5290 );
5291 last_outdent = Some(row);
5292 }
5293 }
5294 }
5295 }
5296
5297 self.transact(cx, |this, cx| {
5298 this.buffer.update(cx, |buffer, cx| {
5299 let empty_str: Arc<str> = "".into();
5300 buffer.edit(
5301 deletion_ranges
5302 .into_iter()
5303 .map(|range| (range, empty_str.clone())),
5304 None,
5305 cx,
5306 );
5307 });
5308 let selections = this.selections.all::<usize>(cx);
5309 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5310 });
5311 }
5312
5313 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5314 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5315 let selections = self.selections.all::<Point>(cx);
5316
5317 let mut new_cursors = Vec::new();
5318 let mut edit_ranges = Vec::new();
5319 let mut selections = selections.iter().peekable();
5320 while let Some(selection) = selections.next() {
5321 let mut rows = selection.spanned_rows(false, &display_map);
5322 let goal_display_column = selection.head().to_display_point(&display_map).column();
5323
5324 // Accumulate contiguous regions of rows that we want to delete.
5325 while let Some(next_selection) = selections.peek() {
5326 let next_rows = next_selection.spanned_rows(false, &display_map);
5327 if next_rows.start <= rows.end {
5328 rows.end = next_rows.end;
5329 selections.next().unwrap();
5330 } else {
5331 break;
5332 }
5333 }
5334
5335 let buffer = &display_map.buffer_snapshot;
5336 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5337 let edit_end;
5338 let cursor_buffer_row;
5339 if buffer.max_point().row >= rows.end.0 {
5340 // If there's a line after the range, delete the \n from the end of the row range
5341 // and position the cursor on the next line.
5342 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5343 cursor_buffer_row = rows.end;
5344 } else {
5345 // If there isn't a line after the range, delete the \n from the line before the
5346 // start of the row range and position the cursor there.
5347 edit_start = edit_start.saturating_sub(1);
5348 edit_end = buffer.len();
5349 cursor_buffer_row = rows.start.previous_row();
5350 }
5351
5352 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5353 *cursor.column_mut() =
5354 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5355
5356 new_cursors.push((
5357 selection.id,
5358 buffer.anchor_after(cursor.to_point(&display_map)),
5359 ));
5360 edit_ranges.push(edit_start..edit_end);
5361 }
5362
5363 self.transact(cx, |this, cx| {
5364 let buffer = this.buffer.update(cx, |buffer, cx| {
5365 let empty_str: Arc<str> = "".into();
5366 buffer.edit(
5367 edit_ranges
5368 .into_iter()
5369 .map(|range| (range, empty_str.clone())),
5370 None,
5371 cx,
5372 );
5373 buffer.snapshot(cx)
5374 });
5375 let new_selections = new_cursors
5376 .into_iter()
5377 .map(|(id, cursor)| {
5378 let cursor = cursor.to_point(&buffer);
5379 Selection {
5380 id,
5381 start: cursor,
5382 end: cursor,
5383 reversed: false,
5384 goal: SelectionGoal::None,
5385 }
5386 })
5387 .collect();
5388
5389 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5390 s.select(new_selections);
5391 });
5392 });
5393 }
5394
5395 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5396 if self.read_only(cx) {
5397 return;
5398 }
5399 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5400 for selection in self.selections.all::<Point>(cx) {
5401 let start = MultiBufferRow(selection.start.row);
5402 let end = if selection.start.row == selection.end.row {
5403 MultiBufferRow(selection.start.row + 1)
5404 } else {
5405 MultiBufferRow(selection.end.row)
5406 };
5407
5408 if let Some(last_row_range) = row_ranges.last_mut() {
5409 if start <= last_row_range.end {
5410 last_row_range.end = end;
5411 continue;
5412 }
5413 }
5414 row_ranges.push(start..end);
5415 }
5416
5417 let snapshot = self.buffer.read(cx).snapshot(cx);
5418 let mut cursor_positions = Vec::new();
5419 for row_range in &row_ranges {
5420 let anchor = snapshot.anchor_before(Point::new(
5421 row_range.end.previous_row().0,
5422 snapshot.line_len(row_range.end.previous_row()),
5423 ));
5424 cursor_positions.push(anchor..anchor);
5425 }
5426
5427 self.transact(cx, |this, cx| {
5428 for row_range in row_ranges.into_iter().rev() {
5429 for row in row_range.iter_rows().rev() {
5430 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5431 let next_line_row = row.next_row();
5432 let indent = snapshot.indent_size_for_line(next_line_row);
5433 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5434
5435 let replace = if snapshot.line_len(next_line_row) > indent.len {
5436 " "
5437 } else {
5438 ""
5439 };
5440
5441 this.buffer.update(cx, |buffer, cx| {
5442 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5443 });
5444 }
5445 }
5446
5447 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5448 s.select_anchor_ranges(cursor_positions)
5449 });
5450 });
5451 }
5452
5453 pub fn sort_lines_case_sensitive(
5454 &mut self,
5455 _: &SortLinesCaseSensitive,
5456 cx: &mut ViewContext<Self>,
5457 ) {
5458 self.manipulate_lines(cx, |lines| lines.sort())
5459 }
5460
5461 pub fn sort_lines_case_insensitive(
5462 &mut self,
5463 _: &SortLinesCaseInsensitive,
5464 cx: &mut ViewContext<Self>,
5465 ) {
5466 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5467 }
5468
5469 pub fn unique_lines_case_insensitive(
5470 &mut self,
5471 _: &UniqueLinesCaseInsensitive,
5472 cx: &mut ViewContext<Self>,
5473 ) {
5474 self.manipulate_lines(cx, |lines| {
5475 let mut seen = HashSet::default();
5476 lines.retain(|line| seen.insert(line.to_lowercase()));
5477 })
5478 }
5479
5480 pub fn unique_lines_case_sensitive(
5481 &mut self,
5482 _: &UniqueLinesCaseSensitive,
5483 cx: &mut ViewContext<Self>,
5484 ) {
5485 self.manipulate_lines(cx, |lines| {
5486 let mut seen = HashSet::default();
5487 lines.retain(|line| seen.insert(*line));
5488 })
5489 }
5490
5491 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
5492 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
5493 if !revert_changes.is_empty() {
5494 self.transact(cx, |editor, cx| {
5495 editor.buffer().update(cx, |multi_buffer, cx| {
5496 for (buffer_id, changes) in revert_changes {
5497 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
5498 buffer.update(cx, |buffer, cx| {
5499 buffer.edit(
5500 changes.into_iter().map(|(range, text)| {
5501 (range, text.to_string().map(Arc::<str>::from))
5502 }),
5503 None,
5504 cx,
5505 );
5506 });
5507 }
5508 }
5509 });
5510 editor.change_selections(None, cx, |selections| selections.refresh());
5511 });
5512 }
5513 }
5514
5515 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
5516 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
5517 let project_path = buffer.read(cx).project_path(cx)?;
5518 let project = self.project.as_ref()?.read(cx);
5519 let entry = project.entry_for_path(&project_path, cx)?;
5520 let abs_path = project.absolute_path(&project_path, cx)?;
5521 let parent = if entry.is_symlink {
5522 abs_path.canonicalize().ok()?
5523 } else {
5524 abs_path
5525 }
5526 .parent()?
5527 .to_path_buf();
5528 Some(parent)
5529 }) {
5530 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
5531 }
5532 }
5533
5534 fn gather_revert_changes(
5535 &mut self,
5536 selections: &[Selection<Anchor>],
5537 cx: &mut ViewContext<'_, Editor>,
5538 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
5539 let mut revert_changes = HashMap::default();
5540 self.buffer.update(cx, |multi_buffer, cx| {
5541 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
5542 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
5543 Self::prepare_revert_change(&mut revert_changes, &multi_buffer, &hunk, cx);
5544 }
5545 });
5546 revert_changes
5547 }
5548
5549 fn prepare_revert_change(
5550 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
5551 multi_buffer: &MultiBuffer,
5552 hunk: &DiffHunk<MultiBufferRow>,
5553 cx: &mut AppContext,
5554 ) -> Option<()> {
5555 let buffer = multi_buffer.buffer(hunk.buffer_id)?;
5556 let buffer = buffer.read(cx);
5557 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
5558 let buffer_snapshot = buffer.snapshot();
5559 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
5560 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
5561 probe
5562 .0
5563 .start
5564 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
5565 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
5566 }) {
5567 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
5568 Some(())
5569 } else {
5570 None
5571 }
5572 }
5573
5574 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
5575 self.manipulate_lines(cx, |lines| lines.reverse())
5576 }
5577
5578 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
5579 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
5580 }
5581
5582 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
5583 where
5584 Fn: FnMut(&mut Vec<&str>),
5585 {
5586 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5587 let buffer = self.buffer.read(cx).snapshot(cx);
5588
5589 let mut edits = Vec::new();
5590
5591 let selections = self.selections.all::<Point>(cx);
5592 let mut selections = selections.iter().peekable();
5593 let mut contiguous_row_selections = Vec::new();
5594 let mut new_selections = Vec::new();
5595 let mut added_lines = 0;
5596 let mut removed_lines = 0;
5597
5598 while let Some(selection) = selections.next() {
5599 let (start_row, end_row) = consume_contiguous_rows(
5600 &mut contiguous_row_selections,
5601 selection,
5602 &display_map,
5603 &mut selections,
5604 );
5605
5606 let start_point = Point::new(start_row.0, 0);
5607 let end_point = Point::new(
5608 end_row.previous_row().0,
5609 buffer.line_len(end_row.previous_row()),
5610 );
5611 let text = buffer
5612 .text_for_range(start_point..end_point)
5613 .collect::<String>();
5614
5615 let mut lines = text.split('\n').collect_vec();
5616
5617 let lines_before = lines.len();
5618 callback(&mut lines);
5619 let lines_after = lines.len();
5620
5621 edits.push((start_point..end_point, lines.join("\n")));
5622
5623 // Selections must change based on added and removed line count
5624 let start_row =
5625 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
5626 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
5627 new_selections.push(Selection {
5628 id: selection.id,
5629 start: start_row,
5630 end: end_row,
5631 goal: SelectionGoal::None,
5632 reversed: selection.reversed,
5633 });
5634
5635 if lines_after > lines_before {
5636 added_lines += lines_after - lines_before;
5637 } else if lines_before > lines_after {
5638 removed_lines += lines_before - lines_after;
5639 }
5640 }
5641
5642 self.transact(cx, |this, cx| {
5643 let buffer = this.buffer.update(cx, |buffer, cx| {
5644 buffer.edit(edits, None, cx);
5645 buffer.snapshot(cx)
5646 });
5647
5648 // Recalculate offsets on newly edited buffer
5649 let new_selections = new_selections
5650 .iter()
5651 .map(|s| {
5652 let start_point = Point::new(s.start.0, 0);
5653 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
5654 Selection {
5655 id: s.id,
5656 start: buffer.point_to_offset(start_point),
5657 end: buffer.point_to_offset(end_point),
5658 goal: s.goal,
5659 reversed: s.reversed,
5660 }
5661 })
5662 .collect();
5663
5664 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5665 s.select(new_selections);
5666 });
5667
5668 this.request_autoscroll(Autoscroll::fit(), cx);
5669 });
5670 }
5671
5672 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
5673 self.manipulate_text(cx, |text| text.to_uppercase())
5674 }
5675
5676 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
5677 self.manipulate_text(cx, |text| text.to_lowercase())
5678 }
5679
5680 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
5681 self.manipulate_text(cx, |text| {
5682 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
5683 // https://github.com/rutrum/convert-case/issues/16
5684 text.split('\n')
5685 .map(|line| line.to_case(Case::Title))
5686 .join("\n")
5687 })
5688 }
5689
5690 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
5691 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
5692 }
5693
5694 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
5695 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
5696 }
5697
5698 pub fn convert_to_upper_camel_case(
5699 &mut self,
5700 _: &ConvertToUpperCamelCase,
5701 cx: &mut ViewContext<Self>,
5702 ) {
5703 self.manipulate_text(cx, |text| {
5704 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
5705 // https://github.com/rutrum/convert-case/issues/16
5706 text.split('\n')
5707 .map(|line| line.to_case(Case::UpperCamel))
5708 .join("\n")
5709 })
5710 }
5711
5712 pub fn convert_to_lower_camel_case(
5713 &mut self,
5714 _: &ConvertToLowerCamelCase,
5715 cx: &mut ViewContext<Self>,
5716 ) {
5717 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
5718 }
5719
5720 pub fn convert_to_opposite_case(
5721 &mut self,
5722 _: &ConvertToOppositeCase,
5723 cx: &mut ViewContext<Self>,
5724 ) {
5725 self.manipulate_text(cx, |text| {
5726 text.chars()
5727 .fold(String::with_capacity(text.len()), |mut t, c| {
5728 if c.is_uppercase() {
5729 t.extend(c.to_lowercase());
5730 } else {
5731 t.extend(c.to_uppercase());
5732 }
5733 t
5734 })
5735 })
5736 }
5737
5738 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
5739 where
5740 Fn: FnMut(&str) -> String,
5741 {
5742 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5743 let buffer = self.buffer.read(cx).snapshot(cx);
5744
5745 let mut new_selections = Vec::new();
5746 let mut edits = Vec::new();
5747 let mut selection_adjustment = 0i32;
5748
5749 for selection in self.selections.all::<usize>(cx) {
5750 let selection_is_empty = selection.is_empty();
5751
5752 let (start, end) = if selection_is_empty {
5753 let word_range = movement::surrounding_word(
5754 &display_map,
5755 selection.start.to_display_point(&display_map),
5756 );
5757 let start = word_range.start.to_offset(&display_map, Bias::Left);
5758 let end = word_range.end.to_offset(&display_map, Bias::Left);
5759 (start, end)
5760 } else {
5761 (selection.start, selection.end)
5762 };
5763
5764 let text = buffer.text_for_range(start..end).collect::<String>();
5765 let old_length = text.len() as i32;
5766 let text = callback(&text);
5767
5768 new_selections.push(Selection {
5769 start: (start as i32 - selection_adjustment) as usize,
5770 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
5771 goal: SelectionGoal::None,
5772 ..selection
5773 });
5774
5775 selection_adjustment += old_length - text.len() as i32;
5776
5777 edits.push((start..end, text));
5778 }
5779
5780 self.transact(cx, |this, cx| {
5781 this.buffer.update(cx, |buffer, cx| {
5782 buffer.edit(edits, None, cx);
5783 });
5784
5785 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5786 s.select(new_selections);
5787 });
5788
5789 this.request_autoscroll(Autoscroll::fit(), cx);
5790 });
5791 }
5792
5793 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
5794 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5795 let buffer = &display_map.buffer_snapshot;
5796 let selections = self.selections.all::<Point>(cx);
5797
5798 let mut edits = Vec::new();
5799 let mut selections_iter = selections.iter().peekable();
5800 while let Some(selection) = selections_iter.next() {
5801 // Avoid duplicating the same lines twice.
5802 let mut rows = selection.spanned_rows(false, &display_map);
5803
5804 while let Some(next_selection) = selections_iter.peek() {
5805 let next_rows = next_selection.spanned_rows(false, &display_map);
5806 if next_rows.start < rows.end {
5807 rows.end = next_rows.end;
5808 selections_iter.next().unwrap();
5809 } else {
5810 break;
5811 }
5812 }
5813
5814 // Copy the text from the selected row region and splice it either at the start
5815 // or end of the region.
5816 let start = Point::new(rows.start.0, 0);
5817 let end = Point::new(
5818 rows.end.previous_row().0,
5819 buffer.line_len(rows.end.previous_row()),
5820 );
5821 let text = buffer
5822 .text_for_range(start..end)
5823 .chain(Some("\n"))
5824 .collect::<String>();
5825 let insert_location = if upwards {
5826 Point::new(rows.end.0, 0)
5827 } else {
5828 start
5829 };
5830 edits.push((insert_location..insert_location, text));
5831 }
5832
5833 self.transact(cx, |this, cx| {
5834 this.buffer.update(cx, |buffer, cx| {
5835 buffer.edit(edits, None, cx);
5836 });
5837
5838 this.request_autoscroll(Autoscroll::fit(), cx);
5839 });
5840 }
5841
5842 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
5843 self.duplicate_line(true, cx);
5844 }
5845
5846 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
5847 self.duplicate_line(false, cx);
5848 }
5849
5850 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
5851 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5852 let buffer = self.buffer.read(cx).snapshot(cx);
5853
5854 let mut edits = Vec::new();
5855 let mut unfold_ranges = Vec::new();
5856 let mut refold_ranges = Vec::new();
5857
5858 let selections = self.selections.all::<Point>(cx);
5859 let mut selections = selections.iter().peekable();
5860 let mut contiguous_row_selections = Vec::new();
5861 let mut new_selections = Vec::new();
5862
5863 while let Some(selection) = selections.next() {
5864 // Find all the selections that span a contiguous row range
5865 let (start_row, end_row) = consume_contiguous_rows(
5866 &mut contiguous_row_selections,
5867 selection,
5868 &display_map,
5869 &mut selections,
5870 );
5871
5872 // Move the text spanned by the row range to be before the line preceding the row range
5873 if start_row.0 > 0 {
5874 let range_to_move = Point::new(
5875 start_row.previous_row().0,
5876 buffer.line_len(start_row.previous_row()),
5877 )
5878 ..Point::new(
5879 end_row.previous_row().0,
5880 buffer.line_len(end_row.previous_row()),
5881 );
5882 let insertion_point = display_map
5883 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
5884 .0;
5885
5886 // Don't move lines across excerpts
5887 if buffer
5888 .excerpt_boundaries_in_range((
5889 Bound::Excluded(insertion_point),
5890 Bound::Included(range_to_move.end),
5891 ))
5892 .next()
5893 .is_none()
5894 {
5895 let text = buffer
5896 .text_for_range(range_to_move.clone())
5897 .flat_map(|s| s.chars())
5898 .skip(1)
5899 .chain(['\n'])
5900 .collect::<String>();
5901
5902 edits.push((
5903 buffer.anchor_after(range_to_move.start)
5904 ..buffer.anchor_before(range_to_move.end),
5905 String::new(),
5906 ));
5907 let insertion_anchor = buffer.anchor_after(insertion_point);
5908 edits.push((insertion_anchor..insertion_anchor, text));
5909
5910 let row_delta = range_to_move.start.row - insertion_point.row + 1;
5911
5912 // Move selections up
5913 new_selections.extend(contiguous_row_selections.drain(..).map(
5914 |mut selection| {
5915 selection.start.row -= row_delta;
5916 selection.end.row -= row_delta;
5917 selection
5918 },
5919 ));
5920
5921 // Move folds up
5922 unfold_ranges.push(range_to_move.clone());
5923 for fold in display_map.folds_in_range(
5924 buffer.anchor_before(range_to_move.start)
5925 ..buffer.anchor_after(range_to_move.end),
5926 ) {
5927 let mut start = fold.range.start.to_point(&buffer);
5928 let mut end = fold.range.end.to_point(&buffer);
5929 start.row -= row_delta;
5930 end.row -= row_delta;
5931 refold_ranges.push((start..end, fold.placeholder.clone()));
5932 }
5933 }
5934 }
5935
5936 // If we didn't move line(s), preserve the existing selections
5937 new_selections.append(&mut contiguous_row_selections);
5938 }
5939
5940 self.transact(cx, |this, cx| {
5941 this.unfold_ranges(unfold_ranges, true, true, cx);
5942 this.buffer.update(cx, |buffer, cx| {
5943 for (range, text) in edits {
5944 buffer.edit([(range, text)], None, cx);
5945 }
5946 });
5947 this.fold_ranges(refold_ranges, true, cx);
5948 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5949 s.select(new_selections);
5950 })
5951 });
5952 }
5953
5954 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
5955 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5956 let buffer = self.buffer.read(cx).snapshot(cx);
5957
5958 let mut edits = Vec::new();
5959 let mut unfold_ranges = Vec::new();
5960 let mut refold_ranges = Vec::new();
5961
5962 let selections = self.selections.all::<Point>(cx);
5963 let mut selections = selections.iter().peekable();
5964 let mut contiguous_row_selections = Vec::new();
5965 let mut new_selections = Vec::new();
5966
5967 while let Some(selection) = selections.next() {
5968 // Find all the selections that span a contiguous row range
5969 let (start_row, end_row) = consume_contiguous_rows(
5970 &mut contiguous_row_selections,
5971 selection,
5972 &display_map,
5973 &mut selections,
5974 );
5975
5976 // Move the text spanned by the row range to be after the last line of the row range
5977 if end_row.0 <= buffer.max_point().row {
5978 let range_to_move =
5979 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
5980 let insertion_point = display_map
5981 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
5982 .0;
5983
5984 // Don't move lines across excerpt boundaries
5985 if buffer
5986 .excerpt_boundaries_in_range((
5987 Bound::Excluded(range_to_move.start),
5988 Bound::Included(insertion_point),
5989 ))
5990 .next()
5991 .is_none()
5992 {
5993 let mut text = String::from("\n");
5994 text.extend(buffer.text_for_range(range_to_move.clone()));
5995 text.pop(); // Drop trailing newline
5996 edits.push((
5997 buffer.anchor_after(range_to_move.start)
5998 ..buffer.anchor_before(range_to_move.end),
5999 String::new(),
6000 ));
6001 let insertion_anchor = buffer.anchor_after(insertion_point);
6002 edits.push((insertion_anchor..insertion_anchor, text));
6003
6004 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6005
6006 // Move selections down
6007 new_selections.extend(contiguous_row_selections.drain(..).map(
6008 |mut selection| {
6009 selection.start.row += row_delta;
6010 selection.end.row += row_delta;
6011 selection
6012 },
6013 ));
6014
6015 // Move folds down
6016 unfold_ranges.push(range_to_move.clone());
6017 for fold in display_map.folds_in_range(
6018 buffer.anchor_before(range_to_move.start)
6019 ..buffer.anchor_after(range_to_move.end),
6020 ) {
6021 let mut start = fold.range.start.to_point(&buffer);
6022 let mut end = fold.range.end.to_point(&buffer);
6023 start.row += row_delta;
6024 end.row += row_delta;
6025 refold_ranges.push((start..end, fold.placeholder.clone()));
6026 }
6027 }
6028 }
6029
6030 // If we didn't move line(s), preserve the existing selections
6031 new_selections.append(&mut contiguous_row_selections);
6032 }
6033
6034 self.transact(cx, |this, cx| {
6035 this.unfold_ranges(unfold_ranges, true, true, cx);
6036 this.buffer.update(cx, |buffer, cx| {
6037 for (range, text) in edits {
6038 buffer.edit([(range, text)], None, cx);
6039 }
6040 });
6041 this.fold_ranges(refold_ranges, true, cx);
6042 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6043 });
6044 }
6045
6046 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6047 let text_layout_details = &self.text_layout_details(cx);
6048 self.transact(cx, |this, cx| {
6049 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6050 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6051 let line_mode = s.line_mode;
6052 s.move_with(|display_map, selection| {
6053 if !selection.is_empty() || line_mode {
6054 return;
6055 }
6056
6057 let mut head = selection.head();
6058 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6059 if head.column() == display_map.line_len(head.row()) {
6060 transpose_offset = display_map
6061 .buffer_snapshot
6062 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6063 }
6064
6065 if transpose_offset == 0 {
6066 return;
6067 }
6068
6069 *head.column_mut() += 1;
6070 head = display_map.clip_point(head, Bias::Right);
6071 let goal = SelectionGoal::HorizontalPosition(
6072 display_map
6073 .x_for_display_point(head, &text_layout_details)
6074 .into(),
6075 );
6076 selection.collapse_to(head, goal);
6077
6078 let transpose_start = display_map
6079 .buffer_snapshot
6080 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6081 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6082 let transpose_end = display_map
6083 .buffer_snapshot
6084 .clip_offset(transpose_offset + 1, Bias::Right);
6085 if let Some(ch) =
6086 display_map.buffer_snapshot.chars_at(transpose_start).next()
6087 {
6088 edits.push((transpose_start..transpose_offset, String::new()));
6089 edits.push((transpose_end..transpose_end, ch.to_string()));
6090 }
6091 }
6092 });
6093 edits
6094 });
6095 this.buffer
6096 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6097 let selections = this.selections.all::<usize>(cx);
6098 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6099 s.select(selections);
6100 });
6101 });
6102 }
6103
6104 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6105 let mut text = String::new();
6106 let buffer = self.buffer.read(cx).snapshot(cx);
6107 let mut selections = self.selections.all::<Point>(cx);
6108 let mut clipboard_selections = Vec::with_capacity(selections.len());
6109 {
6110 let max_point = buffer.max_point();
6111 let mut is_first = true;
6112 for selection in &mut selections {
6113 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6114 if is_entire_line {
6115 selection.start = Point::new(selection.start.row, 0);
6116 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6117 selection.goal = SelectionGoal::None;
6118 }
6119 if is_first {
6120 is_first = false;
6121 } else {
6122 text += "\n";
6123 }
6124 let mut len = 0;
6125 for chunk in buffer.text_for_range(selection.start..selection.end) {
6126 text.push_str(chunk);
6127 len += chunk.len();
6128 }
6129 clipboard_selections.push(ClipboardSelection {
6130 len,
6131 is_entire_line,
6132 first_line_indent: buffer
6133 .indent_size_for_line(MultiBufferRow(selection.start.row))
6134 .len,
6135 });
6136 }
6137 }
6138
6139 self.transact(cx, |this, cx| {
6140 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6141 s.select(selections);
6142 });
6143 this.insert("", cx);
6144 cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
6145 });
6146 }
6147
6148 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6149 let selections = self.selections.all::<Point>(cx);
6150 let buffer = self.buffer.read(cx).read(cx);
6151 let mut text = String::new();
6152
6153 let mut clipboard_selections = Vec::with_capacity(selections.len());
6154 {
6155 let max_point = buffer.max_point();
6156 let mut is_first = true;
6157 for selection in selections.iter() {
6158 let mut start = selection.start;
6159 let mut end = selection.end;
6160 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6161 if is_entire_line {
6162 start = Point::new(start.row, 0);
6163 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6164 }
6165 if is_first {
6166 is_first = false;
6167 } else {
6168 text += "\n";
6169 }
6170 let mut len = 0;
6171 for chunk in buffer.text_for_range(start..end) {
6172 text.push_str(chunk);
6173 len += chunk.len();
6174 }
6175 clipboard_selections.push(ClipboardSelection {
6176 len,
6177 is_entire_line,
6178 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6179 });
6180 }
6181 }
6182
6183 cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
6184 }
6185
6186 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
6187 if self.read_only(cx) {
6188 return;
6189 }
6190
6191 self.transact(cx, |this, cx| {
6192 if let Some(item) = cx.read_from_clipboard() {
6193 let clipboard_text = Cow::Borrowed(item.text());
6194 if let Some(mut clipboard_selections) = item.metadata::<Vec<ClipboardSelection>>() {
6195 let old_selections = this.selections.all::<usize>(cx);
6196 let all_selections_were_entire_line =
6197 clipboard_selections.iter().all(|s| s.is_entire_line);
6198 let first_selection_indent_column =
6199 clipboard_selections.first().map(|s| s.first_line_indent);
6200 if clipboard_selections.len() != old_selections.len() {
6201 clipboard_selections.drain(..);
6202 }
6203
6204 this.buffer.update(cx, |buffer, cx| {
6205 let snapshot = buffer.read(cx);
6206 let mut start_offset = 0;
6207 let mut edits = Vec::new();
6208 let mut original_indent_columns = Vec::new();
6209 let line_mode = this.selections.line_mode;
6210 for (ix, selection) in old_selections.iter().enumerate() {
6211 let to_insert;
6212 let entire_line;
6213 let original_indent_column;
6214 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6215 let end_offset = start_offset + clipboard_selection.len;
6216 to_insert = &clipboard_text[start_offset..end_offset];
6217 entire_line = clipboard_selection.is_entire_line;
6218 start_offset = end_offset + 1;
6219 original_indent_column =
6220 Some(clipboard_selection.first_line_indent);
6221 } else {
6222 to_insert = clipboard_text.as_str();
6223 entire_line = all_selections_were_entire_line;
6224 original_indent_column = first_selection_indent_column
6225 }
6226
6227 // If the corresponding selection was empty when this slice of the
6228 // clipboard text was written, then the entire line containing the
6229 // selection was copied. If this selection is also currently empty,
6230 // then paste the line before the current line of the buffer.
6231 let range = if selection.is_empty() && !line_mode && entire_line {
6232 let column = selection.start.to_point(&snapshot).column as usize;
6233 let line_start = selection.start - column;
6234 line_start..line_start
6235 } else {
6236 selection.range()
6237 };
6238
6239 edits.push((range, to_insert));
6240 original_indent_columns.extend(original_indent_column);
6241 }
6242 drop(snapshot);
6243
6244 buffer.edit(
6245 edits,
6246 Some(AutoindentMode::Block {
6247 original_indent_columns,
6248 }),
6249 cx,
6250 );
6251 });
6252
6253 let selections = this.selections.all::<usize>(cx);
6254 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6255 } else {
6256 this.insert(&clipboard_text, cx);
6257 }
6258 }
6259 });
6260 }
6261
6262 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
6263 if self.read_only(cx) {
6264 return;
6265 }
6266
6267 if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
6268 if let Some((selections, _)) = self.selection_history.transaction(tx_id).cloned() {
6269 self.change_selections(None, cx, |s| {
6270 s.select_anchors(selections.to_vec());
6271 });
6272 }
6273 self.request_autoscroll(Autoscroll::fit(), cx);
6274 self.unmark_text(cx);
6275 self.refresh_inline_completion(true, cx);
6276 cx.emit(EditorEvent::Edited);
6277 cx.emit(EditorEvent::TransactionUndone {
6278 transaction_id: tx_id,
6279 });
6280 }
6281 }
6282
6283 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
6284 if self.read_only(cx) {
6285 return;
6286 }
6287
6288 if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
6289 if let Some((_, Some(selections))) = self.selection_history.transaction(tx_id).cloned()
6290 {
6291 self.change_selections(None, cx, |s| {
6292 s.select_anchors(selections.to_vec());
6293 });
6294 }
6295 self.request_autoscroll(Autoscroll::fit(), cx);
6296 self.unmark_text(cx);
6297 self.refresh_inline_completion(true, cx);
6298 cx.emit(EditorEvent::Edited);
6299 }
6300 }
6301
6302 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
6303 self.buffer
6304 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
6305 }
6306
6307 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
6308 self.buffer
6309 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
6310 }
6311
6312 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
6313 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6314 let line_mode = s.line_mode;
6315 s.move_with(|map, selection| {
6316 let cursor = if selection.is_empty() && !line_mode {
6317 movement::left(map, selection.start)
6318 } else {
6319 selection.start
6320 };
6321 selection.collapse_to(cursor, SelectionGoal::None);
6322 });
6323 })
6324 }
6325
6326 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
6327 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6328 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
6329 })
6330 }
6331
6332 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
6333 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6334 let line_mode = s.line_mode;
6335 s.move_with(|map, selection| {
6336 let cursor = if selection.is_empty() && !line_mode {
6337 movement::right(map, selection.end)
6338 } else {
6339 selection.end
6340 };
6341 selection.collapse_to(cursor, SelectionGoal::None)
6342 });
6343 })
6344 }
6345
6346 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
6347 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6348 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
6349 })
6350 }
6351
6352 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
6353 if self.take_rename(true, cx).is_some() {
6354 return;
6355 }
6356
6357 if matches!(self.mode, EditorMode::SingleLine) {
6358 cx.propagate();
6359 return;
6360 }
6361
6362 let text_layout_details = &self.text_layout_details(cx);
6363
6364 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6365 let line_mode = s.line_mode;
6366 s.move_with(|map, selection| {
6367 if !selection.is_empty() && !line_mode {
6368 selection.goal = SelectionGoal::None;
6369 }
6370 let (cursor, goal) = movement::up(
6371 map,
6372 selection.start,
6373 selection.goal,
6374 false,
6375 &text_layout_details,
6376 );
6377 selection.collapse_to(cursor, goal);
6378 });
6379 })
6380 }
6381
6382 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
6383 if self.take_rename(true, cx).is_some() {
6384 return;
6385 }
6386
6387 if matches!(self.mode, EditorMode::SingleLine) {
6388 cx.propagate();
6389 return;
6390 }
6391
6392 let text_layout_details = &self.text_layout_details(cx);
6393
6394 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6395 let line_mode = s.line_mode;
6396 s.move_with(|map, selection| {
6397 if !selection.is_empty() && !line_mode {
6398 selection.goal = SelectionGoal::None;
6399 }
6400 let (cursor, goal) = movement::up_by_rows(
6401 map,
6402 selection.start,
6403 action.lines,
6404 selection.goal,
6405 false,
6406 &text_layout_details,
6407 );
6408 selection.collapse_to(cursor, goal);
6409 });
6410 })
6411 }
6412
6413 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
6414 if self.take_rename(true, cx).is_some() {
6415 return;
6416 }
6417
6418 if matches!(self.mode, EditorMode::SingleLine) {
6419 cx.propagate();
6420 return;
6421 }
6422
6423 let text_layout_details = &self.text_layout_details(cx);
6424
6425 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6426 let line_mode = s.line_mode;
6427 s.move_with(|map, selection| {
6428 if !selection.is_empty() && !line_mode {
6429 selection.goal = SelectionGoal::None;
6430 }
6431 let (cursor, goal) = movement::down_by_rows(
6432 map,
6433 selection.start,
6434 action.lines,
6435 selection.goal,
6436 false,
6437 &text_layout_details,
6438 );
6439 selection.collapse_to(cursor, goal);
6440 });
6441 })
6442 }
6443
6444 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
6445 let text_layout_details = &self.text_layout_details(cx);
6446 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6447 s.move_heads_with(|map, head, goal| {
6448 movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
6449 })
6450 })
6451 }
6452
6453 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
6454 let text_layout_details = &self.text_layout_details(cx);
6455 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6456 s.move_heads_with(|map, head, goal| {
6457 movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
6458 })
6459 })
6460 }
6461
6462 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
6463 if self.take_rename(true, cx).is_some() {
6464 return;
6465 }
6466
6467 if matches!(self.mode, EditorMode::SingleLine) {
6468 cx.propagate();
6469 return;
6470 }
6471
6472 let row_count = if let Some(row_count) = self.visible_line_count() {
6473 row_count as u32 - 1
6474 } else {
6475 return;
6476 };
6477
6478 let autoscroll = if action.center_cursor {
6479 Autoscroll::center()
6480 } else {
6481 Autoscroll::fit()
6482 };
6483
6484 let text_layout_details = &self.text_layout_details(cx);
6485
6486 self.change_selections(Some(autoscroll), cx, |s| {
6487 let line_mode = s.line_mode;
6488 s.move_with(|map, selection| {
6489 if !selection.is_empty() && !line_mode {
6490 selection.goal = SelectionGoal::None;
6491 }
6492 let (cursor, goal) = movement::up_by_rows(
6493 map,
6494 selection.end,
6495 row_count,
6496 selection.goal,
6497 false,
6498 &text_layout_details,
6499 );
6500 selection.collapse_to(cursor, goal);
6501 });
6502 });
6503 }
6504
6505 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
6506 let text_layout_details = &self.text_layout_details(cx);
6507 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6508 s.move_heads_with(|map, head, goal| {
6509 movement::up(map, head, goal, false, &text_layout_details)
6510 })
6511 })
6512 }
6513
6514 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
6515 self.take_rename(true, cx);
6516
6517 if self.mode == EditorMode::SingleLine {
6518 cx.propagate();
6519 return;
6520 }
6521
6522 let text_layout_details = &self.text_layout_details(cx);
6523 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6524 let line_mode = s.line_mode;
6525 s.move_with(|map, selection| {
6526 if !selection.is_empty() && !line_mode {
6527 selection.goal = SelectionGoal::None;
6528 }
6529 let (cursor, goal) = movement::down(
6530 map,
6531 selection.end,
6532 selection.goal,
6533 false,
6534 &text_layout_details,
6535 );
6536 selection.collapse_to(cursor, goal);
6537 });
6538 });
6539 }
6540
6541 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
6542 if self.take_rename(true, cx).is_some() {
6543 return;
6544 }
6545
6546 if self
6547 .context_menu
6548 .write()
6549 .as_mut()
6550 .map(|menu| menu.select_last(self.project.as_ref(), cx))
6551 .unwrap_or(false)
6552 {
6553 return;
6554 }
6555
6556 if matches!(self.mode, EditorMode::SingleLine) {
6557 cx.propagate();
6558 return;
6559 }
6560
6561 let row_count = if let Some(row_count) = self.visible_line_count() {
6562 row_count as u32 - 1
6563 } else {
6564 return;
6565 };
6566
6567 let autoscroll = if action.center_cursor {
6568 Autoscroll::center()
6569 } else {
6570 Autoscroll::fit()
6571 };
6572
6573 let text_layout_details = &self.text_layout_details(cx);
6574 self.change_selections(Some(autoscroll), cx, |s| {
6575 let line_mode = s.line_mode;
6576 s.move_with(|map, selection| {
6577 if !selection.is_empty() && !line_mode {
6578 selection.goal = SelectionGoal::None;
6579 }
6580 let (cursor, goal) = movement::down_by_rows(
6581 map,
6582 selection.end,
6583 row_count,
6584 selection.goal,
6585 false,
6586 &text_layout_details,
6587 );
6588 selection.collapse_to(cursor, goal);
6589 });
6590 });
6591 }
6592
6593 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
6594 let text_layout_details = &self.text_layout_details(cx);
6595 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6596 s.move_heads_with(|map, head, goal| {
6597 movement::down(map, head, goal, false, &text_layout_details)
6598 })
6599 });
6600 }
6601
6602 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
6603 if let Some(context_menu) = self.context_menu.write().as_mut() {
6604 context_menu.select_first(self.project.as_ref(), cx);
6605 }
6606 }
6607
6608 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
6609 if let Some(context_menu) = self.context_menu.write().as_mut() {
6610 context_menu.select_prev(self.project.as_ref(), cx);
6611 }
6612 }
6613
6614 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
6615 if let Some(context_menu) = self.context_menu.write().as_mut() {
6616 context_menu.select_next(self.project.as_ref(), cx);
6617 }
6618 }
6619
6620 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
6621 if let Some(context_menu) = self.context_menu.write().as_mut() {
6622 context_menu.select_last(self.project.as_ref(), cx);
6623 }
6624 }
6625
6626 pub fn move_to_previous_word_start(
6627 &mut self,
6628 _: &MoveToPreviousWordStart,
6629 cx: &mut ViewContext<Self>,
6630 ) {
6631 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6632 s.move_cursors_with(|map, head, _| {
6633 (
6634 movement::previous_word_start(map, head),
6635 SelectionGoal::None,
6636 )
6637 });
6638 })
6639 }
6640
6641 pub fn move_to_previous_subword_start(
6642 &mut self,
6643 _: &MoveToPreviousSubwordStart,
6644 cx: &mut ViewContext<Self>,
6645 ) {
6646 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6647 s.move_cursors_with(|map, head, _| {
6648 (
6649 movement::previous_subword_start(map, head),
6650 SelectionGoal::None,
6651 )
6652 });
6653 })
6654 }
6655
6656 pub fn select_to_previous_word_start(
6657 &mut self,
6658 _: &SelectToPreviousWordStart,
6659 cx: &mut ViewContext<Self>,
6660 ) {
6661 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6662 s.move_heads_with(|map, head, _| {
6663 (
6664 movement::previous_word_start(map, head),
6665 SelectionGoal::None,
6666 )
6667 });
6668 })
6669 }
6670
6671 pub fn select_to_previous_subword_start(
6672 &mut self,
6673 _: &SelectToPreviousSubwordStart,
6674 cx: &mut ViewContext<Self>,
6675 ) {
6676 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6677 s.move_heads_with(|map, head, _| {
6678 (
6679 movement::previous_subword_start(map, head),
6680 SelectionGoal::None,
6681 )
6682 });
6683 })
6684 }
6685
6686 pub fn delete_to_previous_word_start(
6687 &mut self,
6688 _: &DeleteToPreviousWordStart,
6689 cx: &mut ViewContext<Self>,
6690 ) {
6691 self.transact(cx, |this, cx| {
6692 this.select_autoclose_pair(cx);
6693 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6694 let line_mode = s.line_mode;
6695 s.move_with(|map, selection| {
6696 if selection.is_empty() && !line_mode {
6697 let cursor = movement::previous_word_start(map, selection.head());
6698 selection.set_head(cursor, SelectionGoal::None);
6699 }
6700 });
6701 });
6702 this.insert("", cx);
6703 });
6704 }
6705
6706 pub fn delete_to_previous_subword_start(
6707 &mut self,
6708 _: &DeleteToPreviousSubwordStart,
6709 cx: &mut ViewContext<Self>,
6710 ) {
6711 self.transact(cx, |this, cx| {
6712 this.select_autoclose_pair(cx);
6713 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6714 let line_mode = s.line_mode;
6715 s.move_with(|map, selection| {
6716 if selection.is_empty() && !line_mode {
6717 let cursor = movement::previous_subword_start(map, selection.head());
6718 selection.set_head(cursor, SelectionGoal::None);
6719 }
6720 });
6721 });
6722 this.insert("", cx);
6723 });
6724 }
6725
6726 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
6727 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6728 s.move_cursors_with(|map, head, _| {
6729 (movement::next_word_end(map, head), SelectionGoal::None)
6730 });
6731 })
6732 }
6733
6734 pub fn move_to_next_subword_end(
6735 &mut self,
6736 _: &MoveToNextSubwordEnd,
6737 cx: &mut ViewContext<Self>,
6738 ) {
6739 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6740 s.move_cursors_with(|map, head, _| {
6741 (movement::next_subword_end(map, head), SelectionGoal::None)
6742 });
6743 })
6744 }
6745
6746 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
6747 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6748 s.move_heads_with(|map, head, _| {
6749 (movement::next_word_end(map, head), SelectionGoal::None)
6750 });
6751 })
6752 }
6753
6754 pub fn select_to_next_subword_end(
6755 &mut self,
6756 _: &SelectToNextSubwordEnd,
6757 cx: &mut ViewContext<Self>,
6758 ) {
6759 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6760 s.move_heads_with(|map, head, _| {
6761 (movement::next_subword_end(map, head), SelectionGoal::None)
6762 });
6763 })
6764 }
6765
6766 pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
6767 self.transact(cx, |this, cx| {
6768 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6769 let line_mode = s.line_mode;
6770 s.move_with(|map, selection| {
6771 if selection.is_empty() && !line_mode {
6772 let cursor = movement::next_word_end(map, selection.head());
6773 selection.set_head(cursor, SelectionGoal::None);
6774 }
6775 });
6776 });
6777 this.insert("", cx);
6778 });
6779 }
6780
6781 pub fn delete_to_next_subword_end(
6782 &mut self,
6783 _: &DeleteToNextSubwordEnd,
6784 cx: &mut ViewContext<Self>,
6785 ) {
6786 self.transact(cx, |this, cx| {
6787 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6788 s.move_with(|map, selection| {
6789 if selection.is_empty() {
6790 let cursor = movement::next_subword_end(map, selection.head());
6791 selection.set_head(cursor, SelectionGoal::None);
6792 }
6793 });
6794 });
6795 this.insert("", cx);
6796 });
6797 }
6798
6799 pub fn move_to_beginning_of_line(
6800 &mut self,
6801 action: &MoveToBeginningOfLine,
6802 cx: &mut ViewContext<Self>,
6803 ) {
6804 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6805 s.move_cursors_with(|map, head, _| {
6806 (
6807 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
6808 SelectionGoal::None,
6809 )
6810 });
6811 })
6812 }
6813
6814 pub fn select_to_beginning_of_line(
6815 &mut self,
6816 action: &SelectToBeginningOfLine,
6817 cx: &mut ViewContext<Self>,
6818 ) {
6819 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6820 s.move_heads_with(|map, head, _| {
6821 (
6822 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
6823 SelectionGoal::None,
6824 )
6825 });
6826 });
6827 }
6828
6829 pub fn delete_to_beginning_of_line(
6830 &mut self,
6831 _: &DeleteToBeginningOfLine,
6832 cx: &mut ViewContext<Self>,
6833 ) {
6834 self.transact(cx, |this, cx| {
6835 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6836 s.move_with(|_, selection| {
6837 selection.reversed = true;
6838 });
6839 });
6840
6841 this.select_to_beginning_of_line(
6842 &SelectToBeginningOfLine {
6843 stop_at_soft_wraps: false,
6844 },
6845 cx,
6846 );
6847 this.backspace(&Backspace, cx);
6848 });
6849 }
6850
6851 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
6852 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6853 s.move_cursors_with(|map, head, _| {
6854 (
6855 movement::line_end(map, head, action.stop_at_soft_wraps),
6856 SelectionGoal::None,
6857 )
6858 });
6859 })
6860 }
6861
6862 pub fn select_to_end_of_line(
6863 &mut self,
6864 action: &SelectToEndOfLine,
6865 cx: &mut ViewContext<Self>,
6866 ) {
6867 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6868 s.move_heads_with(|map, head, _| {
6869 (
6870 movement::line_end(map, head, action.stop_at_soft_wraps),
6871 SelectionGoal::None,
6872 )
6873 });
6874 })
6875 }
6876
6877 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
6878 self.transact(cx, |this, cx| {
6879 this.select_to_end_of_line(
6880 &SelectToEndOfLine {
6881 stop_at_soft_wraps: false,
6882 },
6883 cx,
6884 );
6885 this.delete(&Delete, cx);
6886 });
6887 }
6888
6889 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
6890 self.transact(cx, |this, cx| {
6891 this.select_to_end_of_line(
6892 &SelectToEndOfLine {
6893 stop_at_soft_wraps: false,
6894 },
6895 cx,
6896 );
6897 this.cut(&Cut, cx);
6898 });
6899 }
6900
6901 pub fn move_to_start_of_paragraph(
6902 &mut self,
6903 _: &MoveToStartOfParagraph,
6904 cx: &mut ViewContext<Self>,
6905 ) {
6906 if matches!(self.mode, EditorMode::SingleLine) {
6907 cx.propagate();
6908 return;
6909 }
6910
6911 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6912 s.move_with(|map, selection| {
6913 selection.collapse_to(
6914 movement::start_of_paragraph(map, selection.head(), 1),
6915 SelectionGoal::None,
6916 )
6917 });
6918 })
6919 }
6920
6921 pub fn move_to_end_of_paragraph(
6922 &mut self,
6923 _: &MoveToEndOfParagraph,
6924 cx: &mut ViewContext<Self>,
6925 ) {
6926 if matches!(self.mode, EditorMode::SingleLine) {
6927 cx.propagate();
6928 return;
6929 }
6930
6931 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6932 s.move_with(|map, selection| {
6933 selection.collapse_to(
6934 movement::end_of_paragraph(map, selection.head(), 1),
6935 SelectionGoal::None,
6936 )
6937 });
6938 })
6939 }
6940
6941 pub fn select_to_start_of_paragraph(
6942 &mut self,
6943 _: &SelectToStartOfParagraph,
6944 cx: &mut ViewContext<Self>,
6945 ) {
6946 if matches!(self.mode, EditorMode::SingleLine) {
6947 cx.propagate();
6948 return;
6949 }
6950
6951 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6952 s.move_heads_with(|map, head, _| {
6953 (
6954 movement::start_of_paragraph(map, head, 1),
6955 SelectionGoal::None,
6956 )
6957 });
6958 })
6959 }
6960
6961 pub fn select_to_end_of_paragraph(
6962 &mut self,
6963 _: &SelectToEndOfParagraph,
6964 cx: &mut ViewContext<Self>,
6965 ) {
6966 if matches!(self.mode, EditorMode::SingleLine) {
6967 cx.propagate();
6968 return;
6969 }
6970
6971 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6972 s.move_heads_with(|map, head, _| {
6973 (
6974 movement::end_of_paragraph(map, head, 1),
6975 SelectionGoal::None,
6976 )
6977 });
6978 })
6979 }
6980
6981 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
6982 if matches!(self.mode, EditorMode::SingleLine) {
6983 cx.propagate();
6984 return;
6985 }
6986
6987 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6988 s.select_ranges(vec![0..0]);
6989 });
6990 }
6991
6992 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
6993 let mut selection = self.selections.last::<Point>(cx);
6994 selection.set_head(Point::zero(), SelectionGoal::None);
6995
6996 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6997 s.select(vec![selection]);
6998 });
6999 }
7000
7001 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7002 if matches!(self.mode, EditorMode::SingleLine) {
7003 cx.propagate();
7004 return;
7005 }
7006
7007 let cursor = self.buffer.read(cx).read(cx).len();
7008 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7009 s.select_ranges(vec![cursor..cursor])
7010 });
7011 }
7012
7013 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7014 self.nav_history = nav_history;
7015 }
7016
7017 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7018 self.nav_history.as_ref()
7019 }
7020
7021 fn push_to_nav_history(
7022 &mut self,
7023 cursor_anchor: Anchor,
7024 new_position: Option<Point>,
7025 cx: &mut ViewContext<Self>,
7026 ) {
7027 if let Some(nav_history) = self.nav_history.as_mut() {
7028 let buffer = self.buffer.read(cx).read(cx);
7029 let cursor_position = cursor_anchor.to_point(&buffer);
7030 let scroll_state = self.scroll_manager.anchor();
7031 let scroll_top_row = scroll_state.top_row(&buffer);
7032 drop(buffer);
7033
7034 if let Some(new_position) = new_position {
7035 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7036 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7037 return;
7038 }
7039 }
7040
7041 nav_history.push(
7042 Some(NavigationData {
7043 cursor_anchor,
7044 cursor_position,
7045 scroll_anchor: scroll_state,
7046 scroll_top_row,
7047 }),
7048 cx,
7049 );
7050 }
7051 }
7052
7053 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7054 let buffer = self.buffer.read(cx).snapshot(cx);
7055 let mut selection = self.selections.first::<usize>(cx);
7056 selection.set_head(buffer.len(), SelectionGoal::None);
7057 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7058 s.select(vec![selection]);
7059 });
7060 }
7061
7062 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7063 let end = self.buffer.read(cx).read(cx).len();
7064 self.change_selections(None, cx, |s| {
7065 s.select_ranges(vec![0..end]);
7066 });
7067 }
7068
7069 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7070 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7071 let mut selections = self.selections.all::<Point>(cx);
7072 let max_point = display_map.buffer_snapshot.max_point();
7073 for selection in &mut selections {
7074 let rows = selection.spanned_rows(true, &display_map);
7075 selection.start = Point::new(rows.start.0, 0);
7076 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7077 selection.reversed = false;
7078 }
7079 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7080 s.select(selections);
7081 });
7082 }
7083
7084 pub fn split_selection_into_lines(
7085 &mut self,
7086 _: &SplitSelectionIntoLines,
7087 cx: &mut ViewContext<Self>,
7088 ) {
7089 let mut to_unfold = Vec::new();
7090 let mut new_selection_ranges = Vec::new();
7091 {
7092 let selections = self.selections.all::<Point>(cx);
7093 let buffer = self.buffer.read(cx).read(cx);
7094 for selection in selections {
7095 for row in selection.start.row..selection.end.row {
7096 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7097 new_selection_ranges.push(cursor..cursor);
7098 }
7099 new_selection_ranges.push(selection.end..selection.end);
7100 to_unfold.push(selection.start..selection.end);
7101 }
7102 }
7103 self.unfold_ranges(to_unfold, true, true, cx);
7104 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7105 s.select_ranges(new_selection_ranges);
7106 });
7107 }
7108
7109 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7110 self.add_selection(true, cx);
7111 }
7112
7113 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7114 self.add_selection(false, cx);
7115 }
7116
7117 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7118 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7119 let mut selections = self.selections.all::<Point>(cx);
7120 let text_layout_details = self.text_layout_details(cx);
7121 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7122 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7123 let range = oldest_selection.display_range(&display_map).sorted();
7124
7125 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7126 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7127 let positions = start_x.min(end_x)..start_x.max(end_x);
7128
7129 selections.clear();
7130 let mut stack = Vec::new();
7131 for row in range.start.row().0..=range.end.row().0 {
7132 if let Some(selection) = self.selections.build_columnar_selection(
7133 &display_map,
7134 DisplayRow(row),
7135 &positions,
7136 oldest_selection.reversed,
7137 &text_layout_details,
7138 ) {
7139 stack.push(selection.id);
7140 selections.push(selection);
7141 }
7142 }
7143
7144 if above {
7145 stack.reverse();
7146 }
7147
7148 AddSelectionsState { above, stack }
7149 });
7150
7151 let last_added_selection = *state.stack.last().unwrap();
7152 let mut new_selections = Vec::new();
7153 if above == state.above {
7154 let end_row = if above {
7155 DisplayRow(0)
7156 } else {
7157 display_map.max_point().row()
7158 };
7159
7160 'outer: for selection in selections {
7161 if selection.id == last_added_selection {
7162 let range = selection.display_range(&display_map).sorted();
7163 debug_assert_eq!(range.start.row(), range.end.row());
7164 let mut row = range.start.row();
7165 let positions =
7166 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7167 px(start)..px(end)
7168 } else {
7169 let start_x =
7170 display_map.x_for_display_point(range.start, &text_layout_details);
7171 let end_x =
7172 display_map.x_for_display_point(range.end, &text_layout_details);
7173 start_x.min(end_x)..start_x.max(end_x)
7174 };
7175
7176 while row != end_row {
7177 if above {
7178 row.0 -= 1;
7179 } else {
7180 row.0 += 1;
7181 }
7182
7183 if let Some(new_selection) = self.selections.build_columnar_selection(
7184 &display_map,
7185 row,
7186 &positions,
7187 selection.reversed,
7188 &text_layout_details,
7189 ) {
7190 state.stack.push(new_selection.id);
7191 if above {
7192 new_selections.push(new_selection);
7193 new_selections.push(selection);
7194 } else {
7195 new_selections.push(selection);
7196 new_selections.push(new_selection);
7197 }
7198
7199 continue 'outer;
7200 }
7201 }
7202 }
7203
7204 new_selections.push(selection);
7205 }
7206 } else {
7207 new_selections = selections;
7208 new_selections.retain(|s| s.id != last_added_selection);
7209 state.stack.pop();
7210 }
7211
7212 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7213 s.select(new_selections);
7214 });
7215 if state.stack.len() > 1 {
7216 self.add_selections_state = Some(state);
7217 }
7218 }
7219
7220 pub fn select_next_match_internal(
7221 &mut self,
7222 display_map: &DisplaySnapshot,
7223 replace_newest: bool,
7224 autoscroll: Option<Autoscroll>,
7225 cx: &mut ViewContext<Self>,
7226 ) -> Result<()> {
7227 fn select_next_match_ranges(
7228 this: &mut Editor,
7229 range: Range<usize>,
7230 replace_newest: bool,
7231 auto_scroll: Option<Autoscroll>,
7232 cx: &mut ViewContext<Editor>,
7233 ) {
7234 this.unfold_ranges([range.clone()], false, true, cx);
7235 this.change_selections(auto_scroll, cx, |s| {
7236 if replace_newest {
7237 s.delete(s.newest_anchor().id);
7238 }
7239 s.insert_range(range.clone());
7240 });
7241 }
7242
7243 let buffer = &display_map.buffer_snapshot;
7244 let mut selections = self.selections.all::<usize>(cx);
7245 if let Some(mut select_next_state) = self.select_next_state.take() {
7246 let query = &select_next_state.query;
7247 if !select_next_state.done {
7248 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7249 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7250 let mut next_selected_range = None;
7251
7252 let bytes_after_last_selection =
7253 buffer.bytes_in_range(last_selection.end..buffer.len());
7254 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
7255 let query_matches = query
7256 .stream_find_iter(bytes_after_last_selection)
7257 .map(|result| (last_selection.end, result))
7258 .chain(
7259 query
7260 .stream_find_iter(bytes_before_first_selection)
7261 .map(|result| (0, result)),
7262 );
7263
7264 for (start_offset, query_match) in query_matches {
7265 let query_match = query_match.unwrap(); // can only fail due to I/O
7266 let offset_range =
7267 start_offset + query_match.start()..start_offset + query_match.end();
7268 let display_range = offset_range.start.to_display_point(&display_map)
7269 ..offset_range.end.to_display_point(&display_map);
7270
7271 if !select_next_state.wordwise
7272 || (!movement::is_inside_word(&display_map, display_range.start)
7273 && !movement::is_inside_word(&display_map, display_range.end))
7274 {
7275 // TODO: This is n^2, because we might check all the selections
7276 if !selections
7277 .iter()
7278 .any(|selection| selection.range().overlaps(&offset_range))
7279 {
7280 next_selected_range = Some(offset_range);
7281 break;
7282 }
7283 }
7284 }
7285
7286 if let Some(next_selected_range) = next_selected_range {
7287 select_next_match_ranges(
7288 self,
7289 next_selected_range,
7290 replace_newest,
7291 autoscroll,
7292 cx,
7293 );
7294 } else {
7295 select_next_state.done = true;
7296 }
7297 }
7298
7299 self.select_next_state = Some(select_next_state);
7300 } else {
7301 let mut only_carets = true;
7302 let mut same_text_selected = true;
7303 let mut selected_text = None;
7304
7305 let mut selections_iter = selections.iter().peekable();
7306 while let Some(selection) = selections_iter.next() {
7307 if selection.start != selection.end {
7308 only_carets = false;
7309 }
7310
7311 if same_text_selected {
7312 if selected_text.is_none() {
7313 selected_text =
7314 Some(buffer.text_for_range(selection.range()).collect::<String>());
7315 }
7316
7317 if let Some(next_selection) = selections_iter.peek() {
7318 if next_selection.range().len() == selection.range().len() {
7319 let next_selected_text = buffer
7320 .text_for_range(next_selection.range())
7321 .collect::<String>();
7322 if Some(next_selected_text) != selected_text {
7323 same_text_selected = false;
7324 selected_text = None;
7325 }
7326 } else {
7327 same_text_selected = false;
7328 selected_text = None;
7329 }
7330 }
7331 }
7332 }
7333
7334 if only_carets {
7335 for selection in &mut selections {
7336 let word_range = movement::surrounding_word(
7337 &display_map,
7338 selection.start.to_display_point(&display_map),
7339 );
7340 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
7341 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
7342 selection.goal = SelectionGoal::None;
7343 selection.reversed = false;
7344 select_next_match_ranges(
7345 self,
7346 selection.start..selection.end,
7347 replace_newest,
7348 autoscroll,
7349 cx,
7350 );
7351 }
7352
7353 if selections.len() == 1 {
7354 let selection = selections
7355 .last()
7356 .expect("ensured that there's only one selection");
7357 let query = buffer
7358 .text_for_range(selection.start..selection.end)
7359 .collect::<String>();
7360 let is_empty = query.is_empty();
7361 let select_state = SelectNextState {
7362 query: AhoCorasick::new(&[query])?,
7363 wordwise: true,
7364 done: is_empty,
7365 };
7366 self.select_next_state = Some(select_state);
7367 } else {
7368 self.select_next_state = None;
7369 }
7370 } else if let Some(selected_text) = selected_text {
7371 self.select_next_state = Some(SelectNextState {
7372 query: AhoCorasick::new(&[selected_text])?,
7373 wordwise: false,
7374 done: false,
7375 });
7376 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
7377 }
7378 }
7379 Ok(())
7380 }
7381
7382 pub fn select_all_matches(
7383 &mut self,
7384 _action: &SelectAllMatches,
7385 cx: &mut ViewContext<Self>,
7386 ) -> Result<()> {
7387 self.push_to_selection_history();
7388 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7389
7390 self.select_next_match_internal(&display_map, false, None, cx)?;
7391 let Some(select_next_state) = self.select_next_state.as_mut() else {
7392 return Ok(());
7393 };
7394 if select_next_state.done {
7395 return Ok(());
7396 }
7397
7398 let mut new_selections = self.selections.all::<usize>(cx);
7399
7400 let buffer = &display_map.buffer_snapshot;
7401 let query_matches = select_next_state
7402 .query
7403 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
7404
7405 for query_match in query_matches {
7406 let query_match = query_match.unwrap(); // can only fail due to I/O
7407 let offset_range = query_match.start()..query_match.end();
7408 let display_range = offset_range.start.to_display_point(&display_map)
7409 ..offset_range.end.to_display_point(&display_map);
7410
7411 if !select_next_state.wordwise
7412 || (!movement::is_inside_word(&display_map, display_range.start)
7413 && !movement::is_inside_word(&display_map, display_range.end))
7414 {
7415 self.selections.change_with(cx, |selections| {
7416 new_selections.push(Selection {
7417 id: selections.new_selection_id(),
7418 start: offset_range.start,
7419 end: offset_range.end,
7420 reversed: false,
7421 goal: SelectionGoal::None,
7422 });
7423 });
7424 }
7425 }
7426
7427 new_selections.sort_by_key(|selection| selection.start);
7428 let mut ix = 0;
7429 while ix + 1 < new_selections.len() {
7430 let current_selection = &new_selections[ix];
7431 let next_selection = &new_selections[ix + 1];
7432 if current_selection.range().overlaps(&next_selection.range()) {
7433 if current_selection.id < next_selection.id {
7434 new_selections.remove(ix + 1);
7435 } else {
7436 new_selections.remove(ix);
7437 }
7438 } else {
7439 ix += 1;
7440 }
7441 }
7442
7443 select_next_state.done = true;
7444 self.unfold_ranges(
7445 new_selections.iter().map(|selection| selection.range()),
7446 false,
7447 false,
7448 cx,
7449 );
7450 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
7451 selections.select(new_selections)
7452 });
7453
7454 Ok(())
7455 }
7456
7457 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
7458 self.push_to_selection_history();
7459 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7460 self.select_next_match_internal(
7461 &display_map,
7462 action.replace_newest,
7463 Some(Autoscroll::newest()),
7464 cx,
7465 )?;
7466 Ok(())
7467 }
7468
7469 pub fn select_previous(
7470 &mut self,
7471 action: &SelectPrevious,
7472 cx: &mut ViewContext<Self>,
7473 ) -> Result<()> {
7474 self.push_to_selection_history();
7475 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7476 let buffer = &display_map.buffer_snapshot;
7477 let mut selections = self.selections.all::<usize>(cx);
7478 if let Some(mut select_prev_state) = self.select_prev_state.take() {
7479 let query = &select_prev_state.query;
7480 if !select_prev_state.done {
7481 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7482 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7483 let mut next_selected_range = None;
7484 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
7485 let bytes_before_last_selection =
7486 buffer.reversed_bytes_in_range(0..last_selection.start);
7487 let bytes_after_first_selection =
7488 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
7489 let query_matches = query
7490 .stream_find_iter(bytes_before_last_selection)
7491 .map(|result| (last_selection.start, result))
7492 .chain(
7493 query
7494 .stream_find_iter(bytes_after_first_selection)
7495 .map(|result| (buffer.len(), result)),
7496 );
7497 for (end_offset, query_match) in query_matches {
7498 let query_match = query_match.unwrap(); // can only fail due to I/O
7499 let offset_range =
7500 end_offset - query_match.end()..end_offset - query_match.start();
7501 let display_range = offset_range.start.to_display_point(&display_map)
7502 ..offset_range.end.to_display_point(&display_map);
7503
7504 if !select_prev_state.wordwise
7505 || (!movement::is_inside_word(&display_map, display_range.start)
7506 && !movement::is_inside_word(&display_map, display_range.end))
7507 {
7508 next_selected_range = Some(offset_range);
7509 break;
7510 }
7511 }
7512
7513 if let Some(next_selected_range) = next_selected_range {
7514 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
7515 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
7516 if action.replace_newest {
7517 s.delete(s.newest_anchor().id);
7518 }
7519 s.insert_range(next_selected_range);
7520 });
7521 } else {
7522 select_prev_state.done = true;
7523 }
7524 }
7525
7526 self.select_prev_state = Some(select_prev_state);
7527 } else {
7528 let mut only_carets = true;
7529 let mut same_text_selected = true;
7530 let mut selected_text = None;
7531
7532 let mut selections_iter = selections.iter().peekable();
7533 while let Some(selection) = selections_iter.next() {
7534 if selection.start != selection.end {
7535 only_carets = false;
7536 }
7537
7538 if same_text_selected {
7539 if selected_text.is_none() {
7540 selected_text =
7541 Some(buffer.text_for_range(selection.range()).collect::<String>());
7542 }
7543
7544 if let Some(next_selection) = selections_iter.peek() {
7545 if next_selection.range().len() == selection.range().len() {
7546 let next_selected_text = buffer
7547 .text_for_range(next_selection.range())
7548 .collect::<String>();
7549 if Some(next_selected_text) != selected_text {
7550 same_text_selected = false;
7551 selected_text = None;
7552 }
7553 } else {
7554 same_text_selected = false;
7555 selected_text = None;
7556 }
7557 }
7558 }
7559 }
7560
7561 if only_carets {
7562 for selection in &mut selections {
7563 let word_range = movement::surrounding_word(
7564 &display_map,
7565 selection.start.to_display_point(&display_map),
7566 );
7567 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
7568 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
7569 selection.goal = SelectionGoal::None;
7570 selection.reversed = false;
7571 }
7572 if selections.len() == 1 {
7573 let selection = selections
7574 .last()
7575 .expect("ensured that there's only one selection");
7576 let query = buffer
7577 .text_for_range(selection.start..selection.end)
7578 .collect::<String>();
7579 let is_empty = query.is_empty();
7580 let select_state = SelectNextState {
7581 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
7582 wordwise: true,
7583 done: is_empty,
7584 };
7585 self.select_prev_state = Some(select_state);
7586 } else {
7587 self.select_prev_state = None;
7588 }
7589
7590 self.unfold_ranges(
7591 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
7592 false,
7593 true,
7594 cx,
7595 );
7596 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
7597 s.select(selections);
7598 });
7599 } else if let Some(selected_text) = selected_text {
7600 self.select_prev_state = Some(SelectNextState {
7601 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
7602 wordwise: false,
7603 done: false,
7604 });
7605 self.select_previous(action, cx)?;
7606 }
7607 }
7608 Ok(())
7609 }
7610
7611 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
7612 let text_layout_details = &self.text_layout_details(cx);
7613 self.transact(cx, |this, cx| {
7614 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
7615 let mut edits = Vec::new();
7616 let mut selection_edit_ranges = Vec::new();
7617 let mut last_toggled_row = None;
7618 let snapshot = this.buffer.read(cx).read(cx);
7619 let empty_str: Arc<str> = "".into();
7620 let mut suffixes_inserted = Vec::new();
7621
7622 fn comment_prefix_range(
7623 snapshot: &MultiBufferSnapshot,
7624 row: MultiBufferRow,
7625 comment_prefix: &str,
7626 comment_prefix_whitespace: &str,
7627 ) -> Range<Point> {
7628 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
7629
7630 let mut line_bytes = snapshot
7631 .bytes_in_range(start..snapshot.max_point())
7632 .flatten()
7633 .copied();
7634
7635 // If this line currently begins with the line comment prefix, then record
7636 // the range containing the prefix.
7637 if line_bytes
7638 .by_ref()
7639 .take(comment_prefix.len())
7640 .eq(comment_prefix.bytes())
7641 {
7642 // Include any whitespace that matches the comment prefix.
7643 let matching_whitespace_len = line_bytes
7644 .zip(comment_prefix_whitespace.bytes())
7645 .take_while(|(a, b)| a == b)
7646 .count() as u32;
7647 let end = Point::new(
7648 start.row,
7649 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
7650 );
7651 start..end
7652 } else {
7653 start..start
7654 }
7655 }
7656
7657 fn comment_suffix_range(
7658 snapshot: &MultiBufferSnapshot,
7659 row: MultiBufferRow,
7660 comment_suffix: &str,
7661 comment_suffix_has_leading_space: bool,
7662 ) -> Range<Point> {
7663 let end = Point::new(row.0, snapshot.line_len(row));
7664 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
7665
7666 let mut line_end_bytes = snapshot
7667 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
7668 .flatten()
7669 .copied();
7670
7671 let leading_space_len = if suffix_start_column > 0
7672 && line_end_bytes.next() == Some(b' ')
7673 && comment_suffix_has_leading_space
7674 {
7675 1
7676 } else {
7677 0
7678 };
7679
7680 // If this line currently begins with the line comment prefix, then record
7681 // the range containing the prefix.
7682 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
7683 let start = Point::new(end.row, suffix_start_column - leading_space_len);
7684 start..end
7685 } else {
7686 end..end
7687 }
7688 }
7689
7690 // TODO: Handle selections that cross excerpts
7691 for selection in &mut selections {
7692 let start_column = snapshot
7693 .indent_size_for_line(MultiBufferRow(selection.start.row))
7694 .len;
7695 let language = if let Some(language) =
7696 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
7697 {
7698 language
7699 } else {
7700 continue;
7701 };
7702
7703 selection_edit_ranges.clear();
7704
7705 // If multiple selections contain a given row, avoid processing that
7706 // row more than once.
7707 let mut start_row = MultiBufferRow(selection.start.row);
7708 if last_toggled_row == Some(start_row) {
7709 start_row = start_row.next_row();
7710 }
7711 let end_row =
7712 if selection.end.row > selection.start.row && selection.end.column == 0 {
7713 MultiBufferRow(selection.end.row - 1)
7714 } else {
7715 MultiBufferRow(selection.end.row)
7716 };
7717 last_toggled_row = Some(end_row);
7718
7719 if start_row > end_row {
7720 continue;
7721 }
7722
7723 // If the language has line comments, toggle those.
7724 let full_comment_prefixes = language.line_comment_prefixes();
7725 if !full_comment_prefixes.is_empty() {
7726 let first_prefix = full_comment_prefixes
7727 .first()
7728 .expect("prefixes is non-empty");
7729 let prefix_trimmed_lengths = full_comment_prefixes
7730 .iter()
7731 .map(|p| p.trim_end_matches(' ').len())
7732 .collect::<SmallVec<[usize; 4]>>();
7733
7734 let mut all_selection_lines_are_comments = true;
7735
7736 for row in start_row.0..=end_row.0 {
7737 let row = MultiBufferRow(row);
7738 if start_row < end_row && snapshot.is_line_blank(row) {
7739 continue;
7740 }
7741
7742 let prefix_range = full_comment_prefixes
7743 .iter()
7744 .zip(prefix_trimmed_lengths.iter().copied())
7745 .map(|(prefix, trimmed_prefix_len)| {
7746 comment_prefix_range(
7747 snapshot.deref(),
7748 row,
7749 &prefix[..trimmed_prefix_len],
7750 &prefix[trimmed_prefix_len..],
7751 )
7752 })
7753 .max_by_key(|range| range.end.column - range.start.column)
7754 .expect("prefixes is non-empty");
7755
7756 if prefix_range.is_empty() {
7757 all_selection_lines_are_comments = false;
7758 }
7759
7760 selection_edit_ranges.push(prefix_range);
7761 }
7762
7763 if all_selection_lines_are_comments {
7764 edits.extend(
7765 selection_edit_ranges
7766 .iter()
7767 .cloned()
7768 .map(|range| (range, empty_str.clone())),
7769 );
7770 } else {
7771 let min_column = selection_edit_ranges
7772 .iter()
7773 .map(|range| range.start.column)
7774 .min()
7775 .unwrap_or(0);
7776 edits.extend(selection_edit_ranges.iter().map(|range| {
7777 let position = Point::new(range.start.row, min_column);
7778 (position..position, first_prefix.clone())
7779 }));
7780 }
7781 } else if let Some((full_comment_prefix, comment_suffix)) =
7782 language.block_comment_delimiters()
7783 {
7784 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
7785 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
7786 let prefix_range = comment_prefix_range(
7787 snapshot.deref(),
7788 start_row,
7789 comment_prefix,
7790 comment_prefix_whitespace,
7791 );
7792 let suffix_range = comment_suffix_range(
7793 snapshot.deref(),
7794 end_row,
7795 comment_suffix.trim_start_matches(' '),
7796 comment_suffix.starts_with(' '),
7797 );
7798
7799 if prefix_range.is_empty() || suffix_range.is_empty() {
7800 edits.push((
7801 prefix_range.start..prefix_range.start,
7802 full_comment_prefix.clone(),
7803 ));
7804 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
7805 suffixes_inserted.push((end_row, comment_suffix.len()));
7806 } else {
7807 edits.push((prefix_range, empty_str.clone()));
7808 edits.push((suffix_range, empty_str.clone()));
7809 }
7810 } else {
7811 continue;
7812 }
7813 }
7814
7815 drop(snapshot);
7816 this.buffer.update(cx, |buffer, cx| {
7817 buffer.edit(edits, None, cx);
7818 });
7819
7820 // Adjust selections so that they end before any comment suffixes that
7821 // were inserted.
7822 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
7823 let mut selections = this.selections.all::<Point>(cx);
7824 let snapshot = this.buffer.read(cx).read(cx);
7825 for selection in &mut selections {
7826 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
7827 match row.cmp(&MultiBufferRow(selection.end.row)) {
7828 Ordering::Less => {
7829 suffixes_inserted.next();
7830 continue;
7831 }
7832 Ordering::Greater => break,
7833 Ordering::Equal => {
7834 if selection.end.column == snapshot.line_len(row) {
7835 if selection.is_empty() {
7836 selection.start.column -= suffix_len as u32;
7837 }
7838 selection.end.column -= suffix_len as u32;
7839 }
7840 break;
7841 }
7842 }
7843 }
7844 }
7845
7846 drop(snapshot);
7847 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7848
7849 let selections = this.selections.all::<Point>(cx);
7850 let selections_on_single_row = selections.windows(2).all(|selections| {
7851 selections[0].start.row == selections[1].start.row
7852 && selections[0].end.row == selections[1].end.row
7853 && selections[0].start.row == selections[0].end.row
7854 });
7855 let selections_selecting = selections
7856 .iter()
7857 .any(|selection| selection.start != selection.end);
7858 let advance_downwards = action.advance_downwards
7859 && selections_on_single_row
7860 && !selections_selecting
7861 && this.mode != EditorMode::SingleLine;
7862
7863 if advance_downwards {
7864 let snapshot = this.buffer.read(cx).snapshot(cx);
7865
7866 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7867 s.move_cursors_with(|display_snapshot, display_point, _| {
7868 let mut point = display_point.to_point(display_snapshot);
7869 point.row += 1;
7870 point = snapshot.clip_point(point, Bias::Left);
7871 let display_point = point.to_display_point(display_snapshot);
7872 let goal = SelectionGoal::HorizontalPosition(
7873 display_snapshot
7874 .x_for_display_point(display_point, &text_layout_details)
7875 .into(),
7876 );
7877 (display_point, goal)
7878 })
7879 });
7880 }
7881 });
7882 }
7883
7884 pub fn select_larger_syntax_node(
7885 &mut self,
7886 _: &SelectLargerSyntaxNode,
7887 cx: &mut ViewContext<Self>,
7888 ) {
7889 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7890 let buffer = self.buffer.read(cx).snapshot(cx);
7891 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
7892
7893 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
7894 let mut selected_larger_node = false;
7895 let new_selections = old_selections
7896 .iter()
7897 .map(|selection| {
7898 let old_range = selection.start..selection.end;
7899 let mut new_range = old_range.clone();
7900 while let Some(containing_range) =
7901 buffer.range_for_syntax_ancestor(new_range.clone())
7902 {
7903 new_range = containing_range;
7904 if !display_map.intersects_fold(new_range.start)
7905 && !display_map.intersects_fold(new_range.end)
7906 {
7907 break;
7908 }
7909 }
7910
7911 selected_larger_node |= new_range != old_range;
7912 Selection {
7913 id: selection.id,
7914 start: new_range.start,
7915 end: new_range.end,
7916 goal: SelectionGoal::None,
7917 reversed: selection.reversed,
7918 }
7919 })
7920 .collect::<Vec<_>>();
7921
7922 if selected_larger_node {
7923 stack.push(old_selections);
7924 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7925 s.select(new_selections);
7926 });
7927 }
7928 self.select_larger_syntax_node_stack = stack;
7929 }
7930
7931 pub fn select_smaller_syntax_node(
7932 &mut self,
7933 _: &SelectSmallerSyntaxNode,
7934 cx: &mut ViewContext<Self>,
7935 ) {
7936 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
7937 if let Some(selections) = stack.pop() {
7938 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7939 s.select(selections.to_vec());
7940 });
7941 }
7942 self.select_larger_syntax_node_stack = stack;
7943 }
7944
7945 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
7946 let project = self.project.clone();
7947 cx.spawn(|this, mut cx| async move {
7948 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
7949 this.display_map.update(cx, |map, cx| map.snapshot(cx))
7950 }) else {
7951 return;
7952 };
7953
7954 let Some(project) = project else {
7955 return;
7956 };
7957
7958 let hide_runnables = project
7959 .update(&mut cx, |project, cx| {
7960 // Do not display any test indicators in non-dev server remote projects.
7961 project.is_remote() && project.ssh_connection_string(cx).is_none()
7962 })
7963 .unwrap_or(true);
7964 if hide_runnables {
7965 return;
7966 }
7967 let new_rows =
7968 cx.background_executor()
7969 .spawn({
7970 let snapshot = display_snapshot.clone();
7971 async move {
7972 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
7973 }
7974 })
7975 .await;
7976 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
7977
7978 this.update(&mut cx, |this, _| {
7979 this.clear_tasks();
7980 for (key, value) in rows {
7981 this.insert_tasks(key, value);
7982 }
7983 })
7984 .ok();
7985 })
7986 }
7987 fn fetch_runnable_ranges(
7988 snapshot: &DisplaySnapshot,
7989 range: Range<Anchor>,
7990 ) -> Vec<language::RunnableRange> {
7991 snapshot.buffer_snapshot.runnable_ranges(range).collect()
7992 }
7993
7994 fn runnable_rows(
7995 project: Model<Project>,
7996 snapshot: DisplaySnapshot,
7997 runnable_ranges: Vec<RunnableRange>,
7998 mut cx: AsyncWindowContext,
7999 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8000 runnable_ranges
8001 .into_iter()
8002 .filter_map(|mut runnable| {
8003 let tasks = cx
8004 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8005 .ok()?;
8006 if tasks.is_empty() {
8007 return None;
8008 }
8009
8010 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8011
8012 let row = snapshot
8013 .buffer_snapshot
8014 .buffer_line_for_row(MultiBufferRow(point.row))?
8015 .1
8016 .start
8017 .row;
8018
8019 let context_range =
8020 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8021 Some((
8022 (runnable.buffer_id, row),
8023 RunnableTasks {
8024 templates: tasks,
8025 offset: MultiBufferOffset(runnable.run_range.start),
8026 context_range,
8027 column: point.column,
8028 extra_variables: runnable.extra_captures,
8029 },
8030 ))
8031 })
8032 .collect()
8033 }
8034
8035 fn templates_with_tags(
8036 project: &Model<Project>,
8037 runnable: &mut Runnable,
8038 cx: &WindowContext<'_>,
8039 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8040 let (inventory, worktree_id) = project.read_with(cx, |project, cx| {
8041 let worktree_id = project
8042 .buffer_for_id(runnable.buffer)
8043 .and_then(|buffer| buffer.read(cx).file())
8044 .map(|file| WorktreeId::from_usize(file.worktree_id()));
8045
8046 (project.task_inventory().clone(), worktree_id)
8047 });
8048
8049 let inventory = inventory.read(cx);
8050 let tags = mem::take(&mut runnable.tags);
8051 let mut tags: Vec<_> = tags
8052 .into_iter()
8053 .flat_map(|tag| {
8054 let tag = tag.0.clone();
8055 inventory
8056 .list_tasks(Some(runnable.language.clone()), worktree_id)
8057 .into_iter()
8058 .filter(move |(_, template)| {
8059 template.tags.iter().any(|source_tag| source_tag == &tag)
8060 })
8061 })
8062 .sorted_by_key(|(kind, _)| kind.to_owned())
8063 .collect();
8064 if let Some((leading_tag_source, _)) = tags.first() {
8065 // Strongest source wins; if we have worktree tag binding, prefer that to
8066 // global and language bindings;
8067 // if we have a global binding, prefer that to language binding.
8068 let first_mismatch = tags
8069 .iter()
8070 .position(|(tag_source, _)| tag_source != leading_tag_source);
8071 if let Some(index) = first_mismatch {
8072 tags.truncate(index);
8073 }
8074 }
8075
8076 tags
8077 }
8078
8079 pub fn move_to_enclosing_bracket(
8080 &mut self,
8081 _: &MoveToEnclosingBracket,
8082 cx: &mut ViewContext<Self>,
8083 ) {
8084 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8085 s.move_offsets_with(|snapshot, selection| {
8086 let Some(enclosing_bracket_ranges) =
8087 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
8088 else {
8089 return;
8090 };
8091
8092 let mut best_length = usize::MAX;
8093 let mut best_inside = false;
8094 let mut best_in_bracket_range = false;
8095 let mut best_destination = None;
8096 for (open, close) in enclosing_bracket_ranges {
8097 let close = close.to_inclusive();
8098 let length = close.end() - open.start;
8099 let inside = selection.start >= open.end && selection.end <= *close.start();
8100 let in_bracket_range = open.to_inclusive().contains(&selection.head())
8101 || close.contains(&selection.head());
8102
8103 // If best is next to a bracket and current isn't, skip
8104 if !in_bracket_range && best_in_bracket_range {
8105 continue;
8106 }
8107
8108 // Prefer smaller lengths unless best is inside and current isn't
8109 if length > best_length && (best_inside || !inside) {
8110 continue;
8111 }
8112
8113 best_length = length;
8114 best_inside = inside;
8115 best_in_bracket_range = in_bracket_range;
8116 best_destination = Some(
8117 if close.contains(&selection.start) && close.contains(&selection.end) {
8118 if inside {
8119 open.end
8120 } else {
8121 open.start
8122 }
8123 } else {
8124 if inside {
8125 *close.start()
8126 } else {
8127 *close.end()
8128 }
8129 },
8130 );
8131 }
8132
8133 if let Some(destination) = best_destination {
8134 selection.collapse_to(destination, SelectionGoal::None);
8135 }
8136 })
8137 });
8138 }
8139
8140 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
8141 self.end_selection(cx);
8142 self.selection_history.mode = SelectionHistoryMode::Undoing;
8143 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
8144 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8145 self.select_next_state = entry.select_next_state;
8146 self.select_prev_state = entry.select_prev_state;
8147 self.add_selections_state = entry.add_selections_state;
8148 self.request_autoscroll(Autoscroll::newest(), cx);
8149 }
8150 self.selection_history.mode = SelectionHistoryMode::Normal;
8151 }
8152
8153 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
8154 self.end_selection(cx);
8155 self.selection_history.mode = SelectionHistoryMode::Redoing;
8156 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
8157 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8158 self.select_next_state = entry.select_next_state;
8159 self.select_prev_state = entry.select_prev_state;
8160 self.add_selections_state = entry.add_selections_state;
8161 self.request_autoscroll(Autoscroll::newest(), cx);
8162 }
8163 self.selection_history.mode = SelectionHistoryMode::Normal;
8164 }
8165
8166 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
8167 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
8168 }
8169
8170 pub fn expand_excerpts_down(
8171 &mut self,
8172 action: &ExpandExcerptsDown,
8173 cx: &mut ViewContext<Self>,
8174 ) {
8175 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
8176 }
8177
8178 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
8179 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
8180 }
8181
8182 pub fn expand_excerpts_for_direction(
8183 &mut self,
8184 lines: u32,
8185 direction: ExpandExcerptDirection,
8186 cx: &mut ViewContext<Self>,
8187 ) {
8188 let selections = self.selections.disjoint_anchors();
8189
8190 let lines = if lines == 0 {
8191 EditorSettings::get_global(cx).expand_excerpt_lines
8192 } else {
8193 lines
8194 };
8195
8196 self.buffer.update(cx, |buffer, cx| {
8197 buffer.expand_excerpts(
8198 selections
8199 .into_iter()
8200 .map(|selection| selection.head().excerpt_id)
8201 .dedup(),
8202 lines,
8203 direction,
8204 cx,
8205 )
8206 })
8207 }
8208
8209 pub fn expand_excerpt(
8210 &mut self,
8211 excerpt: ExcerptId,
8212 direction: ExpandExcerptDirection,
8213 cx: &mut ViewContext<Self>,
8214 ) {
8215 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
8216 self.buffer.update(cx, |buffer, cx| {
8217 buffer.expand_excerpts([excerpt], lines, direction, cx)
8218 })
8219 }
8220
8221 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
8222 self.go_to_diagnostic_impl(Direction::Next, cx)
8223 }
8224
8225 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
8226 self.go_to_diagnostic_impl(Direction::Prev, cx)
8227 }
8228
8229 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
8230 let buffer = self.buffer.read(cx).snapshot(cx);
8231 let selection = self.selections.newest::<usize>(cx);
8232
8233 // If there is an active Diagnostic Popover jump to its diagnostic instead.
8234 if direction == Direction::Next {
8235 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
8236 let (group_id, jump_to) = popover.activation_info();
8237 if self.activate_diagnostics(group_id, cx) {
8238 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8239 let mut new_selection = s.newest_anchor().clone();
8240 new_selection.collapse_to(jump_to, SelectionGoal::None);
8241 s.select_anchors(vec![new_selection.clone()]);
8242 });
8243 }
8244 return;
8245 }
8246 }
8247
8248 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
8249 active_diagnostics
8250 .primary_range
8251 .to_offset(&buffer)
8252 .to_inclusive()
8253 });
8254 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
8255 if active_primary_range.contains(&selection.head()) {
8256 *active_primary_range.start()
8257 } else {
8258 selection.head()
8259 }
8260 } else {
8261 selection.head()
8262 };
8263 let snapshot = self.snapshot(cx);
8264 loop {
8265 let diagnostics = if direction == Direction::Prev {
8266 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
8267 } else {
8268 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
8269 }
8270 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
8271 let group = diagnostics
8272 // relies on diagnostics_in_range to return diagnostics with the same starting range to
8273 // be sorted in a stable way
8274 // skip until we are at current active diagnostic, if it exists
8275 .skip_while(|entry| {
8276 (match direction {
8277 Direction::Prev => entry.range.start >= search_start,
8278 Direction::Next => entry.range.start <= search_start,
8279 }) && self
8280 .active_diagnostics
8281 .as_ref()
8282 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
8283 })
8284 .find_map(|entry| {
8285 if entry.diagnostic.is_primary
8286 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
8287 && !entry.range.is_empty()
8288 // if we match with the active diagnostic, skip it
8289 && Some(entry.diagnostic.group_id)
8290 != self.active_diagnostics.as_ref().map(|d| d.group_id)
8291 {
8292 Some((entry.range, entry.diagnostic.group_id))
8293 } else {
8294 None
8295 }
8296 });
8297
8298 if let Some((primary_range, group_id)) = group {
8299 if self.activate_diagnostics(group_id, cx) {
8300 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8301 s.select(vec![Selection {
8302 id: selection.id,
8303 start: primary_range.start,
8304 end: primary_range.start,
8305 reversed: false,
8306 goal: SelectionGoal::None,
8307 }]);
8308 });
8309 }
8310 break;
8311 } else {
8312 // Cycle around to the start of the buffer, potentially moving back to the start of
8313 // the currently active diagnostic.
8314 active_primary_range.take();
8315 if direction == Direction::Prev {
8316 if search_start == buffer.len() {
8317 break;
8318 } else {
8319 search_start = buffer.len();
8320 }
8321 } else if search_start == 0 {
8322 break;
8323 } else {
8324 search_start = 0;
8325 }
8326 }
8327 }
8328 }
8329
8330 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
8331 let snapshot = self
8332 .display_map
8333 .update(cx, |display_map, cx| display_map.snapshot(cx));
8334 let selection = self.selections.newest::<Point>(cx);
8335
8336 if !self.seek_in_direction(
8337 &snapshot,
8338 selection.head(),
8339 false,
8340 snapshot.buffer_snapshot.git_diff_hunks_in_range(
8341 MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
8342 ),
8343 cx,
8344 ) {
8345 let wrapped_point = Point::zero();
8346 self.seek_in_direction(
8347 &snapshot,
8348 wrapped_point,
8349 true,
8350 snapshot.buffer_snapshot.git_diff_hunks_in_range(
8351 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
8352 ),
8353 cx,
8354 );
8355 }
8356 }
8357
8358 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
8359 let snapshot = self
8360 .display_map
8361 .update(cx, |display_map, cx| display_map.snapshot(cx));
8362 let selection = self.selections.newest::<Point>(cx);
8363
8364 if !self.seek_in_direction(
8365 &snapshot,
8366 selection.head(),
8367 false,
8368 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
8369 MultiBufferRow(0)..MultiBufferRow(selection.head().row),
8370 ),
8371 cx,
8372 ) {
8373 let wrapped_point = snapshot.buffer_snapshot.max_point();
8374 self.seek_in_direction(
8375 &snapshot,
8376 wrapped_point,
8377 true,
8378 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
8379 MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
8380 ),
8381 cx,
8382 );
8383 }
8384 }
8385
8386 fn seek_in_direction(
8387 &mut self,
8388 snapshot: &DisplaySnapshot,
8389 initial_point: Point,
8390 is_wrapped: bool,
8391 hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
8392 cx: &mut ViewContext<Editor>,
8393 ) -> bool {
8394 let display_point = initial_point.to_display_point(snapshot);
8395 let mut hunks = hunks
8396 .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
8397 .filter(|hunk| {
8398 if is_wrapped {
8399 true
8400 } else {
8401 !hunk.contains_display_row(display_point.row())
8402 }
8403 })
8404 .dedup();
8405
8406 if let Some(hunk) = hunks.next() {
8407 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8408 let row = hunk.start_display_row();
8409 let point = DisplayPoint::new(row, 0);
8410 s.select_display_ranges([point..point]);
8411 });
8412
8413 true
8414 } else {
8415 false
8416 }
8417 }
8418
8419 pub fn go_to_definition(
8420 &mut self,
8421 _: &GoToDefinition,
8422 cx: &mut ViewContext<Self>,
8423 ) -> Task<Result<bool>> {
8424 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx)
8425 }
8426
8427 pub fn go_to_implementation(
8428 &mut self,
8429 _: &GoToImplementation,
8430 cx: &mut ViewContext<Self>,
8431 ) -> Task<Result<bool>> {
8432 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
8433 }
8434
8435 pub fn go_to_implementation_split(
8436 &mut self,
8437 _: &GoToImplementationSplit,
8438 cx: &mut ViewContext<Self>,
8439 ) -> Task<Result<bool>> {
8440 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
8441 }
8442
8443 pub fn go_to_type_definition(
8444 &mut self,
8445 _: &GoToTypeDefinition,
8446 cx: &mut ViewContext<Self>,
8447 ) -> Task<Result<bool>> {
8448 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
8449 }
8450
8451 pub fn go_to_definition_split(
8452 &mut self,
8453 _: &GoToDefinitionSplit,
8454 cx: &mut ViewContext<Self>,
8455 ) -> Task<Result<bool>> {
8456 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
8457 }
8458
8459 pub fn go_to_type_definition_split(
8460 &mut self,
8461 _: &GoToTypeDefinitionSplit,
8462 cx: &mut ViewContext<Self>,
8463 ) -> Task<Result<bool>> {
8464 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
8465 }
8466
8467 fn go_to_definition_of_kind(
8468 &mut self,
8469 kind: GotoDefinitionKind,
8470 split: bool,
8471 cx: &mut ViewContext<Self>,
8472 ) -> Task<Result<bool>> {
8473 let Some(workspace) = self.workspace() else {
8474 return Task::ready(Ok(false));
8475 };
8476 let buffer = self.buffer.read(cx);
8477 let head = self.selections.newest::<usize>(cx).head();
8478 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
8479 text_anchor
8480 } else {
8481 return Task::ready(Ok(false));
8482 };
8483
8484 let project = workspace.read(cx).project().clone();
8485 let definitions = project.update(cx, |project, cx| match kind {
8486 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
8487 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
8488 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
8489 });
8490
8491 cx.spawn(|editor, mut cx| async move {
8492 let definitions = definitions.await?;
8493 let navigated = editor
8494 .update(&mut cx, |editor, cx| {
8495 editor.navigate_to_hover_links(
8496 Some(kind),
8497 definitions
8498 .into_iter()
8499 .filter(|location| {
8500 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
8501 })
8502 .map(HoverLink::Text)
8503 .collect::<Vec<_>>(),
8504 split,
8505 cx,
8506 )
8507 })?
8508 .await?;
8509 anyhow::Ok(navigated)
8510 })
8511 }
8512
8513 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
8514 let position = self.selections.newest_anchor().head();
8515 let Some((buffer, buffer_position)) =
8516 self.buffer.read(cx).text_anchor_for_position(position, cx)
8517 else {
8518 return;
8519 };
8520
8521 cx.spawn(|editor, mut cx| async move {
8522 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
8523 editor.update(&mut cx, |_, cx| {
8524 cx.open_url(&url);
8525 })
8526 } else {
8527 Ok(())
8528 }
8529 })
8530 .detach();
8531 }
8532
8533 pub(crate) fn navigate_to_hover_links(
8534 &mut self,
8535 kind: Option<GotoDefinitionKind>,
8536 mut definitions: Vec<HoverLink>,
8537 split: bool,
8538 cx: &mut ViewContext<Editor>,
8539 ) -> Task<Result<bool>> {
8540 // If there is one definition, just open it directly
8541 if definitions.len() == 1 {
8542 let definition = definitions.pop().unwrap();
8543 let target_task = match definition {
8544 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
8545 HoverLink::InlayHint(lsp_location, server_id) => {
8546 self.compute_target_location(lsp_location, server_id, cx)
8547 }
8548 HoverLink::Url(url) => {
8549 cx.open_url(&url);
8550 Task::ready(Ok(None))
8551 }
8552 };
8553 cx.spawn(|editor, mut cx| async move {
8554 let target = target_task.await.context("target resolution task")?;
8555 if let Some(target) = target {
8556 editor.update(&mut cx, |editor, cx| {
8557 let Some(workspace) = editor.workspace() else {
8558 return false;
8559 };
8560 let pane = workspace.read(cx).active_pane().clone();
8561
8562 let range = target.range.to_offset(target.buffer.read(cx));
8563 let range = editor.range_for_match(&range);
8564
8565 /// If select range has more than one line, we
8566 /// just point the cursor to range.start.
8567 fn check_multiline_range(
8568 buffer: &Buffer,
8569 range: Range<usize>,
8570 ) -> Range<usize> {
8571 if buffer.offset_to_point(range.start).row
8572 == buffer.offset_to_point(range.end).row
8573 {
8574 range
8575 } else {
8576 range.start..range.start
8577 }
8578 }
8579
8580 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
8581 let buffer = target.buffer.read(cx);
8582 let range = check_multiline_range(buffer, range);
8583 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
8584 s.select_ranges([range]);
8585 });
8586 } else {
8587 cx.window_context().defer(move |cx| {
8588 let target_editor: View<Self> =
8589 workspace.update(cx, |workspace, cx| {
8590 let pane = if split {
8591 workspace.adjacent_pane(cx)
8592 } else {
8593 workspace.active_pane().clone()
8594 };
8595
8596 workspace.open_project_item(pane, target.buffer.clone(), cx)
8597 });
8598 target_editor.update(cx, |target_editor, cx| {
8599 // When selecting a definition in a different buffer, disable the nav history
8600 // to avoid creating a history entry at the previous cursor location.
8601 pane.update(cx, |pane, _| pane.disable_history());
8602 let buffer = target.buffer.read(cx);
8603 let range = check_multiline_range(buffer, range);
8604 target_editor.change_selections(
8605 Some(Autoscroll::focused()),
8606 cx,
8607 |s| {
8608 s.select_ranges([range]);
8609 },
8610 );
8611 pane.update(cx, |pane, _| pane.enable_history());
8612 });
8613 });
8614 }
8615 true
8616 })
8617 } else {
8618 Ok(false)
8619 }
8620 })
8621 } else if !definitions.is_empty() {
8622 let replica_id = self.replica_id(cx);
8623 cx.spawn(|editor, mut cx| async move {
8624 let (title, location_tasks, workspace) = editor
8625 .update(&mut cx, |editor, cx| {
8626 let tab_kind = match kind {
8627 Some(GotoDefinitionKind::Implementation) => "Implementations",
8628 _ => "Definitions",
8629 };
8630 let title = definitions
8631 .iter()
8632 .find_map(|definition| match definition {
8633 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
8634 let buffer = origin.buffer.read(cx);
8635 format!(
8636 "{} for {}",
8637 tab_kind,
8638 buffer
8639 .text_for_range(origin.range.clone())
8640 .collect::<String>()
8641 )
8642 }),
8643 HoverLink::InlayHint(_, _) => None,
8644 HoverLink::Url(_) => None,
8645 })
8646 .unwrap_or(tab_kind.to_string());
8647 let location_tasks = definitions
8648 .into_iter()
8649 .map(|definition| match definition {
8650 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
8651 HoverLink::InlayHint(lsp_location, server_id) => {
8652 editor.compute_target_location(lsp_location, server_id, cx)
8653 }
8654 HoverLink::Url(_) => Task::ready(Ok(None)),
8655 })
8656 .collect::<Vec<_>>();
8657 (title, location_tasks, editor.workspace().clone())
8658 })
8659 .context("location tasks preparation")?;
8660
8661 let locations = futures::future::join_all(location_tasks)
8662 .await
8663 .into_iter()
8664 .filter_map(|location| location.transpose())
8665 .collect::<Result<_>>()
8666 .context("location tasks")?;
8667
8668 let Some(workspace) = workspace else {
8669 return Ok(false);
8670 };
8671 let opened = workspace
8672 .update(&mut cx, |workspace, cx| {
8673 Self::open_locations_in_multibuffer(
8674 workspace, locations, replica_id, title, split, cx,
8675 )
8676 })
8677 .ok();
8678
8679 anyhow::Ok(opened.is_some())
8680 })
8681 } else {
8682 Task::ready(Ok(false))
8683 }
8684 }
8685
8686 fn compute_target_location(
8687 &self,
8688 lsp_location: lsp::Location,
8689 server_id: LanguageServerId,
8690 cx: &mut ViewContext<Editor>,
8691 ) -> Task<anyhow::Result<Option<Location>>> {
8692 let Some(project) = self.project.clone() else {
8693 return Task::Ready(Some(Ok(None)));
8694 };
8695
8696 cx.spawn(move |editor, mut cx| async move {
8697 let location_task = editor.update(&mut cx, |editor, cx| {
8698 project.update(cx, |project, cx| {
8699 let language_server_name =
8700 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
8701 project
8702 .language_server_for_buffer(buffer.read(cx), server_id, cx)
8703 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
8704 });
8705 language_server_name.map(|language_server_name| {
8706 project.open_local_buffer_via_lsp(
8707 lsp_location.uri.clone(),
8708 server_id,
8709 language_server_name,
8710 cx,
8711 )
8712 })
8713 })
8714 })?;
8715 let location = match location_task {
8716 Some(task) => Some({
8717 let target_buffer_handle = task.await.context("open local buffer")?;
8718 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
8719 let target_start = target_buffer
8720 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
8721 let target_end = target_buffer
8722 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
8723 target_buffer.anchor_after(target_start)
8724 ..target_buffer.anchor_before(target_end)
8725 })?;
8726 Location {
8727 buffer: target_buffer_handle,
8728 range,
8729 }
8730 }),
8731 None => None,
8732 };
8733 Ok(location)
8734 })
8735 }
8736
8737 pub fn find_all_references(
8738 &mut self,
8739 _: &FindAllReferences,
8740 cx: &mut ViewContext<Self>,
8741 ) -> Option<Task<Result<()>>> {
8742 let multi_buffer = self.buffer.read(cx);
8743 let selection = self.selections.newest::<usize>(cx);
8744 let head = selection.head();
8745
8746 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
8747 let head_anchor = multi_buffer_snapshot.anchor_at(
8748 head,
8749 if head < selection.tail() {
8750 Bias::Right
8751 } else {
8752 Bias::Left
8753 },
8754 );
8755
8756 match self
8757 .find_all_references_task_sources
8758 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
8759 {
8760 Ok(_) => {
8761 log::info!(
8762 "Ignoring repeated FindAllReferences invocation with the position of already running task"
8763 );
8764 return None;
8765 }
8766 Err(i) => {
8767 self.find_all_references_task_sources.insert(i, head_anchor);
8768 }
8769 }
8770
8771 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
8772 let replica_id = self.replica_id(cx);
8773 let workspace = self.workspace()?;
8774 let project = workspace.read(cx).project().clone();
8775 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
8776 Some(cx.spawn(|editor, mut cx| async move {
8777 let _cleanup = defer({
8778 let mut cx = cx.clone();
8779 move || {
8780 let _ = editor.update(&mut cx, |editor, _| {
8781 if let Ok(i) =
8782 editor
8783 .find_all_references_task_sources
8784 .binary_search_by(|anchor| {
8785 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
8786 })
8787 {
8788 editor.find_all_references_task_sources.remove(i);
8789 }
8790 });
8791 }
8792 });
8793
8794 let locations = references.await?;
8795 if locations.is_empty() {
8796 return anyhow::Ok(());
8797 }
8798
8799 workspace.update(&mut cx, |workspace, cx| {
8800 let title = locations
8801 .first()
8802 .as_ref()
8803 .map(|location| {
8804 let buffer = location.buffer.read(cx);
8805 format!(
8806 "References to `{}`",
8807 buffer
8808 .text_for_range(location.range.clone())
8809 .collect::<String>()
8810 )
8811 })
8812 .unwrap();
8813 Self::open_locations_in_multibuffer(
8814 workspace, locations, replica_id, title, false, cx,
8815 );
8816 })
8817 }))
8818 }
8819
8820 /// Opens a multibuffer with the given project locations in it
8821 pub fn open_locations_in_multibuffer(
8822 workspace: &mut Workspace,
8823 mut locations: Vec<Location>,
8824 replica_id: ReplicaId,
8825 title: String,
8826 split: bool,
8827 cx: &mut ViewContext<Workspace>,
8828 ) {
8829 // If there are multiple definitions, open them in a multibuffer
8830 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
8831 let mut locations = locations.into_iter().peekable();
8832 let mut ranges_to_highlight = Vec::new();
8833 let capability = workspace.project().read(cx).capability();
8834
8835 let excerpt_buffer = cx.new_model(|cx| {
8836 let mut multibuffer = MultiBuffer::new(replica_id, capability);
8837 while let Some(location) = locations.next() {
8838 let buffer = location.buffer.read(cx);
8839 let mut ranges_for_buffer = Vec::new();
8840 let range = location.range.to_offset(buffer);
8841 ranges_for_buffer.push(range.clone());
8842
8843 while let Some(next_location) = locations.peek() {
8844 if next_location.buffer == location.buffer {
8845 ranges_for_buffer.push(next_location.range.to_offset(buffer));
8846 locations.next();
8847 } else {
8848 break;
8849 }
8850 }
8851
8852 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
8853 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
8854 location.buffer.clone(),
8855 ranges_for_buffer,
8856 DEFAULT_MULTIBUFFER_CONTEXT,
8857 cx,
8858 ))
8859 }
8860
8861 multibuffer.with_title(title)
8862 });
8863
8864 let editor = cx.new_view(|cx| {
8865 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
8866 });
8867 editor.update(cx, |editor, cx| {
8868 editor.highlight_background::<Self>(
8869 &ranges_to_highlight,
8870 |theme| theme.editor_highlighted_line_background,
8871 cx,
8872 );
8873 });
8874
8875 let item = Box::new(editor);
8876 let item_id = item.item_id();
8877
8878 if split {
8879 workspace.split_item(SplitDirection::Right, item.clone(), cx);
8880 } else {
8881 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
8882 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
8883 pane.close_current_preview_item(cx)
8884 } else {
8885 None
8886 }
8887 });
8888 workspace.add_item_to_active_pane(item.clone(), destination_index, cx);
8889 }
8890 workspace.active_pane().update(cx, |pane, cx| {
8891 pane.set_preview_item_id(Some(item_id), cx);
8892 });
8893 }
8894
8895 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
8896 use language::ToOffset as _;
8897
8898 let project = self.project.clone()?;
8899 let selection = self.selections.newest_anchor().clone();
8900 let (cursor_buffer, cursor_buffer_position) = self
8901 .buffer
8902 .read(cx)
8903 .text_anchor_for_position(selection.head(), cx)?;
8904 let (tail_buffer, cursor_buffer_position_end) = self
8905 .buffer
8906 .read(cx)
8907 .text_anchor_for_position(selection.tail(), cx)?;
8908 if tail_buffer != cursor_buffer {
8909 return None;
8910 }
8911
8912 let snapshot = cursor_buffer.read(cx).snapshot();
8913 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
8914 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
8915 let prepare_rename = project.update(cx, |project, cx| {
8916 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
8917 });
8918 drop(snapshot);
8919
8920 Some(cx.spawn(|this, mut cx| async move {
8921 let rename_range = if let Some(range) = prepare_rename.await? {
8922 Some(range)
8923 } else {
8924 this.update(&mut cx, |this, cx| {
8925 let buffer = this.buffer.read(cx).snapshot(cx);
8926 let mut buffer_highlights = this
8927 .document_highlights_for_position(selection.head(), &buffer)
8928 .filter(|highlight| {
8929 highlight.start.excerpt_id == selection.head().excerpt_id
8930 && highlight.end.excerpt_id == selection.head().excerpt_id
8931 });
8932 buffer_highlights
8933 .next()
8934 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
8935 })?
8936 };
8937 if let Some(rename_range) = rename_range {
8938 this.update(&mut cx, |this, cx| {
8939 let snapshot = cursor_buffer.read(cx).snapshot();
8940 let rename_buffer_range = rename_range.to_offset(&snapshot);
8941 let cursor_offset_in_rename_range =
8942 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
8943 let cursor_offset_in_rename_range_end =
8944 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
8945
8946 this.take_rename(false, cx);
8947 let buffer = this.buffer.read(cx).read(cx);
8948 let cursor_offset = selection.head().to_offset(&buffer);
8949 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
8950 let rename_end = rename_start + rename_buffer_range.len();
8951 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
8952 let mut old_highlight_id = None;
8953 let old_name: Arc<str> = buffer
8954 .chunks(rename_start..rename_end, true)
8955 .map(|chunk| {
8956 if old_highlight_id.is_none() {
8957 old_highlight_id = chunk.syntax_highlight_id;
8958 }
8959 chunk.text
8960 })
8961 .collect::<String>()
8962 .into();
8963
8964 drop(buffer);
8965
8966 // Position the selection in the rename editor so that it matches the current selection.
8967 this.show_local_selections = false;
8968 let rename_editor = cx.new_view(|cx| {
8969 let mut editor = Editor::single_line(cx);
8970 editor.buffer.update(cx, |buffer, cx| {
8971 buffer.edit([(0..0, old_name.clone())], None, cx)
8972 });
8973 let rename_selection_range = match cursor_offset_in_rename_range
8974 .cmp(&cursor_offset_in_rename_range_end)
8975 {
8976 Ordering::Equal => {
8977 editor.select_all(&SelectAll, cx);
8978 return editor;
8979 }
8980 Ordering::Less => {
8981 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
8982 }
8983 Ordering::Greater => {
8984 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
8985 }
8986 };
8987 if rename_selection_range.end > old_name.len() {
8988 editor.select_all(&SelectAll, cx);
8989 } else {
8990 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
8991 s.select_ranges([rename_selection_range]);
8992 });
8993 }
8994 editor
8995 });
8996
8997 let write_highlights =
8998 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
8999 let read_highlights =
9000 this.clear_background_highlights::<DocumentHighlightRead>(cx);
9001 let ranges = write_highlights
9002 .iter()
9003 .flat_map(|(_, ranges)| ranges.iter())
9004 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
9005 .cloned()
9006 .collect();
9007
9008 this.highlight_text::<Rename>(
9009 ranges,
9010 HighlightStyle {
9011 fade_out: Some(0.6),
9012 ..Default::default()
9013 },
9014 cx,
9015 );
9016 let rename_focus_handle = rename_editor.focus_handle(cx);
9017 cx.focus(&rename_focus_handle);
9018 let block_id = this.insert_blocks(
9019 [BlockProperties {
9020 style: BlockStyle::Flex,
9021 position: range.start,
9022 height: 1,
9023 render: Box::new({
9024 let rename_editor = rename_editor.clone();
9025 move |cx: &mut BlockContext| {
9026 let mut text_style = cx.editor_style.text.clone();
9027 if let Some(highlight_style) = old_highlight_id
9028 .and_then(|h| h.style(&cx.editor_style.syntax))
9029 {
9030 text_style = text_style.highlight(highlight_style);
9031 }
9032 div()
9033 .pl(cx.anchor_x)
9034 .child(EditorElement::new(
9035 &rename_editor,
9036 EditorStyle {
9037 background: cx.theme().system().transparent,
9038 local_player: cx.editor_style.local_player,
9039 text: text_style,
9040 scrollbar_width: cx.editor_style.scrollbar_width,
9041 syntax: cx.editor_style.syntax.clone(),
9042 status: cx.editor_style.status.clone(),
9043 inlay_hints_style: HighlightStyle {
9044 color: Some(cx.theme().status().hint),
9045 font_weight: Some(FontWeight::BOLD),
9046 ..HighlightStyle::default()
9047 },
9048 suggestions_style: HighlightStyle {
9049 color: Some(cx.theme().status().predictive),
9050 ..HighlightStyle::default()
9051 },
9052 },
9053 ))
9054 .into_any_element()
9055 }
9056 }),
9057 disposition: BlockDisposition::Below,
9058 }],
9059 Some(Autoscroll::fit()),
9060 cx,
9061 )[0];
9062 this.pending_rename = Some(RenameState {
9063 range,
9064 old_name,
9065 editor: rename_editor,
9066 block_id,
9067 });
9068 })?;
9069 }
9070
9071 Ok(())
9072 }))
9073 }
9074
9075 pub fn confirm_rename(
9076 &mut self,
9077 _: &ConfirmRename,
9078 cx: &mut ViewContext<Self>,
9079 ) -> Option<Task<Result<()>>> {
9080 let rename = self.take_rename(false, cx)?;
9081 let workspace = self.workspace()?;
9082 let (start_buffer, start) = self
9083 .buffer
9084 .read(cx)
9085 .text_anchor_for_position(rename.range.start, cx)?;
9086 let (end_buffer, end) = self
9087 .buffer
9088 .read(cx)
9089 .text_anchor_for_position(rename.range.end, cx)?;
9090 if start_buffer != end_buffer {
9091 return None;
9092 }
9093
9094 let buffer = start_buffer;
9095 let range = start..end;
9096 let old_name = rename.old_name;
9097 let new_name = rename.editor.read(cx).text(cx);
9098
9099 let rename = workspace
9100 .read(cx)
9101 .project()
9102 .clone()
9103 .update(cx, |project, cx| {
9104 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
9105 });
9106 let workspace = workspace.downgrade();
9107
9108 Some(cx.spawn(|editor, mut cx| async move {
9109 let project_transaction = rename.await?;
9110 Self::open_project_transaction(
9111 &editor,
9112 workspace,
9113 project_transaction,
9114 format!("Rename: {} → {}", old_name, new_name),
9115 cx.clone(),
9116 )
9117 .await?;
9118
9119 editor.update(&mut cx, |editor, cx| {
9120 editor.refresh_document_highlights(cx);
9121 })?;
9122 Ok(())
9123 }))
9124 }
9125
9126 fn take_rename(
9127 &mut self,
9128 moving_cursor: bool,
9129 cx: &mut ViewContext<Self>,
9130 ) -> Option<RenameState> {
9131 let rename = self.pending_rename.take()?;
9132 if rename.editor.focus_handle(cx).is_focused(cx) {
9133 cx.focus(&self.focus_handle);
9134 }
9135
9136 self.remove_blocks(
9137 [rename.block_id].into_iter().collect(),
9138 Some(Autoscroll::fit()),
9139 cx,
9140 );
9141 self.clear_highlights::<Rename>(cx);
9142 self.show_local_selections = true;
9143
9144 if moving_cursor {
9145 let rename_editor = rename.editor.read(cx);
9146 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
9147
9148 // Update the selection to match the position of the selection inside
9149 // the rename editor.
9150 let snapshot = self.buffer.read(cx).read(cx);
9151 let rename_range = rename.range.to_offset(&snapshot);
9152 let cursor_in_editor = snapshot
9153 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
9154 .min(rename_range.end);
9155 drop(snapshot);
9156
9157 self.change_selections(None, cx, |s| {
9158 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
9159 });
9160 } else {
9161 self.refresh_document_highlights(cx);
9162 }
9163
9164 Some(rename)
9165 }
9166
9167 pub fn pending_rename(&self) -> Option<&RenameState> {
9168 self.pending_rename.as_ref()
9169 }
9170
9171 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9172 let project = match &self.project {
9173 Some(project) => project.clone(),
9174 None => return None,
9175 };
9176
9177 Some(self.perform_format(project, FormatTrigger::Manual, cx))
9178 }
9179
9180 fn perform_format(
9181 &mut self,
9182 project: Model<Project>,
9183 trigger: FormatTrigger,
9184 cx: &mut ViewContext<Self>,
9185 ) -> Task<Result<()>> {
9186 let buffer = self.buffer().clone();
9187 let mut buffers = buffer.read(cx).all_buffers();
9188 if trigger == FormatTrigger::Save {
9189 buffers.retain(|buffer| buffer.read(cx).is_dirty());
9190 }
9191
9192 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
9193 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
9194
9195 cx.spawn(|_, mut cx| async move {
9196 let transaction = futures::select_biased! {
9197 () = timeout => {
9198 log::warn!("timed out waiting for formatting");
9199 None
9200 }
9201 transaction = format.log_err().fuse() => transaction,
9202 };
9203
9204 buffer
9205 .update(&mut cx, |buffer, cx| {
9206 if let Some(transaction) = transaction {
9207 if !buffer.is_singleton() {
9208 buffer.push_transaction(&transaction.0, cx);
9209 }
9210 }
9211
9212 cx.notify();
9213 })
9214 .ok();
9215
9216 Ok(())
9217 })
9218 }
9219
9220 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
9221 if let Some(project) = self.project.clone() {
9222 self.buffer.update(cx, |multi_buffer, cx| {
9223 project.update(cx, |project, cx| {
9224 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
9225 });
9226 })
9227 }
9228 }
9229
9230 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
9231 cx.show_character_palette();
9232 }
9233
9234 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
9235 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
9236 let buffer = self.buffer.read(cx).snapshot(cx);
9237 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
9238 let is_valid = buffer
9239 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
9240 .any(|entry| {
9241 entry.diagnostic.is_primary
9242 && !entry.range.is_empty()
9243 && entry.range.start == primary_range_start
9244 && entry.diagnostic.message == active_diagnostics.primary_message
9245 });
9246
9247 if is_valid != active_diagnostics.is_valid {
9248 active_diagnostics.is_valid = is_valid;
9249 let mut new_styles = HashMap::default();
9250 for (block_id, diagnostic) in &active_diagnostics.blocks {
9251 new_styles.insert(
9252 *block_id,
9253 diagnostic_block_renderer(diagnostic.clone(), is_valid),
9254 );
9255 }
9256 self.display_map
9257 .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
9258 }
9259 }
9260 }
9261
9262 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
9263 self.dismiss_diagnostics(cx);
9264 let snapshot = self.snapshot(cx);
9265 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
9266 let buffer = self.buffer.read(cx).snapshot(cx);
9267
9268 let mut primary_range = None;
9269 let mut primary_message = None;
9270 let mut group_end = Point::zero();
9271 let diagnostic_group = buffer
9272 .diagnostic_group::<MultiBufferPoint>(group_id)
9273 .filter_map(|entry| {
9274 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
9275 && (entry.range.start.row == entry.range.end.row
9276 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
9277 {
9278 return None;
9279 }
9280 if entry.range.end > group_end {
9281 group_end = entry.range.end;
9282 }
9283 if entry.diagnostic.is_primary {
9284 primary_range = Some(entry.range.clone());
9285 primary_message = Some(entry.diagnostic.message.clone());
9286 }
9287 Some(entry)
9288 })
9289 .collect::<Vec<_>>();
9290 let primary_range = primary_range?;
9291 let primary_message = primary_message?;
9292 let primary_range =
9293 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
9294
9295 let blocks = display_map
9296 .insert_blocks(
9297 diagnostic_group.iter().map(|entry| {
9298 let diagnostic = entry.diagnostic.clone();
9299 let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
9300 BlockProperties {
9301 style: BlockStyle::Fixed,
9302 position: buffer.anchor_after(entry.range.start),
9303 height: message_height,
9304 render: diagnostic_block_renderer(diagnostic, true),
9305 disposition: BlockDisposition::Below,
9306 }
9307 }),
9308 cx,
9309 )
9310 .into_iter()
9311 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
9312 .collect();
9313
9314 Some(ActiveDiagnosticGroup {
9315 primary_range,
9316 primary_message,
9317 group_id,
9318 blocks,
9319 is_valid: true,
9320 })
9321 });
9322 self.active_diagnostics.is_some()
9323 }
9324
9325 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
9326 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
9327 self.display_map.update(cx, |display_map, cx| {
9328 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
9329 });
9330 cx.notify();
9331 }
9332 }
9333
9334 pub fn set_selections_from_remote(
9335 &mut self,
9336 selections: Vec<Selection<Anchor>>,
9337 pending_selection: Option<Selection<Anchor>>,
9338 cx: &mut ViewContext<Self>,
9339 ) {
9340 let old_cursor_position = self.selections.newest_anchor().head();
9341 self.selections.change_with(cx, |s| {
9342 s.select_anchors(selections);
9343 if let Some(pending_selection) = pending_selection {
9344 s.set_pending(pending_selection, SelectMode::Character);
9345 } else {
9346 s.clear_pending();
9347 }
9348 });
9349 self.selections_did_change(false, &old_cursor_position, true, cx);
9350 }
9351
9352 fn push_to_selection_history(&mut self) {
9353 self.selection_history.push(SelectionHistoryEntry {
9354 selections: self.selections.disjoint_anchors(),
9355 select_next_state: self.select_next_state.clone(),
9356 select_prev_state: self.select_prev_state.clone(),
9357 add_selections_state: self.add_selections_state.clone(),
9358 });
9359 }
9360
9361 pub fn transact(
9362 &mut self,
9363 cx: &mut ViewContext<Self>,
9364 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
9365 ) -> Option<TransactionId> {
9366 self.start_transaction_at(Instant::now(), cx);
9367 update(self, cx);
9368 self.end_transaction_at(Instant::now(), cx)
9369 }
9370
9371 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
9372 self.end_selection(cx);
9373 if let Some(tx_id) = self
9374 .buffer
9375 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
9376 {
9377 self.selection_history
9378 .insert_transaction(tx_id, self.selections.disjoint_anchors());
9379 cx.emit(EditorEvent::TransactionBegun {
9380 transaction_id: tx_id,
9381 })
9382 }
9383 }
9384
9385 fn end_transaction_at(
9386 &mut self,
9387 now: Instant,
9388 cx: &mut ViewContext<Self>,
9389 ) -> Option<TransactionId> {
9390 if let Some(tx_id) = self
9391 .buffer
9392 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
9393 {
9394 if let Some((_, end_selections)) = self.selection_history.transaction_mut(tx_id) {
9395 *end_selections = Some(self.selections.disjoint_anchors());
9396 } else {
9397 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
9398 }
9399
9400 cx.emit(EditorEvent::Edited);
9401 Some(tx_id)
9402 } else {
9403 None
9404 }
9405 }
9406
9407 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
9408 let mut fold_ranges = Vec::new();
9409
9410 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9411
9412 let selections = self.selections.all_adjusted(cx);
9413 for selection in selections {
9414 let range = selection.range().sorted();
9415 let buffer_start_row = range.start.row;
9416
9417 for row in (0..=range.end.row).rev() {
9418 if let Some((foldable_range, fold_text)) =
9419 display_map.foldable_range(MultiBufferRow(row))
9420 {
9421 if foldable_range.end.row >= buffer_start_row {
9422 fold_ranges.push((foldable_range, fold_text));
9423 if row <= range.start.row {
9424 break;
9425 }
9426 }
9427 }
9428 }
9429 }
9430
9431 self.fold_ranges(fold_ranges, true, cx);
9432 }
9433
9434 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
9435 let buffer_row = fold_at.buffer_row;
9436 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9437
9438 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
9439 let autoscroll = self
9440 .selections
9441 .all::<Point>(cx)
9442 .iter()
9443 .any(|selection| fold_range.overlaps(&selection.range()));
9444
9445 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
9446 }
9447 }
9448
9449 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
9450 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9451 let buffer = &display_map.buffer_snapshot;
9452 let selections = self.selections.all::<Point>(cx);
9453 let ranges = selections
9454 .iter()
9455 .map(|s| {
9456 let range = s.display_range(&display_map).sorted();
9457 let mut start = range.start.to_point(&display_map);
9458 let mut end = range.end.to_point(&display_map);
9459 start.column = 0;
9460 end.column = buffer.line_len(MultiBufferRow(end.row));
9461 start..end
9462 })
9463 .collect::<Vec<_>>();
9464
9465 self.unfold_ranges(ranges, true, true, cx);
9466 }
9467
9468 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
9469 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9470
9471 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
9472 ..Point::new(
9473 unfold_at.buffer_row.0,
9474 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
9475 );
9476
9477 let autoscroll = self
9478 .selections
9479 .all::<Point>(cx)
9480 .iter()
9481 .any(|selection| selection.range().overlaps(&intersection_range));
9482
9483 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
9484 }
9485
9486 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
9487 let selections = self.selections.all::<Point>(cx);
9488 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9489 let line_mode = self.selections.line_mode;
9490 let ranges = selections.into_iter().map(|s| {
9491 if line_mode {
9492 let start = Point::new(s.start.row, 0);
9493 let end = Point::new(
9494 s.end.row,
9495 display_map
9496 .buffer_snapshot
9497 .line_len(MultiBufferRow(s.end.row)),
9498 );
9499 (start..end, display_map.fold_placeholder.clone())
9500 } else {
9501 (s.start..s.end, display_map.fold_placeholder.clone())
9502 }
9503 });
9504 self.fold_ranges(ranges, true, cx);
9505 }
9506
9507 pub fn fold_ranges<T: ToOffset + Clone>(
9508 &mut self,
9509 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
9510 auto_scroll: bool,
9511 cx: &mut ViewContext<Self>,
9512 ) {
9513 let mut fold_ranges = Vec::new();
9514 let mut buffers_affected = HashMap::default();
9515 let multi_buffer = self.buffer().read(cx);
9516 for (fold_range, fold_text) in ranges {
9517 if let Some((_, buffer, _)) =
9518 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
9519 {
9520 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
9521 };
9522 fold_ranges.push((fold_range, fold_text));
9523 }
9524
9525 let mut ranges = fold_ranges.into_iter().peekable();
9526 if ranges.peek().is_some() {
9527 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
9528
9529 if auto_scroll {
9530 self.request_autoscroll(Autoscroll::fit(), cx);
9531 }
9532
9533 for buffer in buffers_affected.into_values() {
9534 self.sync_expanded_diff_hunks(buffer, cx);
9535 }
9536
9537 cx.notify();
9538
9539 if let Some(active_diagnostics) = self.active_diagnostics.take() {
9540 // Clear diagnostics block when folding a range that contains it.
9541 let snapshot = self.snapshot(cx);
9542 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
9543 drop(snapshot);
9544 self.active_diagnostics = Some(active_diagnostics);
9545 self.dismiss_diagnostics(cx);
9546 } else {
9547 self.active_diagnostics = Some(active_diagnostics);
9548 }
9549 }
9550
9551 self.scrollbar_marker_state.dirty = true;
9552 }
9553 }
9554
9555 pub fn unfold_ranges<T: ToOffset + Clone>(
9556 &mut self,
9557 ranges: impl IntoIterator<Item = Range<T>>,
9558 inclusive: bool,
9559 auto_scroll: bool,
9560 cx: &mut ViewContext<Self>,
9561 ) {
9562 let mut unfold_ranges = Vec::new();
9563 let mut buffers_affected = HashMap::default();
9564 let multi_buffer = self.buffer().read(cx);
9565 for range in ranges {
9566 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
9567 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
9568 };
9569 unfold_ranges.push(range);
9570 }
9571
9572 let mut ranges = unfold_ranges.into_iter().peekable();
9573 if ranges.peek().is_some() {
9574 self.display_map
9575 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
9576 if auto_scroll {
9577 self.request_autoscroll(Autoscroll::fit(), cx);
9578 }
9579
9580 for buffer in buffers_affected.into_values() {
9581 self.sync_expanded_diff_hunks(buffer, cx);
9582 }
9583
9584 cx.notify();
9585 self.scrollbar_marker_state.dirty = true;
9586 self.active_indent_guides_state.dirty = true;
9587 }
9588 }
9589
9590 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
9591 if hovered != self.gutter_hovered {
9592 self.gutter_hovered = hovered;
9593 cx.notify();
9594 }
9595 }
9596
9597 pub fn insert_blocks(
9598 &mut self,
9599 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
9600 autoscroll: Option<Autoscroll>,
9601 cx: &mut ViewContext<Self>,
9602 ) -> Vec<BlockId> {
9603 let blocks = self
9604 .display_map
9605 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
9606 if let Some(autoscroll) = autoscroll {
9607 self.request_autoscroll(autoscroll, cx);
9608 }
9609 blocks
9610 }
9611
9612 pub fn replace_blocks(
9613 &mut self,
9614 blocks: HashMap<BlockId, RenderBlock>,
9615 autoscroll: Option<Autoscroll>,
9616 cx: &mut ViewContext<Self>,
9617 ) {
9618 self.display_map
9619 .update(cx, |display_map, _| display_map.replace_blocks(blocks));
9620 if let Some(autoscroll) = autoscroll {
9621 self.request_autoscroll(autoscroll, cx);
9622 }
9623 }
9624
9625 pub fn remove_blocks(
9626 &mut self,
9627 block_ids: HashSet<BlockId>,
9628 autoscroll: Option<Autoscroll>,
9629 cx: &mut ViewContext<Self>,
9630 ) {
9631 self.display_map.update(cx, |display_map, cx| {
9632 display_map.remove_blocks(block_ids, cx)
9633 });
9634 if let Some(autoscroll) = autoscroll {
9635 self.request_autoscroll(autoscroll, cx);
9636 }
9637 }
9638
9639 pub fn insert_flaps(
9640 &mut self,
9641 flaps: impl IntoIterator<Item = Flap>,
9642 cx: &mut ViewContext<Self>,
9643 ) -> Vec<FlapId> {
9644 self.display_map
9645 .update(cx, |map, cx| map.insert_flaps(flaps, cx))
9646 }
9647
9648 pub fn remove_flaps(
9649 &mut self,
9650 ids: impl IntoIterator<Item = FlapId>,
9651 cx: &mut ViewContext<Self>,
9652 ) {
9653 self.display_map
9654 .update(cx, |map, cx| map.remove_flaps(ids, cx));
9655 }
9656
9657 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
9658 self.display_map
9659 .update(cx, |map, cx| map.snapshot(cx))
9660 .longest_row()
9661 }
9662
9663 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
9664 self.display_map
9665 .update(cx, |map, cx| map.snapshot(cx))
9666 .max_point()
9667 }
9668
9669 pub fn text(&self, cx: &AppContext) -> String {
9670 self.buffer.read(cx).read(cx).text()
9671 }
9672
9673 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
9674 let text = self.text(cx);
9675 let text = text.trim();
9676
9677 if text.is_empty() {
9678 return None;
9679 }
9680
9681 Some(text.to_string())
9682 }
9683
9684 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
9685 self.transact(cx, |this, cx| {
9686 this.buffer
9687 .read(cx)
9688 .as_singleton()
9689 .expect("you can only call set_text on editors for singleton buffers")
9690 .update(cx, |buffer, cx| buffer.set_text(text, cx));
9691 });
9692 }
9693
9694 pub fn display_text(&self, cx: &mut AppContext) -> String {
9695 self.display_map
9696 .update(cx, |map, cx| map.snapshot(cx))
9697 .text()
9698 }
9699
9700 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
9701 let mut wrap_guides = smallvec::smallvec![];
9702
9703 if self.show_wrap_guides == Some(false) {
9704 return wrap_guides;
9705 }
9706
9707 let settings = self.buffer.read(cx).settings_at(0, cx);
9708 if settings.show_wrap_guides {
9709 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
9710 wrap_guides.push((soft_wrap as usize, true));
9711 }
9712 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
9713 }
9714
9715 wrap_guides
9716 }
9717
9718 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
9719 let settings = self.buffer.read(cx).settings_at(0, cx);
9720 let mode = self
9721 .soft_wrap_mode_override
9722 .unwrap_or_else(|| settings.soft_wrap);
9723 match mode {
9724 language_settings::SoftWrap::None => SoftWrap::None,
9725 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
9726 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
9727 language_settings::SoftWrap::PreferredLineLength => {
9728 SoftWrap::Column(settings.preferred_line_length)
9729 }
9730 }
9731 }
9732
9733 pub fn set_soft_wrap_mode(
9734 &mut self,
9735 mode: language_settings::SoftWrap,
9736 cx: &mut ViewContext<Self>,
9737 ) {
9738 self.soft_wrap_mode_override = Some(mode);
9739 cx.notify();
9740 }
9741
9742 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
9743 let rem_size = cx.rem_size();
9744 self.display_map.update(cx, |map, cx| {
9745 map.set_font(
9746 style.text.font(),
9747 style.text.font_size.to_pixels(rem_size),
9748 cx,
9749 )
9750 });
9751 self.style = Some(style);
9752 }
9753
9754 pub fn style(&self) -> Option<&EditorStyle> {
9755 self.style.as_ref()
9756 }
9757
9758 // Called by the element. This method is not designed to be called outside of the editor
9759 // element's layout code because it does not notify when rewrapping is computed synchronously.
9760 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
9761 self.display_map
9762 .update(cx, |map, cx| map.set_wrap_width(width, cx))
9763 }
9764
9765 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
9766 if self.soft_wrap_mode_override.is_some() {
9767 self.soft_wrap_mode_override.take();
9768 } else {
9769 let soft_wrap = match self.soft_wrap_mode(cx) {
9770 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
9771 SoftWrap::EditorWidth | SoftWrap::Column(_) => {
9772 language_settings::SoftWrap::PreferLine
9773 }
9774 };
9775 self.soft_wrap_mode_override = Some(soft_wrap);
9776 }
9777 cx.notify();
9778 }
9779
9780 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
9781 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
9782 self.buffer
9783 .read(cx)
9784 .settings_at(0, cx)
9785 .indent_guides
9786 .enabled
9787 });
9788 self.show_indent_guides = Some(!currently_enabled);
9789 cx.notify();
9790 }
9791
9792 fn should_show_indent_guides(&self) -> Option<bool> {
9793 self.show_indent_guides
9794 }
9795
9796 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
9797 let mut editor_settings = EditorSettings::get_global(cx).clone();
9798 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
9799 EditorSettings::override_global(editor_settings, cx);
9800 }
9801
9802 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
9803 self.show_gutter = show_gutter;
9804 cx.notify();
9805 }
9806
9807 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
9808 self.show_line_numbers = Some(show_line_numbers);
9809 cx.notify();
9810 }
9811
9812 pub fn set_show_git_diff_gutter(
9813 &mut self,
9814 show_git_diff_gutter: bool,
9815 cx: &mut ViewContext<Self>,
9816 ) {
9817 self.show_git_diff_gutter = Some(show_git_diff_gutter);
9818 cx.notify();
9819 }
9820
9821 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
9822 self.show_code_actions = Some(show_code_actions);
9823 cx.notify();
9824 }
9825
9826 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
9827 self.show_wrap_guides = Some(show_wrap_guides);
9828 cx.notify();
9829 }
9830
9831 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
9832 self.show_indent_guides = Some(show_indent_guides);
9833 cx.notify();
9834 }
9835
9836 pub fn reveal_in_finder(&mut self, _: &RevealInFinder, cx: &mut ViewContext<Self>) {
9837 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
9838 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
9839 cx.reveal_path(&file.abs_path(cx));
9840 }
9841 }
9842 }
9843
9844 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
9845 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
9846 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
9847 if let Some(path) = file.abs_path(cx).to_str() {
9848 cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
9849 }
9850 }
9851 }
9852 }
9853
9854 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
9855 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
9856 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
9857 if let Some(path) = file.path().to_str() {
9858 cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
9859 }
9860 }
9861 }
9862 }
9863
9864 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
9865 self.show_git_blame_gutter = !self.show_git_blame_gutter;
9866
9867 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
9868 self.start_git_blame(true, cx);
9869 }
9870
9871 cx.notify();
9872 }
9873
9874 pub fn toggle_git_blame_inline(
9875 &mut self,
9876 _: &ToggleGitBlameInline,
9877 cx: &mut ViewContext<Self>,
9878 ) {
9879 self.toggle_git_blame_inline_internal(true, cx);
9880 cx.notify();
9881 }
9882
9883 pub fn git_blame_inline_enabled(&self) -> bool {
9884 self.git_blame_inline_enabled
9885 }
9886
9887 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
9888 if let Some(project) = self.project.as_ref() {
9889 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
9890 return;
9891 };
9892
9893 if buffer.read(cx).file().is_none() {
9894 return;
9895 }
9896
9897 let focused = self.focus_handle(cx).contains_focused(cx);
9898
9899 let project = project.clone();
9900 let blame =
9901 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
9902 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
9903 self.blame = Some(blame);
9904 }
9905 }
9906
9907 fn toggle_git_blame_inline_internal(
9908 &mut self,
9909 user_triggered: bool,
9910 cx: &mut ViewContext<Self>,
9911 ) {
9912 if self.git_blame_inline_enabled {
9913 self.git_blame_inline_enabled = false;
9914 self.show_git_blame_inline = false;
9915 self.show_git_blame_inline_delay_task.take();
9916 } else {
9917 self.git_blame_inline_enabled = true;
9918 self.start_git_blame_inline(user_triggered, cx);
9919 }
9920
9921 cx.notify();
9922 }
9923
9924 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
9925 self.start_git_blame(user_triggered, cx);
9926
9927 if ProjectSettings::get_global(cx)
9928 .git
9929 .inline_blame_delay()
9930 .is_some()
9931 {
9932 self.start_inline_blame_timer(cx);
9933 } else {
9934 self.show_git_blame_inline = true
9935 }
9936 }
9937
9938 pub fn blame(&self) -> Option<&Model<GitBlame>> {
9939 self.blame.as_ref()
9940 }
9941
9942 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
9943 self.show_git_blame_gutter && self.has_blame_entries(cx)
9944 }
9945
9946 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
9947 self.show_git_blame_inline
9948 && self.focus_handle.is_focused(cx)
9949 && !self.newest_selection_head_on_empty_line(cx)
9950 && self.has_blame_entries(cx)
9951 }
9952
9953 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
9954 self.blame()
9955 .map_or(false, |blame| blame.read(cx).has_generated_entries())
9956 }
9957
9958 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
9959 let cursor_anchor = self.selections.newest_anchor().head();
9960
9961 let snapshot = self.buffer.read(cx).snapshot(cx);
9962 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
9963
9964 snapshot.line_len(buffer_row) == 0
9965 }
9966
9967 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
9968 let (path, selection, repo) = maybe!({
9969 let project_handle = self.project.as_ref()?.clone();
9970 let project = project_handle.read(cx);
9971
9972 let selection = self.selections.newest::<Point>(cx);
9973 let selection_range = selection.range();
9974
9975 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
9976 (buffer, selection_range.start.row..selection_range.end.row)
9977 } else {
9978 let buffer_ranges = self
9979 .buffer()
9980 .read(cx)
9981 .range_to_buffer_ranges(selection_range, cx);
9982
9983 let (buffer, range, _) = if selection.reversed {
9984 buffer_ranges.first()
9985 } else {
9986 buffer_ranges.last()
9987 }?;
9988
9989 let snapshot = buffer.read(cx).snapshot();
9990 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
9991 ..text::ToPoint::to_point(&range.end, &snapshot).row;
9992 (buffer.clone(), selection)
9993 };
9994
9995 let path = buffer
9996 .read(cx)
9997 .file()?
9998 .as_local()?
9999 .path()
10000 .to_str()?
10001 .to_string();
10002 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10003 Some((path, selection, repo))
10004 })
10005 .ok_or_else(|| anyhow!("unable to open git repository"))?;
10006
10007 const REMOTE_NAME: &str = "origin";
10008 let origin_url = repo
10009 .remote_url(REMOTE_NAME)
10010 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10011 let sha = repo
10012 .head_sha()
10013 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10014
10015 let (provider, remote) =
10016 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10017 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10018
10019 Ok(provider.build_permalink(
10020 remote,
10021 BuildPermalinkParams {
10022 sha: &sha,
10023 path: &path,
10024 selection: Some(selection),
10025 },
10026 ))
10027 }
10028
10029 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10030 let permalink = self.get_permalink_to_line(cx);
10031
10032 match permalink {
10033 Ok(permalink) => {
10034 cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
10035 }
10036 Err(err) => {
10037 let message = format!("Failed to copy permalink: {err}");
10038
10039 Err::<(), anyhow::Error>(err).log_err();
10040
10041 if let Some(workspace) = self.workspace() {
10042 workspace.update(cx, |workspace, cx| {
10043 struct CopyPermalinkToLine;
10044
10045 workspace.show_toast(
10046 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10047 cx,
10048 )
10049 })
10050 }
10051 }
10052 }
10053 }
10054
10055 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10056 let permalink = self.get_permalink_to_line(cx);
10057
10058 match permalink {
10059 Ok(permalink) => {
10060 cx.open_url(permalink.as_ref());
10061 }
10062 Err(err) => {
10063 let message = format!("Failed to open permalink: {err}");
10064
10065 Err::<(), anyhow::Error>(err).log_err();
10066
10067 if let Some(workspace) = self.workspace() {
10068 workspace.update(cx, |workspace, cx| {
10069 struct OpenPermalinkToLine;
10070
10071 workspace.show_toast(
10072 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
10073 cx,
10074 )
10075 })
10076 }
10077 }
10078 }
10079 }
10080
10081 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
10082 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
10083 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
10084 pub fn highlight_rows<T: 'static>(
10085 &mut self,
10086 rows: RangeInclusive<Anchor>,
10087 color: Option<Hsla>,
10088 should_autoscroll: bool,
10089 cx: &mut ViewContext<Self>,
10090 ) {
10091 let snapshot = self.buffer().read(cx).snapshot(cx);
10092 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
10093 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
10094 highlight
10095 .range
10096 .start()
10097 .cmp(&rows.start(), &snapshot)
10098 .then(highlight.range.end().cmp(&rows.end(), &snapshot))
10099 });
10100 match (color, existing_highlight_index) {
10101 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
10102 ix,
10103 RowHighlight {
10104 index: post_inc(&mut self.highlight_order),
10105 range: rows,
10106 should_autoscroll,
10107 color,
10108 },
10109 ),
10110 (None, Ok(i)) => {
10111 row_highlights.remove(i);
10112 }
10113 }
10114 }
10115
10116 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
10117 pub fn clear_row_highlights<T: 'static>(&mut self) {
10118 self.highlighted_rows.remove(&TypeId::of::<T>());
10119 }
10120
10121 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
10122 pub fn highlighted_rows<T: 'static>(
10123 &self,
10124 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
10125 Some(
10126 self.highlighted_rows
10127 .get(&TypeId::of::<T>())?
10128 .iter()
10129 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
10130 )
10131 }
10132
10133 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
10134 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
10135 /// Allows to ignore certain kinds of highlights.
10136 pub fn highlighted_display_rows(
10137 &mut self,
10138 cx: &mut WindowContext,
10139 ) -> BTreeMap<DisplayRow, Hsla> {
10140 let snapshot = self.snapshot(cx);
10141 let mut used_highlight_orders = HashMap::default();
10142 self.highlighted_rows
10143 .iter()
10144 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
10145 .fold(
10146 BTreeMap::<DisplayRow, Hsla>::new(),
10147 |mut unique_rows, highlight| {
10148 let start_row = highlight.range.start().to_display_point(&snapshot).row();
10149 let end_row = highlight.range.end().to_display_point(&snapshot).row();
10150 for row in start_row.0..=end_row.0 {
10151 let used_index =
10152 used_highlight_orders.entry(row).or_insert(highlight.index);
10153 if highlight.index >= *used_index {
10154 *used_index = highlight.index;
10155 match highlight.color {
10156 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
10157 None => unique_rows.remove(&DisplayRow(row)),
10158 };
10159 }
10160 }
10161 unique_rows
10162 },
10163 )
10164 }
10165
10166 pub fn highlighted_display_row_for_autoscroll(
10167 &self,
10168 snapshot: &DisplaySnapshot,
10169 ) -> Option<DisplayRow> {
10170 self.highlighted_rows
10171 .values()
10172 .flat_map(|highlighted_rows| highlighted_rows.iter())
10173 .filter_map(|highlight| {
10174 if highlight.color.is_none() || !highlight.should_autoscroll {
10175 return None;
10176 }
10177 Some(highlight.range.start().to_display_point(&snapshot).row())
10178 })
10179 .min()
10180 }
10181
10182 pub fn set_search_within_ranges(
10183 &mut self,
10184 ranges: &[Range<Anchor>],
10185 cx: &mut ViewContext<Self>,
10186 ) {
10187 self.highlight_background::<SearchWithinRange>(
10188 ranges,
10189 |colors| colors.editor_document_highlight_read_background,
10190 cx,
10191 )
10192 }
10193
10194 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
10195 self.clear_background_highlights::<SearchWithinRange>(cx);
10196 }
10197
10198 pub fn highlight_background<T: 'static>(
10199 &mut self,
10200 ranges: &[Range<Anchor>],
10201 color_fetcher: fn(&ThemeColors) -> Hsla,
10202 cx: &mut ViewContext<Self>,
10203 ) {
10204 let snapshot = self.snapshot(cx);
10205 // this is to try and catch a panic sooner
10206 for range in ranges {
10207 snapshot
10208 .buffer_snapshot
10209 .summary_for_anchor::<usize>(&range.start);
10210 snapshot
10211 .buffer_snapshot
10212 .summary_for_anchor::<usize>(&range.end);
10213 }
10214
10215 self.background_highlights
10216 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10217 self.scrollbar_marker_state.dirty = true;
10218 cx.notify();
10219 }
10220
10221 pub fn clear_background_highlights<T: 'static>(
10222 &mut self,
10223 cx: &mut ViewContext<Self>,
10224 ) -> Option<BackgroundHighlight> {
10225 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
10226 if !text_highlights.1.is_empty() {
10227 self.scrollbar_marker_state.dirty = true;
10228 cx.notify();
10229 }
10230 Some(text_highlights)
10231 }
10232
10233 #[cfg(feature = "test-support")]
10234 pub fn all_text_background_highlights(
10235 &mut self,
10236 cx: &mut ViewContext<Self>,
10237 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10238 let snapshot = self.snapshot(cx);
10239 let buffer = &snapshot.buffer_snapshot;
10240 let start = buffer.anchor_before(0);
10241 let end = buffer.anchor_after(buffer.len());
10242 let theme = cx.theme().colors();
10243 self.background_highlights_in_range(start..end, &snapshot, theme)
10244 }
10245
10246 fn document_highlights_for_position<'a>(
10247 &'a self,
10248 position: Anchor,
10249 buffer: &'a MultiBufferSnapshot,
10250 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
10251 let read_highlights = self
10252 .background_highlights
10253 .get(&TypeId::of::<DocumentHighlightRead>())
10254 .map(|h| &h.1);
10255 let write_highlights = self
10256 .background_highlights
10257 .get(&TypeId::of::<DocumentHighlightWrite>())
10258 .map(|h| &h.1);
10259 let left_position = position.bias_left(buffer);
10260 let right_position = position.bias_right(buffer);
10261 read_highlights
10262 .into_iter()
10263 .chain(write_highlights)
10264 .flat_map(move |ranges| {
10265 let start_ix = match ranges.binary_search_by(|probe| {
10266 let cmp = probe.end.cmp(&left_position, buffer);
10267 if cmp.is_ge() {
10268 Ordering::Greater
10269 } else {
10270 Ordering::Less
10271 }
10272 }) {
10273 Ok(i) | Err(i) => i,
10274 };
10275
10276 ranges[start_ix..]
10277 .iter()
10278 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
10279 })
10280 }
10281
10282 pub fn has_background_highlights<T: 'static>(&self) -> bool {
10283 self.background_highlights
10284 .get(&TypeId::of::<T>())
10285 .map_or(false, |(_, highlights)| !highlights.is_empty())
10286 }
10287
10288 pub fn background_highlights_in_range(
10289 &self,
10290 search_range: Range<Anchor>,
10291 display_snapshot: &DisplaySnapshot,
10292 theme: &ThemeColors,
10293 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10294 let mut results = Vec::new();
10295 for (color_fetcher, ranges) in self.background_highlights.values() {
10296 let color = color_fetcher(theme);
10297 let start_ix = match ranges.binary_search_by(|probe| {
10298 let cmp = probe
10299 .end
10300 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10301 if cmp.is_gt() {
10302 Ordering::Greater
10303 } else {
10304 Ordering::Less
10305 }
10306 }) {
10307 Ok(i) | Err(i) => i,
10308 };
10309 for range in &ranges[start_ix..] {
10310 if range
10311 .start
10312 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10313 .is_ge()
10314 {
10315 break;
10316 }
10317
10318 let start = range.start.to_display_point(&display_snapshot);
10319 let end = range.end.to_display_point(&display_snapshot);
10320 results.push((start..end, color))
10321 }
10322 }
10323 results
10324 }
10325
10326 pub fn background_highlight_row_ranges<T: 'static>(
10327 &self,
10328 search_range: Range<Anchor>,
10329 display_snapshot: &DisplaySnapshot,
10330 count: usize,
10331 ) -> Vec<RangeInclusive<DisplayPoint>> {
10332 let mut results = Vec::new();
10333 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
10334 return vec![];
10335 };
10336
10337 let start_ix = match ranges.binary_search_by(|probe| {
10338 let cmp = probe
10339 .end
10340 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10341 if cmp.is_gt() {
10342 Ordering::Greater
10343 } else {
10344 Ordering::Less
10345 }
10346 }) {
10347 Ok(i) | Err(i) => i,
10348 };
10349 let mut push_region = |start: Option<Point>, end: Option<Point>| {
10350 if let (Some(start_display), Some(end_display)) = (start, end) {
10351 results.push(
10352 start_display.to_display_point(display_snapshot)
10353 ..=end_display.to_display_point(display_snapshot),
10354 );
10355 }
10356 };
10357 let mut start_row: Option<Point> = None;
10358 let mut end_row: Option<Point> = None;
10359 if ranges.len() > count {
10360 return Vec::new();
10361 }
10362 for range in &ranges[start_ix..] {
10363 if range
10364 .start
10365 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10366 .is_ge()
10367 {
10368 break;
10369 }
10370 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
10371 if let Some(current_row) = &end_row {
10372 if end.row == current_row.row {
10373 continue;
10374 }
10375 }
10376 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
10377 if start_row.is_none() {
10378 assert_eq!(end_row, None);
10379 start_row = Some(start);
10380 end_row = Some(end);
10381 continue;
10382 }
10383 if let Some(current_end) = end_row.as_mut() {
10384 if start.row > current_end.row + 1 {
10385 push_region(start_row, end_row);
10386 start_row = Some(start);
10387 end_row = Some(end);
10388 } else {
10389 // Merge two hunks.
10390 *current_end = end;
10391 }
10392 } else {
10393 unreachable!();
10394 }
10395 }
10396 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
10397 push_region(start_row, end_row);
10398 results
10399 }
10400
10401 /// Get the text ranges corresponding to the redaction query
10402 pub fn redacted_ranges(
10403 &self,
10404 search_range: Range<Anchor>,
10405 display_snapshot: &DisplaySnapshot,
10406 cx: &WindowContext,
10407 ) -> Vec<Range<DisplayPoint>> {
10408 display_snapshot
10409 .buffer_snapshot
10410 .redacted_ranges(search_range, |file| {
10411 if let Some(file) = file {
10412 file.is_private()
10413 && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
10414 } else {
10415 false
10416 }
10417 })
10418 .map(|range| {
10419 range.start.to_display_point(display_snapshot)
10420 ..range.end.to_display_point(display_snapshot)
10421 })
10422 .collect()
10423 }
10424
10425 pub fn highlight_text<T: 'static>(
10426 &mut self,
10427 ranges: Vec<Range<Anchor>>,
10428 style: HighlightStyle,
10429 cx: &mut ViewContext<Self>,
10430 ) {
10431 self.display_map.update(cx, |map, _| {
10432 map.highlight_text(TypeId::of::<T>(), ranges, style)
10433 });
10434 cx.notify();
10435 }
10436
10437 pub(crate) fn highlight_inlays<T: 'static>(
10438 &mut self,
10439 highlights: Vec<InlayHighlight>,
10440 style: HighlightStyle,
10441 cx: &mut ViewContext<Self>,
10442 ) {
10443 self.display_map.update(cx, |map, _| {
10444 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
10445 });
10446 cx.notify();
10447 }
10448
10449 pub fn text_highlights<'a, T: 'static>(
10450 &'a self,
10451 cx: &'a AppContext,
10452 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
10453 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
10454 }
10455
10456 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
10457 let cleared = self
10458 .display_map
10459 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
10460 if cleared {
10461 cx.notify();
10462 }
10463 }
10464
10465 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
10466 (self.read_only(cx) || self.blink_manager.read(cx).visible())
10467 && self.focus_handle.is_focused(cx)
10468 }
10469
10470 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
10471 cx.notify();
10472 }
10473
10474 fn on_buffer_event(
10475 &mut self,
10476 multibuffer: Model<MultiBuffer>,
10477 event: &multi_buffer::Event,
10478 cx: &mut ViewContext<Self>,
10479 ) {
10480 match event {
10481 multi_buffer::Event::Edited {
10482 singleton_buffer_edited,
10483 } => {
10484 self.scrollbar_marker_state.dirty = true;
10485 self.active_indent_guides_state.dirty = true;
10486 self.refresh_active_diagnostics(cx);
10487 self.refresh_code_actions(cx);
10488 if self.has_active_inline_completion(cx) {
10489 self.update_visible_inline_completion(cx);
10490 }
10491 cx.emit(EditorEvent::BufferEdited);
10492 cx.emit(SearchEvent::MatchesInvalidated);
10493
10494 if *singleton_buffer_edited {
10495 if let Some(project) = &self.project {
10496 let project = project.read(cx);
10497 let languages_affected = multibuffer
10498 .read(cx)
10499 .all_buffers()
10500 .into_iter()
10501 .filter_map(|buffer| {
10502 let buffer = buffer.read(cx);
10503 let language = buffer.language()?;
10504 if project.is_local()
10505 && project.language_servers_for_buffer(buffer, cx).count() == 0
10506 {
10507 None
10508 } else {
10509 Some(language)
10510 }
10511 })
10512 .cloned()
10513 .collect::<HashSet<_>>();
10514 if !languages_affected.is_empty() {
10515 self.refresh_inlay_hints(
10516 InlayHintRefreshReason::BufferEdited(languages_affected),
10517 cx,
10518 );
10519 }
10520 }
10521 }
10522
10523 let Some(project) = &self.project else { return };
10524 let telemetry = project.read(cx).client().telemetry().clone();
10525 telemetry.log_edit_event("editor");
10526 }
10527 multi_buffer::Event::ExcerptsAdded {
10528 buffer,
10529 predecessor,
10530 excerpts,
10531 } => {
10532 self.tasks_update_task = Some(self.refresh_runnables(cx));
10533 cx.emit(EditorEvent::ExcerptsAdded {
10534 buffer: buffer.clone(),
10535 predecessor: *predecessor,
10536 excerpts: excerpts.clone(),
10537 });
10538 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
10539 }
10540 multi_buffer::Event::ExcerptsRemoved { ids } => {
10541 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
10542 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
10543 }
10544 multi_buffer::Event::Reparsed => {
10545 self.tasks_update_task = Some(self.refresh_runnables(cx));
10546
10547 cx.emit(EditorEvent::Reparsed);
10548 }
10549 multi_buffer::Event::LanguageChanged => {
10550 cx.emit(EditorEvent::Reparsed);
10551 cx.notify();
10552 }
10553 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
10554 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
10555 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
10556 cx.emit(EditorEvent::TitleChanged)
10557 }
10558 multi_buffer::Event::DiffBaseChanged => {
10559 self.scrollbar_marker_state.dirty = true;
10560 cx.emit(EditorEvent::DiffBaseChanged);
10561 cx.notify();
10562 }
10563 multi_buffer::Event::DiffUpdated { buffer } => {
10564 self.sync_expanded_diff_hunks(buffer.clone(), cx);
10565 cx.notify();
10566 }
10567 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
10568 multi_buffer::Event::DiagnosticsUpdated => {
10569 self.refresh_active_diagnostics(cx);
10570 self.scrollbar_marker_state.dirty = true;
10571 cx.notify();
10572 }
10573 _ => {}
10574 };
10575 }
10576
10577 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
10578 cx.notify();
10579 }
10580
10581 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
10582 self.refresh_inline_completion(true, cx);
10583 self.refresh_inlay_hints(
10584 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
10585 self.selections.newest_anchor().head(),
10586 &self.buffer.read(cx).snapshot(cx),
10587 cx,
10588 )),
10589 cx,
10590 );
10591 let editor_settings = EditorSettings::get_global(cx);
10592 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
10593 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
10594 self.current_line_highlight = editor_settings.current_line_highlight;
10595
10596 if self.mode == EditorMode::Full {
10597 let inline_blame_enabled = ProjectSettings::get_global(cx).git.inline_blame_enabled();
10598 if self.git_blame_inline_enabled != inline_blame_enabled {
10599 self.toggle_git_blame_inline_internal(false, cx);
10600 }
10601 }
10602
10603 cx.notify();
10604 }
10605
10606 pub fn set_searchable(&mut self, searchable: bool) {
10607 self.searchable = searchable;
10608 }
10609
10610 pub fn searchable(&self) -> bool {
10611 self.searchable
10612 }
10613
10614 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
10615 self.open_excerpts_common(true, cx)
10616 }
10617
10618 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
10619 self.open_excerpts_common(false, cx)
10620 }
10621
10622 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
10623 let buffer = self.buffer.read(cx);
10624 if buffer.is_singleton() {
10625 cx.propagate();
10626 return;
10627 }
10628
10629 let Some(workspace) = self.workspace() else {
10630 cx.propagate();
10631 return;
10632 };
10633
10634 let mut new_selections_by_buffer = HashMap::default();
10635 for selection in self.selections.all::<usize>(cx) {
10636 for (buffer, mut range, _) in
10637 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
10638 {
10639 if selection.reversed {
10640 mem::swap(&mut range.start, &mut range.end);
10641 }
10642 new_selections_by_buffer
10643 .entry(buffer)
10644 .or_insert(Vec::new())
10645 .push(range)
10646 }
10647 }
10648
10649 // We defer the pane interaction because we ourselves are a workspace item
10650 // and activating a new item causes the pane to call a method on us reentrantly,
10651 // which panics if we're on the stack.
10652 cx.window_context().defer(move |cx| {
10653 workspace.update(cx, |workspace, cx| {
10654 let pane = if split {
10655 workspace.adjacent_pane(cx)
10656 } else {
10657 workspace.active_pane().clone()
10658 };
10659
10660 for (buffer, ranges) in new_selections_by_buffer {
10661 let editor = workspace.open_project_item::<Self>(pane.clone(), buffer, cx);
10662 editor.update(cx, |editor, cx| {
10663 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
10664 s.select_ranges(ranges);
10665 });
10666 });
10667 }
10668 })
10669 });
10670 }
10671
10672 fn jump(
10673 &mut self,
10674 path: ProjectPath,
10675 position: Point,
10676 anchor: language::Anchor,
10677 offset_from_top: u32,
10678 cx: &mut ViewContext<Self>,
10679 ) {
10680 let workspace = self.workspace();
10681 cx.spawn(|_, mut cx| async move {
10682 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
10683 let editor = workspace.update(&mut cx, |workspace, cx| {
10684 // Reset the preview item id before opening the new item
10685 workspace.active_pane().update(cx, |pane, cx| {
10686 pane.set_preview_item_id(None, cx);
10687 });
10688 workspace.open_path_preview(path, None, true, true, cx)
10689 })?;
10690 let editor = editor
10691 .await?
10692 .downcast::<Editor>()
10693 .ok_or_else(|| anyhow!("opened item was not an editor"))?
10694 .downgrade();
10695 editor.update(&mut cx, |editor, cx| {
10696 let buffer = editor
10697 .buffer()
10698 .read(cx)
10699 .as_singleton()
10700 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
10701 let buffer = buffer.read(cx);
10702 let cursor = if buffer.can_resolve(&anchor) {
10703 language::ToPoint::to_point(&anchor, buffer)
10704 } else {
10705 buffer.clip_point(position, Bias::Left)
10706 };
10707
10708 let nav_history = editor.nav_history.take();
10709 editor.change_selections(
10710 Some(Autoscroll::top_relative(offset_from_top as usize)),
10711 cx,
10712 |s| {
10713 s.select_ranges([cursor..cursor]);
10714 },
10715 );
10716 editor.nav_history = nav_history;
10717
10718 anyhow::Ok(())
10719 })??;
10720
10721 anyhow::Ok(())
10722 })
10723 .detach_and_log_err(cx);
10724 }
10725
10726 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
10727 let snapshot = self.buffer.read(cx).read(cx);
10728 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
10729 Some(
10730 ranges
10731 .iter()
10732 .map(move |range| {
10733 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
10734 })
10735 .collect(),
10736 )
10737 }
10738
10739 fn selection_replacement_ranges(
10740 &self,
10741 range: Range<OffsetUtf16>,
10742 cx: &AppContext,
10743 ) -> Vec<Range<OffsetUtf16>> {
10744 let selections = self.selections.all::<OffsetUtf16>(cx);
10745 let newest_selection = selections
10746 .iter()
10747 .max_by_key(|selection| selection.id)
10748 .unwrap();
10749 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
10750 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
10751 let snapshot = self.buffer.read(cx).read(cx);
10752 selections
10753 .into_iter()
10754 .map(|mut selection| {
10755 selection.start.0 =
10756 (selection.start.0 as isize).saturating_add(start_delta) as usize;
10757 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
10758 snapshot.clip_offset_utf16(selection.start, Bias::Left)
10759 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
10760 })
10761 .collect()
10762 }
10763
10764 fn report_editor_event(
10765 &self,
10766 operation: &'static str,
10767 file_extension: Option<String>,
10768 cx: &AppContext,
10769 ) {
10770 if cfg!(any(test, feature = "test-support")) {
10771 return;
10772 }
10773
10774 let Some(project) = &self.project else { return };
10775
10776 // If None, we are in a file without an extension
10777 let file = self
10778 .buffer
10779 .read(cx)
10780 .as_singleton()
10781 .and_then(|b| b.read(cx).file());
10782 let file_extension = file_extension.or(file
10783 .as_ref()
10784 .and_then(|file| Path::new(file.file_name(cx)).extension())
10785 .and_then(|e| e.to_str())
10786 .map(|a| a.to_string()));
10787
10788 let vim_mode = cx
10789 .global::<SettingsStore>()
10790 .raw_user_settings()
10791 .get("vim_mode")
10792 == Some(&serde_json::Value::Bool(true));
10793
10794 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
10795 == language::language_settings::InlineCompletionProvider::Copilot;
10796 let copilot_enabled_for_language = self
10797 .buffer
10798 .read(cx)
10799 .settings_at(0, cx)
10800 .show_inline_completions;
10801
10802 let telemetry = project.read(cx).client().telemetry().clone();
10803 telemetry.report_editor_event(
10804 file_extension,
10805 vim_mode,
10806 operation,
10807 copilot_enabled,
10808 copilot_enabled_for_language,
10809 )
10810 }
10811
10812 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
10813 /// with each line being an array of {text, highlight} objects.
10814 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
10815 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
10816 return;
10817 };
10818
10819 #[derive(Serialize)]
10820 struct Chunk<'a> {
10821 text: String,
10822 highlight: Option<&'a str>,
10823 }
10824
10825 let snapshot = buffer.read(cx).snapshot();
10826 let range = self
10827 .selected_text_range(cx)
10828 .and_then(|selected_range| {
10829 if selected_range.is_empty() {
10830 None
10831 } else {
10832 Some(selected_range)
10833 }
10834 })
10835 .unwrap_or_else(|| 0..snapshot.len());
10836
10837 let chunks = snapshot.chunks(range, true);
10838 let mut lines = Vec::new();
10839 let mut line: VecDeque<Chunk> = VecDeque::new();
10840
10841 let Some(style) = self.style.as_ref() else {
10842 return;
10843 };
10844
10845 for chunk in chunks {
10846 let highlight = chunk
10847 .syntax_highlight_id
10848 .and_then(|id| id.name(&style.syntax));
10849 let mut chunk_lines = chunk.text.split('\n').peekable();
10850 while let Some(text) = chunk_lines.next() {
10851 let mut merged_with_last_token = false;
10852 if let Some(last_token) = line.back_mut() {
10853 if last_token.highlight == highlight {
10854 last_token.text.push_str(text);
10855 merged_with_last_token = true;
10856 }
10857 }
10858
10859 if !merged_with_last_token {
10860 line.push_back(Chunk {
10861 text: text.into(),
10862 highlight,
10863 });
10864 }
10865
10866 if chunk_lines.peek().is_some() {
10867 if line.len() > 1 && line.front().unwrap().text.is_empty() {
10868 line.pop_front();
10869 }
10870 if line.len() > 1 && line.back().unwrap().text.is_empty() {
10871 line.pop_back();
10872 }
10873
10874 lines.push(mem::take(&mut line));
10875 }
10876 }
10877 }
10878
10879 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
10880 return;
10881 };
10882 cx.write_to_clipboard(ClipboardItem::new(lines));
10883 }
10884
10885 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
10886 &self.inlay_hint_cache
10887 }
10888
10889 pub fn replay_insert_event(
10890 &mut self,
10891 text: &str,
10892 relative_utf16_range: Option<Range<isize>>,
10893 cx: &mut ViewContext<Self>,
10894 ) {
10895 if !self.input_enabled {
10896 cx.emit(EditorEvent::InputIgnored { text: text.into() });
10897 return;
10898 }
10899 if let Some(relative_utf16_range) = relative_utf16_range {
10900 let selections = self.selections.all::<OffsetUtf16>(cx);
10901 self.change_selections(None, cx, |s| {
10902 let new_ranges = selections.into_iter().map(|range| {
10903 let start = OffsetUtf16(
10904 range
10905 .head()
10906 .0
10907 .saturating_add_signed(relative_utf16_range.start),
10908 );
10909 let end = OffsetUtf16(
10910 range
10911 .head()
10912 .0
10913 .saturating_add_signed(relative_utf16_range.end),
10914 );
10915 start..end
10916 });
10917 s.select_ranges(new_ranges);
10918 });
10919 }
10920
10921 self.handle_input(text, cx);
10922 }
10923
10924 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
10925 let Some(project) = self.project.as_ref() else {
10926 return false;
10927 };
10928 let project = project.read(cx);
10929
10930 let mut supports = false;
10931 self.buffer().read(cx).for_each_buffer(|buffer| {
10932 if !supports {
10933 supports = project
10934 .language_servers_for_buffer(buffer.read(cx), cx)
10935 .any(
10936 |(_, server)| match server.capabilities().inlay_hint_provider {
10937 Some(lsp::OneOf::Left(enabled)) => enabled,
10938 Some(lsp::OneOf::Right(_)) => true,
10939 None => false,
10940 },
10941 )
10942 }
10943 });
10944 supports
10945 }
10946
10947 pub fn focus(&self, cx: &mut WindowContext) {
10948 cx.focus(&self.focus_handle)
10949 }
10950
10951 pub fn is_focused(&self, cx: &WindowContext) -> bool {
10952 self.focus_handle.is_focused(cx)
10953 }
10954
10955 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
10956 cx.emit(EditorEvent::Focused);
10957 if let Some(rename) = self.pending_rename.as_ref() {
10958 let rename_editor_focus_handle = rename.editor.read(cx).focus_handle.clone();
10959 cx.focus(&rename_editor_focus_handle);
10960 } else {
10961 if let Some(blame) = self.blame.as_ref() {
10962 blame.update(cx, GitBlame::focus)
10963 }
10964
10965 self.blink_manager.update(cx, BlinkManager::enable);
10966 self.show_cursor_names(cx);
10967 self.buffer.update(cx, |buffer, cx| {
10968 buffer.finalize_last_transaction(cx);
10969 if self.leader_peer_id.is_none() {
10970 buffer.set_active_selections(
10971 &self.selections.disjoint_anchors(),
10972 self.selections.line_mode,
10973 self.cursor_shape,
10974 cx,
10975 );
10976 }
10977 });
10978 }
10979 }
10980
10981 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
10982 self.blink_manager.update(cx, BlinkManager::disable);
10983 self.buffer
10984 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
10985
10986 if let Some(blame) = self.blame.as_ref() {
10987 blame.update(cx, GitBlame::blur)
10988 }
10989 self.hide_context_menu(cx);
10990 hide_hover(self, cx);
10991 cx.emit(EditorEvent::Blurred);
10992 cx.notify();
10993 }
10994
10995 pub fn register_action<A: Action>(
10996 &mut self,
10997 listener: impl Fn(&A, &mut WindowContext) + 'static,
10998 ) -> &mut Self {
10999 let listener = Arc::new(listener);
11000
11001 self.editor_actions.push(Box::new(move |cx| {
11002 let _view = cx.view().clone();
11003 let cx = cx.window_context();
11004 let listener = listener.clone();
11005 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
11006 let action = action.downcast_ref().unwrap();
11007 if phase == DispatchPhase::Bubble {
11008 listener(action, cx)
11009 }
11010 })
11011 }));
11012 self
11013 }
11014}
11015
11016fn hunks_for_selections(
11017 multi_buffer_snapshot: &MultiBufferSnapshot,
11018 selections: &[Selection<Anchor>],
11019) -> Vec<DiffHunk<MultiBufferRow>> {
11020 let mut hunks = Vec::with_capacity(selections.len());
11021 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
11022 HashMap::default();
11023 let buffer_rows_for_selections = selections.iter().map(|selection| {
11024 let head = selection.head();
11025 let tail = selection.tail();
11026 let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
11027 let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
11028 if start > end {
11029 end..start
11030 } else {
11031 start..end
11032 }
11033 });
11034
11035 for selected_multi_buffer_rows in buffer_rows_for_selections {
11036 let query_rows =
11037 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
11038 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
11039 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
11040 // when the caret is just above or just below the deleted hunk.
11041 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
11042 let related_to_selection = if allow_adjacent {
11043 hunk.associated_range.overlaps(&query_rows)
11044 || hunk.associated_range.start == query_rows.end
11045 || hunk.associated_range.end == query_rows.start
11046 } else {
11047 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
11048 // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
11049 hunk.associated_range.overlaps(&selected_multi_buffer_rows)
11050 || selected_multi_buffer_rows.end == hunk.associated_range.start
11051 };
11052 if related_to_selection {
11053 if !processed_buffer_rows
11054 .entry(hunk.buffer_id)
11055 .or_default()
11056 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
11057 {
11058 continue;
11059 }
11060 hunks.push(hunk);
11061 }
11062 }
11063 }
11064
11065 hunks
11066}
11067
11068pub trait CollaborationHub {
11069 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
11070 fn user_participant_indices<'a>(
11071 &self,
11072 cx: &'a AppContext,
11073 ) -> &'a HashMap<u64, ParticipantIndex>;
11074 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
11075}
11076
11077impl CollaborationHub for Model<Project> {
11078 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
11079 self.read(cx).collaborators()
11080 }
11081
11082 fn user_participant_indices<'a>(
11083 &self,
11084 cx: &'a AppContext,
11085 ) -> &'a HashMap<u64, ParticipantIndex> {
11086 self.read(cx).user_store().read(cx).participant_indices()
11087 }
11088
11089 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
11090 let this = self.read(cx);
11091 let user_ids = this.collaborators().values().map(|c| c.user_id);
11092 this.user_store().read_with(cx, |user_store, cx| {
11093 user_store.participant_names(user_ids, cx)
11094 })
11095 }
11096}
11097
11098pub trait CompletionProvider {
11099 fn completions(
11100 &self,
11101 buffer: &Model<Buffer>,
11102 buffer_position: text::Anchor,
11103 cx: &mut ViewContext<Editor>,
11104 ) -> Task<Result<Vec<Completion>>>;
11105
11106 fn resolve_completions(
11107 &self,
11108 buffer: Model<Buffer>,
11109 completion_indices: Vec<usize>,
11110 completions: Arc<RwLock<Box<[Completion]>>>,
11111 cx: &mut ViewContext<Editor>,
11112 ) -> Task<Result<bool>>;
11113
11114 fn apply_additional_edits_for_completion(
11115 &self,
11116 buffer: Model<Buffer>,
11117 completion: Completion,
11118 push_to_history: bool,
11119 cx: &mut ViewContext<Editor>,
11120 ) -> Task<Result<Option<language::Transaction>>>;
11121
11122 fn is_completion_trigger(
11123 &self,
11124 buffer: &Model<Buffer>,
11125 position: language::Anchor,
11126 text: &str,
11127 trigger_in_words: bool,
11128 cx: &mut ViewContext<Editor>,
11129 ) -> bool;
11130}
11131
11132impl CompletionProvider for Model<Project> {
11133 fn completions(
11134 &self,
11135 buffer: &Model<Buffer>,
11136 buffer_position: text::Anchor,
11137 cx: &mut ViewContext<Editor>,
11138 ) -> Task<Result<Vec<Completion>>> {
11139 self.update(cx, |project, cx| {
11140 project.completions(&buffer, buffer_position, cx)
11141 })
11142 }
11143
11144 fn resolve_completions(
11145 &self,
11146 buffer: Model<Buffer>,
11147 completion_indices: Vec<usize>,
11148 completions: Arc<RwLock<Box<[Completion]>>>,
11149 cx: &mut ViewContext<Editor>,
11150 ) -> Task<Result<bool>> {
11151 self.update(cx, |project, cx| {
11152 project.resolve_completions(buffer, completion_indices, completions, cx)
11153 })
11154 }
11155
11156 fn apply_additional_edits_for_completion(
11157 &self,
11158 buffer: Model<Buffer>,
11159 completion: Completion,
11160 push_to_history: bool,
11161 cx: &mut ViewContext<Editor>,
11162 ) -> Task<Result<Option<language::Transaction>>> {
11163 self.update(cx, |project, cx| {
11164 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
11165 })
11166 }
11167
11168 fn is_completion_trigger(
11169 &self,
11170 buffer: &Model<Buffer>,
11171 position: language::Anchor,
11172 text: &str,
11173 trigger_in_words: bool,
11174 cx: &mut ViewContext<Editor>,
11175 ) -> bool {
11176 if !EditorSettings::get_global(cx).show_completions_on_input {
11177 return false;
11178 }
11179
11180 let mut chars = text.chars();
11181 let char = if let Some(char) = chars.next() {
11182 char
11183 } else {
11184 return false;
11185 };
11186 if chars.next().is_some() {
11187 return false;
11188 }
11189
11190 let buffer = buffer.read(cx);
11191 let scope = buffer.snapshot().language_scope_at(position);
11192 if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
11193 return true;
11194 }
11195
11196 buffer
11197 .completion_triggers()
11198 .iter()
11199 .any(|string| string == text)
11200 }
11201}
11202
11203fn inlay_hint_settings(
11204 location: Anchor,
11205 snapshot: &MultiBufferSnapshot,
11206 cx: &mut ViewContext<'_, Editor>,
11207) -> InlayHintSettings {
11208 let file = snapshot.file_at(location);
11209 let language = snapshot.language_at(location);
11210 let settings = all_language_settings(file, cx);
11211 settings
11212 .language(language.map(|l| l.name()).as_deref())
11213 .inlay_hints
11214}
11215
11216fn consume_contiguous_rows(
11217 contiguous_row_selections: &mut Vec<Selection<Point>>,
11218 selection: &Selection<Point>,
11219 display_map: &DisplaySnapshot,
11220 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
11221) -> (MultiBufferRow, MultiBufferRow) {
11222 contiguous_row_selections.push(selection.clone());
11223 let start_row = MultiBufferRow(selection.start.row);
11224 let mut end_row = ending_row(selection, display_map);
11225
11226 while let Some(next_selection) = selections.peek() {
11227 if next_selection.start.row <= end_row.0 {
11228 end_row = ending_row(next_selection, display_map);
11229 contiguous_row_selections.push(selections.next().unwrap().clone());
11230 } else {
11231 break;
11232 }
11233 }
11234 (start_row, end_row)
11235}
11236
11237fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
11238 if next_selection.end.column > 0 || next_selection.is_empty() {
11239 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
11240 } else {
11241 MultiBufferRow(next_selection.end.row)
11242 }
11243}
11244
11245impl EditorSnapshot {
11246 pub fn remote_selections_in_range<'a>(
11247 &'a self,
11248 range: &'a Range<Anchor>,
11249 collaboration_hub: &dyn CollaborationHub,
11250 cx: &'a AppContext,
11251 ) -> impl 'a + Iterator<Item = RemoteSelection> {
11252 let participant_names = collaboration_hub.user_names(cx);
11253 let participant_indices = collaboration_hub.user_participant_indices(cx);
11254 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
11255 let collaborators_by_replica_id = collaborators_by_peer_id
11256 .iter()
11257 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
11258 .collect::<HashMap<_, _>>();
11259 self.buffer_snapshot
11260 .remote_selections_in_range(range)
11261 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
11262 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
11263 let participant_index = participant_indices.get(&collaborator.user_id).copied();
11264 let user_name = participant_names.get(&collaborator.user_id).cloned();
11265 Some(RemoteSelection {
11266 replica_id,
11267 selection,
11268 cursor_shape,
11269 line_mode,
11270 participant_index,
11271 peer_id: collaborator.peer_id,
11272 user_name,
11273 })
11274 })
11275 }
11276
11277 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
11278 self.display_snapshot.buffer_snapshot.language_at(position)
11279 }
11280
11281 pub fn is_focused(&self) -> bool {
11282 self.is_focused
11283 }
11284
11285 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
11286 self.placeholder_text.as_ref()
11287 }
11288
11289 pub fn scroll_position(&self) -> gpui::Point<f32> {
11290 self.scroll_anchor.scroll_position(&self.display_snapshot)
11291 }
11292
11293 pub fn gutter_dimensions(
11294 &self,
11295 font_id: FontId,
11296 font_size: Pixels,
11297 em_width: Pixels,
11298 max_line_number_width: Pixels,
11299 cx: &AppContext,
11300 ) -> GutterDimensions {
11301 if !self.show_gutter {
11302 return GutterDimensions::default();
11303 }
11304 let descent = cx.text_system().descent(font_id, font_size);
11305
11306 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
11307 matches!(
11308 ProjectSettings::get_global(cx).git.git_gutter,
11309 Some(GitGutterSetting::TrackedFiles)
11310 )
11311 });
11312 let gutter_settings = EditorSettings::get_global(cx).gutter;
11313 let show_line_numbers = self
11314 .show_line_numbers
11315 .unwrap_or_else(|| gutter_settings.line_numbers);
11316 let line_gutter_width = if show_line_numbers {
11317 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
11318 let min_width_for_number_on_gutter = em_width * 4.0;
11319 max_line_number_width.max(min_width_for_number_on_gutter)
11320 } else {
11321 0.0.into()
11322 };
11323
11324 let show_code_actions = self
11325 .show_code_actions
11326 .unwrap_or_else(|| gutter_settings.code_actions);
11327
11328 let git_blame_entries_width = self
11329 .render_git_blame_gutter
11330 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
11331
11332 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
11333 left_padding += if show_code_actions {
11334 em_width * 3.0
11335 } else if show_git_gutter && show_line_numbers {
11336 em_width * 2.0
11337 } else if show_git_gutter || show_line_numbers {
11338 em_width
11339 } else {
11340 px(0.)
11341 };
11342
11343 let right_padding = if gutter_settings.folds && show_line_numbers {
11344 em_width * 4.0
11345 } else if gutter_settings.folds {
11346 em_width * 3.0
11347 } else if show_line_numbers {
11348 em_width
11349 } else {
11350 px(0.)
11351 };
11352
11353 GutterDimensions {
11354 left_padding,
11355 right_padding,
11356 width: line_gutter_width + left_padding + right_padding,
11357 margin: -descent,
11358 git_blame_entries_width,
11359 }
11360 }
11361
11362 pub fn render_fold_toggle(
11363 &self,
11364 buffer_row: MultiBufferRow,
11365 row_contains_cursor: bool,
11366 editor: View<Editor>,
11367 cx: &mut WindowContext,
11368 ) -> Option<AnyElement> {
11369 let folded = self.is_line_folded(buffer_row);
11370
11371 if let Some(flap) = self
11372 .flap_snapshot
11373 .query_row(buffer_row, &self.buffer_snapshot)
11374 {
11375 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
11376 if folded {
11377 editor.update(cx, |editor, cx| {
11378 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
11379 });
11380 } else {
11381 editor.update(cx, |editor, cx| {
11382 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
11383 });
11384 }
11385 });
11386
11387 Some((flap.render_toggle)(
11388 buffer_row,
11389 folded,
11390 toggle_callback,
11391 cx,
11392 ))
11393 } else if folded
11394 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
11395 {
11396 Some(
11397 IconButton::new(
11398 ("indent-fold-indicator", buffer_row.0),
11399 ui::IconName::ChevronDown,
11400 )
11401 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
11402 if folded {
11403 this.unfold_at(&UnfoldAt { buffer_row }, cx);
11404 } else {
11405 this.fold_at(&FoldAt { buffer_row }, cx);
11406 }
11407 }))
11408 .icon_color(ui::Color::Muted)
11409 .icon_size(ui::IconSize::Small)
11410 .selected(folded)
11411 .selected_icon(ui::IconName::ChevronRight)
11412 .size(ui::ButtonSize::None)
11413 .into_any_element(),
11414 )
11415 } else {
11416 None
11417 }
11418 }
11419
11420 pub fn render_flap_trailer(
11421 &self,
11422 buffer_row: MultiBufferRow,
11423 cx: &mut WindowContext,
11424 ) -> Option<AnyElement> {
11425 let folded = self.is_line_folded(buffer_row);
11426 let flap = self
11427 .flap_snapshot
11428 .query_row(buffer_row, &self.buffer_snapshot)?;
11429 Some((flap.render_trailer)(buffer_row, folded, cx))
11430 }
11431}
11432
11433impl Deref for EditorSnapshot {
11434 type Target = DisplaySnapshot;
11435
11436 fn deref(&self) -> &Self::Target {
11437 &self.display_snapshot
11438 }
11439}
11440
11441#[derive(Clone, Debug, PartialEq, Eq)]
11442pub enum EditorEvent {
11443 InputIgnored {
11444 text: Arc<str>,
11445 },
11446 InputHandled {
11447 utf16_range_to_replace: Option<Range<isize>>,
11448 text: Arc<str>,
11449 },
11450 ExcerptsAdded {
11451 buffer: Model<Buffer>,
11452 predecessor: ExcerptId,
11453 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
11454 },
11455 ExcerptsRemoved {
11456 ids: Vec<ExcerptId>,
11457 },
11458 BufferEdited,
11459 Edited,
11460 Reparsed,
11461 Focused,
11462 Blurred,
11463 DirtyChanged,
11464 Saved,
11465 TitleChanged,
11466 DiffBaseChanged,
11467 SelectionsChanged {
11468 local: bool,
11469 },
11470 ScrollPositionChanged {
11471 local: bool,
11472 autoscroll: bool,
11473 },
11474 Closed,
11475 TransactionUndone {
11476 transaction_id: clock::Lamport,
11477 },
11478 TransactionBegun {
11479 transaction_id: clock::Lamport,
11480 },
11481}
11482
11483impl EventEmitter<EditorEvent> for Editor {}
11484
11485impl FocusableView for Editor {
11486 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
11487 self.focus_handle.clone()
11488 }
11489}
11490
11491impl Render for Editor {
11492 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
11493 let settings = ThemeSettings::get_global(cx);
11494
11495 let text_style = match self.mode {
11496 EditorMode::SingleLine | EditorMode::AutoHeight { .. } => TextStyle {
11497 color: cx.theme().colors().editor_foreground,
11498 font_family: settings.ui_font.family.clone(),
11499 font_features: settings.ui_font.features.clone(),
11500 font_size: rems(0.875).into(),
11501 font_weight: settings.ui_font.weight,
11502 font_style: FontStyle::Normal,
11503 line_height: relative(settings.buffer_line_height.value()),
11504 background_color: None,
11505 underline: None,
11506 strikethrough: None,
11507 white_space: WhiteSpace::Normal,
11508 },
11509 EditorMode::Full => TextStyle {
11510 color: cx.theme().colors().editor_foreground,
11511 font_family: settings.buffer_font.family.clone(),
11512 font_features: settings.buffer_font.features.clone(),
11513 font_size: settings.buffer_font_size(cx).into(),
11514 font_weight: settings.buffer_font.weight,
11515 font_style: FontStyle::Normal,
11516 line_height: relative(settings.buffer_line_height.value()),
11517 background_color: None,
11518 underline: None,
11519 strikethrough: None,
11520 white_space: WhiteSpace::Normal,
11521 },
11522 };
11523
11524 let background = match self.mode {
11525 EditorMode::SingleLine => cx.theme().system().transparent,
11526 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
11527 EditorMode::Full => cx.theme().colors().editor_background,
11528 };
11529
11530 EditorElement::new(
11531 cx.view(),
11532 EditorStyle {
11533 background,
11534 local_player: cx.theme().players().local(),
11535 text: text_style,
11536 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
11537 syntax: cx.theme().syntax().clone(),
11538 status: cx.theme().status().clone(),
11539 inlay_hints_style: HighlightStyle {
11540 color: Some(cx.theme().status().hint),
11541 ..HighlightStyle::default()
11542 },
11543 suggestions_style: HighlightStyle {
11544 color: Some(cx.theme().status().predictive),
11545 ..HighlightStyle::default()
11546 },
11547 },
11548 )
11549 }
11550}
11551
11552impl ViewInputHandler for Editor {
11553 fn text_for_range(
11554 &mut self,
11555 range_utf16: Range<usize>,
11556 cx: &mut ViewContext<Self>,
11557 ) -> Option<String> {
11558 Some(
11559 self.buffer
11560 .read(cx)
11561 .read(cx)
11562 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
11563 .collect(),
11564 )
11565 }
11566
11567 fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
11568 // Prevent the IME menu from appearing when holding down an alphabetic key
11569 // while input is disabled.
11570 if !self.input_enabled {
11571 return None;
11572 }
11573
11574 let range = self.selections.newest::<OffsetUtf16>(cx).range();
11575 Some(range.start.0..range.end.0)
11576 }
11577
11578 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
11579 let snapshot = self.buffer.read(cx).read(cx);
11580 let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
11581 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
11582 }
11583
11584 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
11585 self.clear_highlights::<InputComposition>(cx);
11586 self.ime_transaction.take();
11587 }
11588
11589 fn replace_text_in_range(
11590 &mut self,
11591 range_utf16: Option<Range<usize>>,
11592 text: &str,
11593 cx: &mut ViewContext<Self>,
11594 ) {
11595 if !self.input_enabled {
11596 cx.emit(EditorEvent::InputIgnored { text: text.into() });
11597 return;
11598 }
11599
11600 self.transact(cx, |this, cx| {
11601 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
11602 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
11603 Some(this.selection_replacement_ranges(range_utf16, cx))
11604 } else {
11605 this.marked_text_ranges(cx)
11606 };
11607
11608 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
11609 let newest_selection_id = this.selections.newest_anchor().id;
11610 this.selections
11611 .all::<OffsetUtf16>(cx)
11612 .iter()
11613 .zip(ranges_to_replace.iter())
11614 .find_map(|(selection, range)| {
11615 if selection.id == newest_selection_id {
11616 Some(
11617 (range.start.0 as isize - selection.head().0 as isize)
11618 ..(range.end.0 as isize - selection.head().0 as isize),
11619 )
11620 } else {
11621 None
11622 }
11623 })
11624 });
11625
11626 cx.emit(EditorEvent::InputHandled {
11627 utf16_range_to_replace: range_to_replace,
11628 text: text.into(),
11629 });
11630
11631 if let Some(new_selected_ranges) = new_selected_ranges {
11632 this.change_selections(None, cx, |selections| {
11633 selections.select_ranges(new_selected_ranges)
11634 });
11635 this.backspace(&Default::default(), cx);
11636 }
11637
11638 this.handle_input(text, cx);
11639 });
11640
11641 if let Some(transaction) = self.ime_transaction {
11642 self.buffer.update(cx, |buffer, cx| {
11643 buffer.group_until_transaction(transaction, cx);
11644 });
11645 }
11646
11647 self.unmark_text(cx);
11648 }
11649
11650 fn replace_and_mark_text_in_range(
11651 &mut self,
11652 range_utf16: Option<Range<usize>>,
11653 text: &str,
11654 new_selected_range_utf16: Option<Range<usize>>,
11655 cx: &mut ViewContext<Self>,
11656 ) {
11657 if !self.input_enabled {
11658 cx.emit(EditorEvent::InputIgnored { text: text.into() });
11659 return;
11660 }
11661
11662 let transaction = self.transact(cx, |this, cx| {
11663 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
11664 let snapshot = this.buffer.read(cx).read(cx);
11665 if let Some(relative_range_utf16) = range_utf16.as_ref() {
11666 for marked_range in &mut marked_ranges {
11667 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
11668 marked_range.start.0 += relative_range_utf16.start;
11669 marked_range.start =
11670 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
11671 marked_range.end =
11672 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
11673 }
11674 }
11675 Some(marked_ranges)
11676 } else if let Some(range_utf16) = range_utf16 {
11677 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
11678 Some(this.selection_replacement_ranges(range_utf16, cx))
11679 } else {
11680 None
11681 };
11682
11683 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
11684 let newest_selection_id = this.selections.newest_anchor().id;
11685 this.selections
11686 .all::<OffsetUtf16>(cx)
11687 .iter()
11688 .zip(ranges_to_replace.iter())
11689 .find_map(|(selection, range)| {
11690 if selection.id == newest_selection_id {
11691 Some(
11692 (range.start.0 as isize - selection.head().0 as isize)
11693 ..(range.end.0 as isize - selection.head().0 as isize),
11694 )
11695 } else {
11696 None
11697 }
11698 })
11699 });
11700
11701 cx.emit(EditorEvent::InputHandled {
11702 utf16_range_to_replace: range_to_replace,
11703 text: text.into(),
11704 });
11705
11706 if let Some(ranges) = ranges_to_replace {
11707 this.change_selections(None, cx, |s| s.select_ranges(ranges));
11708 }
11709
11710 let marked_ranges = {
11711 let snapshot = this.buffer.read(cx).read(cx);
11712 this.selections
11713 .disjoint_anchors()
11714 .iter()
11715 .map(|selection| {
11716 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
11717 })
11718 .collect::<Vec<_>>()
11719 };
11720
11721 if text.is_empty() {
11722 this.unmark_text(cx);
11723 } else {
11724 this.highlight_text::<InputComposition>(
11725 marked_ranges.clone(),
11726 HighlightStyle {
11727 underline: Some(UnderlineStyle {
11728 thickness: px(1.),
11729 color: None,
11730 wavy: false,
11731 }),
11732 ..Default::default()
11733 },
11734 cx,
11735 );
11736 }
11737
11738 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
11739 let use_autoclose = this.use_autoclose;
11740 this.set_use_autoclose(false);
11741 this.handle_input(text, cx);
11742 this.set_use_autoclose(use_autoclose);
11743
11744 if let Some(new_selected_range) = new_selected_range_utf16 {
11745 let snapshot = this.buffer.read(cx).read(cx);
11746 let new_selected_ranges = marked_ranges
11747 .into_iter()
11748 .map(|marked_range| {
11749 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
11750 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
11751 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
11752 snapshot.clip_offset_utf16(new_start, Bias::Left)
11753 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
11754 })
11755 .collect::<Vec<_>>();
11756
11757 drop(snapshot);
11758 this.change_selections(None, cx, |selections| {
11759 selections.select_ranges(new_selected_ranges)
11760 });
11761 }
11762 });
11763
11764 self.ime_transaction = self.ime_transaction.or(transaction);
11765 if let Some(transaction) = self.ime_transaction {
11766 self.buffer.update(cx, |buffer, cx| {
11767 buffer.group_until_transaction(transaction, cx);
11768 });
11769 }
11770
11771 if self.text_highlights::<InputComposition>(cx).is_none() {
11772 self.ime_transaction.take();
11773 }
11774 }
11775
11776 fn bounds_for_range(
11777 &mut self,
11778 range_utf16: Range<usize>,
11779 element_bounds: gpui::Bounds<Pixels>,
11780 cx: &mut ViewContext<Self>,
11781 ) -> Option<gpui::Bounds<Pixels>> {
11782 let text_layout_details = self.text_layout_details(cx);
11783 let style = &text_layout_details.editor_style;
11784 let font_id = cx.text_system().resolve_font(&style.text.font());
11785 let font_size = style.text.font_size.to_pixels(cx.rem_size());
11786 let line_height = style.text.line_height_in_pixels(cx.rem_size());
11787 let em_width = cx
11788 .text_system()
11789 .typographic_bounds(font_id, font_size, 'm')
11790 .unwrap()
11791 .size
11792 .width;
11793
11794 let snapshot = self.snapshot(cx);
11795 let scroll_position = snapshot.scroll_position();
11796 let scroll_left = scroll_position.x * em_width;
11797
11798 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
11799 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
11800 + self.gutter_dimensions.width;
11801 let y = line_height * (start.row().as_f32() - scroll_position.y);
11802
11803 Some(Bounds {
11804 origin: element_bounds.origin + point(x, y),
11805 size: size(em_width, line_height),
11806 })
11807 }
11808}
11809
11810trait SelectionExt {
11811 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
11812 fn spanned_rows(
11813 &self,
11814 include_end_if_at_line_start: bool,
11815 map: &DisplaySnapshot,
11816 ) -> Range<MultiBufferRow>;
11817}
11818
11819impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
11820 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
11821 let start = self
11822 .start
11823 .to_point(&map.buffer_snapshot)
11824 .to_display_point(map);
11825 let end = self
11826 .end
11827 .to_point(&map.buffer_snapshot)
11828 .to_display_point(map);
11829 if self.reversed {
11830 end..start
11831 } else {
11832 start..end
11833 }
11834 }
11835
11836 fn spanned_rows(
11837 &self,
11838 include_end_if_at_line_start: bool,
11839 map: &DisplaySnapshot,
11840 ) -> Range<MultiBufferRow> {
11841 let start = self.start.to_point(&map.buffer_snapshot);
11842 let mut end = self.end.to_point(&map.buffer_snapshot);
11843 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
11844 end.row -= 1;
11845 }
11846
11847 let buffer_start = map.prev_line_boundary(start).0;
11848 let buffer_end = map.next_line_boundary(end).0;
11849 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
11850 }
11851}
11852
11853impl<T: InvalidationRegion> InvalidationStack<T> {
11854 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
11855 where
11856 S: Clone + ToOffset,
11857 {
11858 while let Some(region) = self.last() {
11859 let all_selections_inside_invalidation_ranges =
11860 if selections.len() == region.ranges().len() {
11861 selections
11862 .iter()
11863 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
11864 .all(|(selection, invalidation_range)| {
11865 let head = selection.head().to_offset(buffer);
11866 invalidation_range.start <= head && invalidation_range.end >= head
11867 })
11868 } else {
11869 false
11870 };
11871
11872 if all_selections_inside_invalidation_ranges {
11873 break;
11874 } else {
11875 self.pop();
11876 }
11877 }
11878 }
11879}
11880
11881impl<T> Default for InvalidationStack<T> {
11882 fn default() -> Self {
11883 Self(Default::default())
11884 }
11885}
11886
11887impl<T> Deref for InvalidationStack<T> {
11888 type Target = Vec<T>;
11889
11890 fn deref(&self) -> &Self::Target {
11891 &self.0
11892 }
11893}
11894
11895impl<T> DerefMut for InvalidationStack<T> {
11896 fn deref_mut(&mut self) -> &mut Self::Target {
11897 &mut self.0
11898 }
11899}
11900
11901impl InvalidationRegion for SnippetState {
11902 fn ranges(&self) -> &[Range<Anchor>] {
11903 &self.ranges[self.active_index]
11904 }
11905}
11906
11907pub fn diagnostic_block_renderer(diagnostic: Diagnostic, _is_valid: bool) -> RenderBlock {
11908 let (text_without_backticks, code_ranges) = highlight_diagnostic_message(&diagnostic);
11909
11910 Box::new(move |cx: &mut BlockContext| {
11911 let group_id: SharedString = cx.block_id.to_string().into();
11912
11913 let mut text_style = cx.text_style().clone();
11914 text_style.color = diagnostic_style(diagnostic.severity, true, cx.theme().status());
11915 let theme_settings = ThemeSettings::get_global(cx);
11916 text_style.font_family = theme_settings.buffer_font.family.clone();
11917 text_style.font_style = theme_settings.buffer_font.style;
11918 text_style.font_features = theme_settings.buffer_font.features.clone();
11919 text_style.font_weight = theme_settings.buffer_font.weight;
11920
11921 let multi_line_diagnostic = diagnostic.message.contains('\n');
11922
11923 let buttons = |diagnostic: &Diagnostic, block_id: usize| {
11924 if multi_line_diagnostic {
11925 v_flex()
11926 } else {
11927 h_flex()
11928 }
11929 .children(diagnostic.is_primary.then(|| {
11930 IconButton::new(("close-block", block_id), IconName::XCircle)
11931 .icon_color(Color::Muted)
11932 .size(ButtonSize::Compact)
11933 .style(ButtonStyle::Transparent)
11934 .visible_on_hover(group_id.clone())
11935 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
11936 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
11937 }))
11938 .child(
11939 IconButton::new(("copy-block", block_id), IconName::Copy)
11940 .icon_color(Color::Muted)
11941 .size(ButtonSize::Compact)
11942 .style(ButtonStyle::Transparent)
11943 .visible_on_hover(group_id.clone())
11944 .on_click({
11945 let message = diagnostic.message.clone();
11946 move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
11947 })
11948 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
11949 )
11950 };
11951
11952 let icon_size = buttons(&diagnostic, cx.block_id)
11953 .into_any_element()
11954 .layout_as_root(AvailableSpace::min_size(), cx);
11955
11956 h_flex()
11957 .id(cx.block_id)
11958 .group(group_id.clone())
11959 .relative()
11960 .size_full()
11961 .pl(cx.gutter_dimensions.width)
11962 .w(cx.max_width + cx.gutter_dimensions.width)
11963 .child(
11964 div()
11965 .flex()
11966 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
11967 .flex_shrink(),
11968 )
11969 .child(buttons(&diagnostic, cx.block_id))
11970 .child(div().flex().flex_shrink_0().child(
11971 StyledText::new(text_without_backticks.clone()).with_highlights(
11972 &text_style,
11973 code_ranges.iter().map(|range| {
11974 (
11975 range.clone(),
11976 HighlightStyle {
11977 font_weight: Some(FontWeight::BOLD),
11978 ..Default::default()
11979 },
11980 )
11981 }),
11982 ),
11983 ))
11984 .into_any_element()
11985 })
11986}
11987
11988pub fn highlight_diagnostic_message(diagnostic: &Diagnostic) -> (SharedString, Vec<Range<usize>>) {
11989 let mut text_without_backticks = String::new();
11990 let mut code_ranges = Vec::new();
11991
11992 if let Some(source) = &diagnostic.source {
11993 text_without_backticks.push_str(&source);
11994 code_ranges.push(0..source.len());
11995 text_without_backticks.push_str(": ");
11996 }
11997
11998 let mut prev_offset = 0;
11999 let mut in_code_block = false;
12000 for (ix, _) in diagnostic
12001 .message
12002 .match_indices('`')
12003 .chain([(diagnostic.message.len(), "")])
12004 {
12005 let prev_len = text_without_backticks.len();
12006 text_without_backticks.push_str(&diagnostic.message[prev_offset..ix]);
12007 prev_offset = ix + 1;
12008 if in_code_block {
12009 code_ranges.push(prev_len..text_without_backticks.len());
12010 in_code_block = false;
12011 } else {
12012 in_code_block = true;
12013 }
12014 }
12015
12016 (text_without_backticks.into(), code_ranges)
12017}
12018
12019fn diagnostic_style(severity: DiagnosticSeverity, valid: bool, colors: &StatusColors) -> Hsla {
12020 match (severity, valid) {
12021 (DiagnosticSeverity::ERROR, true) => colors.error,
12022 (DiagnosticSeverity::ERROR, false) => colors.error,
12023 (DiagnosticSeverity::WARNING, true) => colors.warning,
12024 (DiagnosticSeverity::WARNING, false) => colors.warning,
12025 (DiagnosticSeverity::INFORMATION, true) => colors.info,
12026 (DiagnosticSeverity::INFORMATION, false) => colors.info,
12027 (DiagnosticSeverity::HINT, true) => colors.info,
12028 (DiagnosticSeverity::HINT, false) => colors.info,
12029 _ => colors.ignored,
12030 }
12031}
12032
12033pub fn styled_runs_for_code_label<'a>(
12034 label: &'a CodeLabel,
12035 syntax_theme: &'a theme::SyntaxTheme,
12036) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
12037 let fade_out = HighlightStyle {
12038 fade_out: Some(0.35),
12039 ..Default::default()
12040 };
12041
12042 let mut prev_end = label.filter_range.end;
12043 label
12044 .runs
12045 .iter()
12046 .enumerate()
12047 .flat_map(move |(ix, (range, highlight_id))| {
12048 let style = if let Some(style) = highlight_id.style(syntax_theme) {
12049 style
12050 } else {
12051 return Default::default();
12052 };
12053 let mut muted_style = style;
12054 muted_style.highlight(fade_out);
12055
12056 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
12057 if range.start >= label.filter_range.end {
12058 if range.start > prev_end {
12059 runs.push((prev_end..range.start, fade_out));
12060 }
12061 runs.push((range.clone(), muted_style));
12062 } else if range.end <= label.filter_range.end {
12063 runs.push((range.clone(), style));
12064 } else {
12065 runs.push((range.start..label.filter_range.end, style));
12066 runs.push((label.filter_range.end..range.end, muted_style));
12067 }
12068 prev_end = cmp::max(prev_end, range.end);
12069
12070 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
12071 runs.push((prev_end..label.text.len(), fade_out));
12072 }
12073
12074 runs
12075 })
12076}
12077
12078pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
12079 let mut prev_index = 0;
12080 let mut prev_codepoint: Option<char> = None;
12081 text.char_indices()
12082 .chain([(text.len(), '\0')])
12083 .filter_map(move |(index, codepoint)| {
12084 let prev_codepoint = prev_codepoint.replace(codepoint)?;
12085 let is_boundary = index == text.len()
12086 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
12087 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
12088 if is_boundary {
12089 let chunk = &text[prev_index..index];
12090 prev_index = index;
12091 Some(chunk)
12092 } else {
12093 None
12094 }
12095 })
12096}
12097
12098trait RangeToAnchorExt {
12099 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
12100}
12101
12102impl<T: ToOffset> RangeToAnchorExt for Range<T> {
12103 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
12104 let start_offset = self.start.to_offset(snapshot);
12105 let end_offset = self.end.to_offset(snapshot);
12106 if start_offset == end_offset {
12107 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
12108 } else {
12109 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
12110 }
12111 }
12112}
12113
12114pub trait RowExt {
12115 fn as_f32(&self) -> f32;
12116
12117 fn next_row(&self) -> Self;
12118
12119 fn previous_row(&self) -> Self;
12120
12121 fn minus(&self, other: Self) -> u32;
12122}
12123
12124impl RowExt for DisplayRow {
12125 fn as_f32(&self) -> f32 {
12126 self.0 as f32
12127 }
12128
12129 fn next_row(&self) -> Self {
12130 Self(self.0 + 1)
12131 }
12132
12133 fn previous_row(&self) -> Self {
12134 Self(self.0.saturating_sub(1))
12135 }
12136
12137 fn minus(&self, other: Self) -> u32 {
12138 self.0 - other.0
12139 }
12140}
12141
12142impl RowExt for MultiBufferRow {
12143 fn as_f32(&self) -> f32 {
12144 self.0 as f32
12145 }
12146
12147 fn next_row(&self) -> Self {
12148 Self(self.0 + 1)
12149 }
12150
12151 fn previous_row(&self) -> Self {
12152 Self(self.0.saturating_sub(1))
12153 }
12154
12155 fn minus(&self, other: Self) -> u32 {
12156 self.0 - other.0
12157 }
12158}
12159
12160trait RowRangeExt {
12161 type Row;
12162
12163 fn len(&self) -> usize;
12164
12165 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
12166}
12167
12168impl RowRangeExt for Range<MultiBufferRow> {
12169 type Row = MultiBufferRow;
12170
12171 fn len(&self) -> usize {
12172 (self.end.0 - self.start.0) as usize
12173 }
12174
12175 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
12176 (self.start.0..self.end.0).map(MultiBufferRow)
12177 }
12178}
12179
12180impl RowRangeExt for Range<DisplayRow> {
12181 type Row = DisplayRow;
12182
12183 fn len(&self) -> usize {
12184 (self.end.0 - self.start.0) as usize
12185 }
12186
12187 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
12188 (self.start.0..self.end.0).map(DisplayRow)
12189 }
12190}
12191
12192fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
12193 if hunk.diff_base_byte_range.is_empty() {
12194 DiffHunkStatus::Added
12195 } else if hunk.associated_range.is_empty() {
12196 DiffHunkStatus::Removed
12197 } else {
12198 DiffHunkStatus::Modified
12199 }
12200}