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