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