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