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