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_enclosing_symbol(
8230 &mut self,
8231 _: &SelectEnclosingSymbol,
8232 cx: &mut ViewContext<Self>,
8233 ) {
8234 let buffer = self.buffer.read(cx).snapshot(cx);
8235 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8236
8237 fn update_selection(
8238 selection: &Selection<usize>,
8239 buffer_snap: &MultiBufferSnapshot,
8240 ) -> Option<Selection<usize>> {
8241 let cursor = selection.head();
8242 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8243 for symbol in symbols.iter().rev() {
8244 let start = symbol.range.start.to_offset(&buffer_snap);
8245 let end = symbol.range.end.to_offset(&buffer_snap);
8246 let new_range = start..end;
8247 if start < selection.start || end > selection.end {
8248 return Some(Selection {
8249 id: selection.id,
8250 start: new_range.start,
8251 end: new_range.end,
8252 goal: SelectionGoal::None,
8253 reversed: selection.reversed,
8254 });
8255 }
8256 }
8257 None
8258 }
8259
8260 let mut selected_larger_symbol = false;
8261 let new_selections = old_selections
8262 .iter()
8263 .map(|selection| match update_selection(selection, &buffer) {
8264 Some(new_selection) => {
8265 if new_selection.range() != selection.range() {
8266 selected_larger_symbol = true;
8267 }
8268 new_selection
8269 }
8270 None => selection.clone(),
8271 })
8272 .collect::<Vec<_>>();
8273
8274 if selected_larger_symbol {
8275 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8276 s.select(new_selections);
8277 });
8278 }
8279 }
8280
8281 pub fn select_larger_syntax_node(
8282 &mut self,
8283 _: &SelectLargerSyntaxNode,
8284 cx: &mut ViewContext<Self>,
8285 ) {
8286 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8287 let buffer = self.buffer.read(cx).snapshot(cx);
8288 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8289
8290 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8291 let mut selected_larger_node = false;
8292 let new_selections = old_selections
8293 .iter()
8294 .map(|selection| {
8295 let old_range = selection.start..selection.end;
8296 let mut new_range = old_range.clone();
8297 while let Some(containing_range) =
8298 buffer.range_for_syntax_ancestor(new_range.clone())
8299 {
8300 new_range = containing_range;
8301 if !display_map.intersects_fold(new_range.start)
8302 && !display_map.intersects_fold(new_range.end)
8303 {
8304 break;
8305 }
8306 }
8307
8308 selected_larger_node |= new_range != old_range;
8309 Selection {
8310 id: selection.id,
8311 start: new_range.start,
8312 end: new_range.end,
8313 goal: SelectionGoal::None,
8314 reversed: selection.reversed,
8315 }
8316 })
8317 .collect::<Vec<_>>();
8318
8319 if selected_larger_node {
8320 stack.push(old_selections);
8321 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8322 s.select(new_selections);
8323 });
8324 }
8325 self.select_larger_syntax_node_stack = stack;
8326 }
8327
8328 pub fn select_smaller_syntax_node(
8329 &mut self,
8330 _: &SelectSmallerSyntaxNode,
8331 cx: &mut ViewContext<Self>,
8332 ) {
8333 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8334 if let Some(selections) = stack.pop() {
8335 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8336 s.select(selections.to_vec());
8337 });
8338 }
8339 self.select_larger_syntax_node_stack = stack;
8340 }
8341
8342 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8343 if !EditorSettings::get_global(cx).gutter.runnables {
8344 self.clear_tasks();
8345 return Task::ready(());
8346 }
8347 let project = self.project.clone();
8348 cx.spawn(|this, mut cx| async move {
8349 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8350 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8351 }) else {
8352 return;
8353 };
8354
8355 let Some(project) = project else {
8356 return;
8357 };
8358
8359 let hide_runnables = project
8360 .update(&mut cx, |project, cx| {
8361 // Do not display any test indicators in non-dev server remote projects.
8362 project.is_remote() && project.ssh_connection_string(cx).is_none()
8363 })
8364 .unwrap_or(true);
8365 if hide_runnables {
8366 return;
8367 }
8368 let new_rows =
8369 cx.background_executor()
8370 .spawn({
8371 let snapshot = display_snapshot.clone();
8372 async move {
8373 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8374 }
8375 })
8376 .await;
8377 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8378
8379 this.update(&mut cx, |this, _| {
8380 this.clear_tasks();
8381 for (key, value) in rows {
8382 this.insert_tasks(key, value);
8383 }
8384 })
8385 .ok();
8386 })
8387 }
8388 fn fetch_runnable_ranges(
8389 snapshot: &DisplaySnapshot,
8390 range: Range<Anchor>,
8391 ) -> Vec<language::RunnableRange> {
8392 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8393 }
8394
8395 fn runnable_rows(
8396 project: Model<Project>,
8397 snapshot: DisplaySnapshot,
8398 runnable_ranges: Vec<RunnableRange>,
8399 mut cx: AsyncWindowContext,
8400 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8401 runnable_ranges
8402 .into_iter()
8403 .filter_map(|mut runnable| {
8404 let tasks = cx
8405 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8406 .ok()?;
8407 if tasks.is_empty() {
8408 return None;
8409 }
8410
8411 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8412
8413 let row = snapshot
8414 .buffer_snapshot
8415 .buffer_line_for_row(MultiBufferRow(point.row))?
8416 .1
8417 .start
8418 .row;
8419
8420 let context_range =
8421 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8422 Some((
8423 (runnable.buffer_id, row),
8424 RunnableTasks {
8425 templates: tasks,
8426 offset: MultiBufferOffset(runnable.run_range.start),
8427 context_range,
8428 column: point.column,
8429 extra_variables: runnable.extra_captures,
8430 },
8431 ))
8432 })
8433 .collect()
8434 }
8435
8436 fn templates_with_tags(
8437 project: &Model<Project>,
8438 runnable: &mut Runnable,
8439 cx: &WindowContext<'_>,
8440 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8441 let (inventory, worktree_id) = project.read_with(cx, |project, cx| {
8442 let worktree_id = project
8443 .buffer_for_id(runnable.buffer)
8444 .and_then(|buffer| buffer.read(cx).file())
8445 .map(|file| WorktreeId::from_usize(file.worktree_id()));
8446
8447 (project.task_inventory().clone(), worktree_id)
8448 });
8449
8450 let inventory = inventory.read(cx);
8451 let tags = mem::take(&mut runnable.tags);
8452 let mut tags: Vec<_> = tags
8453 .into_iter()
8454 .flat_map(|tag| {
8455 let tag = tag.0.clone();
8456 inventory
8457 .list_tasks(Some(runnable.language.clone()), worktree_id)
8458 .into_iter()
8459 .filter(move |(_, template)| {
8460 template.tags.iter().any(|source_tag| source_tag == &tag)
8461 })
8462 })
8463 .sorted_by_key(|(kind, _)| kind.to_owned())
8464 .collect();
8465 if let Some((leading_tag_source, _)) = tags.first() {
8466 // Strongest source wins; if we have worktree tag binding, prefer that to
8467 // global and language bindings;
8468 // if we have a global binding, prefer that to language binding.
8469 let first_mismatch = tags
8470 .iter()
8471 .position(|(tag_source, _)| tag_source != leading_tag_source);
8472 if let Some(index) = first_mismatch {
8473 tags.truncate(index);
8474 }
8475 }
8476
8477 tags
8478 }
8479
8480 pub fn move_to_enclosing_bracket(
8481 &mut self,
8482 _: &MoveToEnclosingBracket,
8483 cx: &mut ViewContext<Self>,
8484 ) {
8485 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8486 s.move_offsets_with(|snapshot, selection| {
8487 let Some(enclosing_bracket_ranges) =
8488 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
8489 else {
8490 return;
8491 };
8492
8493 let mut best_length = usize::MAX;
8494 let mut best_inside = false;
8495 let mut best_in_bracket_range = false;
8496 let mut best_destination = None;
8497 for (open, close) in enclosing_bracket_ranges {
8498 let close = close.to_inclusive();
8499 let length = close.end() - open.start;
8500 let inside = selection.start >= open.end && selection.end <= *close.start();
8501 let in_bracket_range = open.to_inclusive().contains(&selection.head())
8502 || close.contains(&selection.head());
8503
8504 // If best is next to a bracket and current isn't, skip
8505 if !in_bracket_range && best_in_bracket_range {
8506 continue;
8507 }
8508
8509 // Prefer smaller lengths unless best is inside and current isn't
8510 if length > best_length && (best_inside || !inside) {
8511 continue;
8512 }
8513
8514 best_length = length;
8515 best_inside = inside;
8516 best_in_bracket_range = in_bracket_range;
8517 best_destination = Some(
8518 if close.contains(&selection.start) && close.contains(&selection.end) {
8519 if inside {
8520 open.end
8521 } else {
8522 open.start
8523 }
8524 } else {
8525 if inside {
8526 *close.start()
8527 } else {
8528 *close.end()
8529 }
8530 },
8531 );
8532 }
8533
8534 if let Some(destination) = best_destination {
8535 selection.collapse_to(destination, SelectionGoal::None);
8536 }
8537 })
8538 });
8539 }
8540
8541 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
8542 self.end_selection(cx);
8543 self.selection_history.mode = SelectionHistoryMode::Undoing;
8544 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
8545 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8546 self.select_next_state = entry.select_next_state;
8547 self.select_prev_state = entry.select_prev_state;
8548 self.add_selections_state = entry.add_selections_state;
8549 self.request_autoscroll(Autoscroll::newest(), cx);
8550 }
8551 self.selection_history.mode = SelectionHistoryMode::Normal;
8552 }
8553
8554 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
8555 self.end_selection(cx);
8556 self.selection_history.mode = SelectionHistoryMode::Redoing;
8557 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
8558 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8559 self.select_next_state = entry.select_next_state;
8560 self.select_prev_state = entry.select_prev_state;
8561 self.add_selections_state = entry.add_selections_state;
8562 self.request_autoscroll(Autoscroll::newest(), cx);
8563 }
8564 self.selection_history.mode = SelectionHistoryMode::Normal;
8565 }
8566
8567 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
8568 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
8569 }
8570
8571 pub fn expand_excerpts_down(
8572 &mut self,
8573 action: &ExpandExcerptsDown,
8574 cx: &mut ViewContext<Self>,
8575 ) {
8576 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
8577 }
8578
8579 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
8580 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
8581 }
8582
8583 pub fn expand_excerpts_for_direction(
8584 &mut self,
8585 lines: u32,
8586 direction: ExpandExcerptDirection,
8587 cx: &mut ViewContext<Self>,
8588 ) {
8589 let selections = self.selections.disjoint_anchors();
8590
8591 let lines = if lines == 0 {
8592 EditorSettings::get_global(cx).expand_excerpt_lines
8593 } else {
8594 lines
8595 };
8596
8597 self.buffer.update(cx, |buffer, cx| {
8598 buffer.expand_excerpts(
8599 selections
8600 .into_iter()
8601 .map(|selection| selection.head().excerpt_id)
8602 .dedup(),
8603 lines,
8604 direction,
8605 cx,
8606 )
8607 })
8608 }
8609
8610 pub fn expand_excerpt(
8611 &mut self,
8612 excerpt: ExcerptId,
8613 direction: ExpandExcerptDirection,
8614 cx: &mut ViewContext<Self>,
8615 ) {
8616 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
8617 self.buffer.update(cx, |buffer, cx| {
8618 buffer.expand_excerpts([excerpt], lines, direction, cx)
8619 })
8620 }
8621
8622 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
8623 self.go_to_diagnostic_impl(Direction::Next, cx)
8624 }
8625
8626 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
8627 self.go_to_diagnostic_impl(Direction::Prev, cx)
8628 }
8629
8630 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
8631 let buffer = self.buffer.read(cx).snapshot(cx);
8632 let selection = self.selections.newest::<usize>(cx);
8633
8634 // If there is an active Diagnostic Popover jump to its diagnostic instead.
8635 if direction == Direction::Next {
8636 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
8637 let (group_id, jump_to) = popover.activation_info();
8638 if self.activate_diagnostics(group_id, cx) {
8639 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8640 let mut new_selection = s.newest_anchor().clone();
8641 new_selection.collapse_to(jump_to, SelectionGoal::None);
8642 s.select_anchors(vec![new_selection.clone()]);
8643 });
8644 }
8645 return;
8646 }
8647 }
8648
8649 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
8650 active_diagnostics
8651 .primary_range
8652 .to_offset(&buffer)
8653 .to_inclusive()
8654 });
8655 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
8656 if active_primary_range.contains(&selection.head()) {
8657 *active_primary_range.start()
8658 } else {
8659 selection.head()
8660 }
8661 } else {
8662 selection.head()
8663 };
8664 let snapshot = self.snapshot(cx);
8665 loop {
8666 let diagnostics = if direction == Direction::Prev {
8667 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
8668 } else {
8669 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
8670 }
8671 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
8672 let group = diagnostics
8673 // relies on diagnostics_in_range to return diagnostics with the same starting range to
8674 // be sorted in a stable way
8675 // skip until we are at current active diagnostic, if it exists
8676 .skip_while(|entry| {
8677 (match direction {
8678 Direction::Prev => entry.range.start >= search_start,
8679 Direction::Next => entry.range.start <= search_start,
8680 }) && self
8681 .active_diagnostics
8682 .as_ref()
8683 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
8684 })
8685 .find_map(|entry| {
8686 if entry.diagnostic.is_primary
8687 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
8688 && !entry.range.is_empty()
8689 // if we match with the active diagnostic, skip it
8690 && Some(entry.diagnostic.group_id)
8691 != self.active_diagnostics.as_ref().map(|d| d.group_id)
8692 {
8693 Some((entry.range, entry.diagnostic.group_id))
8694 } else {
8695 None
8696 }
8697 });
8698
8699 if let Some((primary_range, group_id)) = group {
8700 if self.activate_diagnostics(group_id, cx) {
8701 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8702 s.select(vec![Selection {
8703 id: selection.id,
8704 start: primary_range.start,
8705 end: primary_range.start,
8706 reversed: false,
8707 goal: SelectionGoal::None,
8708 }]);
8709 });
8710 }
8711 break;
8712 } else {
8713 // Cycle around to the start of the buffer, potentially moving back to the start of
8714 // the currently active diagnostic.
8715 active_primary_range.take();
8716 if direction == Direction::Prev {
8717 if search_start == buffer.len() {
8718 break;
8719 } else {
8720 search_start = buffer.len();
8721 }
8722 } else if search_start == 0 {
8723 break;
8724 } else {
8725 search_start = 0;
8726 }
8727 }
8728 }
8729 }
8730
8731 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
8732 let snapshot = self
8733 .display_map
8734 .update(cx, |display_map, cx| display_map.snapshot(cx));
8735 let selection = self.selections.newest::<Point>(cx);
8736
8737 if !self.seek_in_direction(
8738 &snapshot,
8739 selection.head(),
8740 false,
8741 snapshot.buffer_snapshot.git_diff_hunks_in_range(
8742 MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
8743 ),
8744 cx,
8745 ) {
8746 let wrapped_point = Point::zero();
8747 self.seek_in_direction(
8748 &snapshot,
8749 wrapped_point,
8750 true,
8751 snapshot.buffer_snapshot.git_diff_hunks_in_range(
8752 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
8753 ),
8754 cx,
8755 );
8756 }
8757 }
8758
8759 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
8760 let snapshot = self
8761 .display_map
8762 .update(cx, |display_map, cx| display_map.snapshot(cx));
8763 let selection = self.selections.newest::<Point>(cx);
8764
8765 if !self.seek_in_direction(
8766 &snapshot,
8767 selection.head(),
8768 false,
8769 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
8770 MultiBufferRow(0)..MultiBufferRow(selection.head().row),
8771 ),
8772 cx,
8773 ) {
8774 let wrapped_point = snapshot.buffer_snapshot.max_point();
8775 self.seek_in_direction(
8776 &snapshot,
8777 wrapped_point,
8778 true,
8779 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
8780 MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
8781 ),
8782 cx,
8783 );
8784 }
8785 }
8786
8787 fn seek_in_direction(
8788 &mut self,
8789 snapshot: &DisplaySnapshot,
8790 initial_point: Point,
8791 is_wrapped: bool,
8792 hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
8793 cx: &mut ViewContext<Editor>,
8794 ) -> bool {
8795 let display_point = initial_point.to_display_point(snapshot);
8796 let mut hunks = hunks
8797 .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
8798 .filter(|hunk| {
8799 if is_wrapped {
8800 true
8801 } else {
8802 !hunk.contains_display_row(display_point.row())
8803 }
8804 })
8805 .dedup();
8806
8807 if let Some(hunk) = hunks.next() {
8808 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8809 let row = hunk.start_display_row();
8810 let point = DisplayPoint::new(row, 0);
8811 s.select_display_ranges([point..point]);
8812 });
8813
8814 true
8815 } else {
8816 false
8817 }
8818 }
8819
8820 pub fn go_to_definition(
8821 &mut self,
8822 _: &GoToDefinition,
8823 cx: &mut ViewContext<Self>,
8824 ) -> Task<Result<bool>> {
8825 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx)
8826 }
8827
8828 pub fn go_to_implementation(
8829 &mut self,
8830 _: &GoToImplementation,
8831 cx: &mut ViewContext<Self>,
8832 ) -> Task<Result<bool>> {
8833 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
8834 }
8835
8836 pub fn go_to_implementation_split(
8837 &mut self,
8838 _: &GoToImplementationSplit,
8839 cx: &mut ViewContext<Self>,
8840 ) -> Task<Result<bool>> {
8841 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
8842 }
8843
8844 pub fn go_to_type_definition(
8845 &mut self,
8846 _: &GoToTypeDefinition,
8847 cx: &mut ViewContext<Self>,
8848 ) -> Task<Result<bool>> {
8849 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
8850 }
8851
8852 pub fn go_to_definition_split(
8853 &mut self,
8854 _: &GoToDefinitionSplit,
8855 cx: &mut ViewContext<Self>,
8856 ) -> Task<Result<bool>> {
8857 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
8858 }
8859
8860 pub fn go_to_type_definition_split(
8861 &mut self,
8862 _: &GoToTypeDefinitionSplit,
8863 cx: &mut ViewContext<Self>,
8864 ) -> Task<Result<bool>> {
8865 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
8866 }
8867
8868 fn go_to_definition_of_kind(
8869 &mut self,
8870 kind: GotoDefinitionKind,
8871 split: bool,
8872 cx: &mut ViewContext<Self>,
8873 ) -> Task<Result<bool>> {
8874 let Some(workspace) = self.workspace() else {
8875 return Task::ready(Ok(false));
8876 };
8877 let buffer = self.buffer.read(cx);
8878 let head = self.selections.newest::<usize>(cx).head();
8879 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
8880 text_anchor
8881 } else {
8882 return Task::ready(Ok(false));
8883 };
8884
8885 let project = workspace.read(cx).project().clone();
8886 let definitions = project.update(cx, |project, cx| match kind {
8887 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
8888 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
8889 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
8890 });
8891
8892 cx.spawn(|editor, mut cx| async move {
8893 let definitions = definitions.await?;
8894 let navigated = editor
8895 .update(&mut cx, |editor, cx| {
8896 editor.navigate_to_hover_links(
8897 Some(kind),
8898 definitions
8899 .into_iter()
8900 .filter(|location| {
8901 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
8902 })
8903 .map(HoverLink::Text)
8904 .collect::<Vec<_>>(),
8905 split,
8906 cx,
8907 )
8908 })?
8909 .await?;
8910 anyhow::Ok(navigated)
8911 })
8912 }
8913
8914 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
8915 let position = self.selections.newest_anchor().head();
8916 let Some((buffer, buffer_position)) =
8917 self.buffer.read(cx).text_anchor_for_position(position, cx)
8918 else {
8919 return;
8920 };
8921
8922 cx.spawn(|editor, mut cx| async move {
8923 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
8924 editor.update(&mut cx, |_, cx| {
8925 cx.open_url(&url);
8926 })
8927 } else {
8928 Ok(())
8929 }
8930 })
8931 .detach();
8932 }
8933
8934 pub(crate) fn navigate_to_hover_links(
8935 &mut self,
8936 kind: Option<GotoDefinitionKind>,
8937 mut definitions: Vec<HoverLink>,
8938 split: bool,
8939 cx: &mut ViewContext<Editor>,
8940 ) -> Task<Result<bool>> {
8941 // If there is one definition, just open it directly
8942 if definitions.len() == 1 {
8943 let definition = definitions.pop().unwrap();
8944 let target_task = match definition {
8945 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
8946 HoverLink::InlayHint(lsp_location, server_id) => {
8947 self.compute_target_location(lsp_location, server_id, cx)
8948 }
8949 HoverLink::Url(url) => {
8950 cx.open_url(&url);
8951 Task::ready(Ok(None))
8952 }
8953 };
8954 cx.spawn(|editor, mut cx| async move {
8955 let target = target_task.await.context("target resolution task")?;
8956 if let Some(target) = target {
8957 editor.update(&mut cx, |editor, cx| {
8958 let Some(workspace) = editor.workspace() else {
8959 return false;
8960 };
8961 let pane = workspace.read(cx).active_pane().clone();
8962
8963 let range = target.range.to_offset(target.buffer.read(cx));
8964 let range = editor.range_for_match(&range);
8965
8966 /// If select range has more than one line, we
8967 /// just point the cursor to range.start.
8968 fn check_multiline_range(
8969 buffer: &Buffer,
8970 range: Range<usize>,
8971 ) -> Range<usize> {
8972 if buffer.offset_to_point(range.start).row
8973 == buffer.offset_to_point(range.end).row
8974 {
8975 range
8976 } else {
8977 range.start..range.start
8978 }
8979 }
8980
8981 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
8982 let buffer = target.buffer.read(cx);
8983 let range = check_multiline_range(buffer, range);
8984 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
8985 s.select_ranges([range]);
8986 });
8987 } else {
8988 cx.window_context().defer(move |cx| {
8989 let target_editor: View<Self> =
8990 workspace.update(cx, |workspace, cx| {
8991 let pane = if split {
8992 workspace.adjacent_pane(cx)
8993 } else {
8994 workspace.active_pane().clone()
8995 };
8996
8997 workspace.open_project_item(pane, target.buffer.clone(), cx)
8998 });
8999 target_editor.update(cx, |target_editor, cx| {
9000 // When selecting a definition in a different buffer, disable the nav history
9001 // to avoid creating a history entry at the previous cursor location.
9002 pane.update(cx, |pane, _| pane.disable_history());
9003 let buffer = target.buffer.read(cx);
9004 let range = check_multiline_range(buffer, range);
9005 target_editor.change_selections(
9006 Some(Autoscroll::focused()),
9007 cx,
9008 |s| {
9009 s.select_ranges([range]);
9010 },
9011 );
9012 pane.update(cx, |pane, _| pane.enable_history());
9013 });
9014 });
9015 }
9016 true
9017 })
9018 } else {
9019 Ok(false)
9020 }
9021 })
9022 } else if !definitions.is_empty() {
9023 let replica_id = self.replica_id(cx);
9024 cx.spawn(|editor, mut cx| async move {
9025 let (title, location_tasks, workspace) = editor
9026 .update(&mut cx, |editor, cx| {
9027 let tab_kind = match kind {
9028 Some(GotoDefinitionKind::Implementation) => "Implementations",
9029 _ => "Definitions",
9030 };
9031 let title = definitions
9032 .iter()
9033 .find_map(|definition| match definition {
9034 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9035 let buffer = origin.buffer.read(cx);
9036 format!(
9037 "{} for {}",
9038 tab_kind,
9039 buffer
9040 .text_for_range(origin.range.clone())
9041 .collect::<String>()
9042 )
9043 }),
9044 HoverLink::InlayHint(_, _) => None,
9045 HoverLink::Url(_) => None,
9046 })
9047 .unwrap_or(tab_kind.to_string());
9048 let location_tasks = definitions
9049 .into_iter()
9050 .map(|definition| match definition {
9051 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9052 HoverLink::InlayHint(lsp_location, server_id) => {
9053 editor.compute_target_location(lsp_location, server_id, cx)
9054 }
9055 HoverLink::Url(_) => Task::ready(Ok(None)),
9056 })
9057 .collect::<Vec<_>>();
9058 (title, location_tasks, editor.workspace().clone())
9059 })
9060 .context("location tasks preparation")?;
9061
9062 let locations = futures::future::join_all(location_tasks)
9063 .await
9064 .into_iter()
9065 .filter_map(|location| location.transpose())
9066 .collect::<Result<_>>()
9067 .context("location tasks")?;
9068
9069 let Some(workspace) = workspace else {
9070 return Ok(false);
9071 };
9072 let opened = workspace
9073 .update(&mut cx, |workspace, cx| {
9074 Self::open_locations_in_multibuffer(
9075 workspace, locations, replica_id, title, split, cx,
9076 )
9077 })
9078 .ok();
9079
9080 anyhow::Ok(opened.is_some())
9081 })
9082 } else {
9083 Task::ready(Ok(false))
9084 }
9085 }
9086
9087 fn compute_target_location(
9088 &self,
9089 lsp_location: lsp::Location,
9090 server_id: LanguageServerId,
9091 cx: &mut ViewContext<Editor>,
9092 ) -> Task<anyhow::Result<Option<Location>>> {
9093 let Some(project) = self.project.clone() else {
9094 return Task::Ready(Some(Ok(None)));
9095 };
9096
9097 cx.spawn(move |editor, mut cx| async move {
9098 let location_task = editor.update(&mut cx, |editor, cx| {
9099 project.update(cx, |project, cx| {
9100 let language_server_name =
9101 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9102 project
9103 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9104 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9105 });
9106 language_server_name.map(|language_server_name| {
9107 project.open_local_buffer_via_lsp(
9108 lsp_location.uri.clone(),
9109 server_id,
9110 language_server_name,
9111 cx,
9112 )
9113 })
9114 })
9115 })?;
9116 let location = match location_task {
9117 Some(task) => Some({
9118 let target_buffer_handle = task.await.context("open local buffer")?;
9119 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9120 let target_start = target_buffer
9121 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9122 let target_end = target_buffer
9123 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9124 target_buffer.anchor_after(target_start)
9125 ..target_buffer.anchor_before(target_end)
9126 })?;
9127 Location {
9128 buffer: target_buffer_handle,
9129 range,
9130 }
9131 }),
9132 None => None,
9133 };
9134 Ok(location)
9135 })
9136 }
9137
9138 pub fn find_all_references(
9139 &mut self,
9140 _: &FindAllReferences,
9141 cx: &mut ViewContext<Self>,
9142 ) -> Option<Task<Result<()>>> {
9143 let multi_buffer = self.buffer.read(cx);
9144 let selection = self.selections.newest::<usize>(cx);
9145 let head = selection.head();
9146
9147 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9148 let head_anchor = multi_buffer_snapshot.anchor_at(
9149 head,
9150 if head < selection.tail() {
9151 Bias::Right
9152 } else {
9153 Bias::Left
9154 },
9155 );
9156
9157 match self
9158 .find_all_references_task_sources
9159 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9160 {
9161 Ok(_) => {
9162 log::info!(
9163 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9164 );
9165 return None;
9166 }
9167 Err(i) => {
9168 self.find_all_references_task_sources.insert(i, head_anchor);
9169 }
9170 }
9171
9172 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9173 let replica_id = self.replica_id(cx);
9174 let workspace = self.workspace()?;
9175 let project = workspace.read(cx).project().clone();
9176 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9177 Some(cx.spawn(|editor, mut cx| async move {
9178 let _cleanup = defer({
9179 let mut cx = cx.clone();
9180 move || {
9181 let _ = editor.update(&mut cx, |editor, _| {
9182 if let Ok(i) =
9183 editor
9184 .find_all_references_task_sources
9185 .binary_search_by(|anchor| {
9186 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9187 })
9188 {
9189 editor.find_all_references_task_sources.remove(i);
9190 }
9191 });
9192 }
9193 });
9194
9195 let locations = references.await?;
9196 if locations.is_empty() {
9197 return anyhow::Ok(());
9198 }
9199
9200 workspace.update(&mut cx, |workspace, cx| {
9201 let title = locations
9202 .first()
9203 .as_ref()
9204 .map(|location| {
9205 let buffer = location.buffer.read(cx);
9206 format!(
9207 "References to `{}`",
9208 buffer
9209 .text_for_range(location.range.clone())
9210 .collect::<String>()
9211 )
9212 })
9213 .unwrap();
9214 Self::open_locations_in_multibuffer(
9215 workspace, locations, replica_id, title, false, cx,
9216 );
9217 })
9218 }))
9219 }
9220
9221 /// Opens a multibuffer with the given project locations in it
9222 pub fn open_locations_in_multibuffer(
9223 workspace: &mut Workspace,
9224 mut locations: Vec<Location>,
9225 replica_id: ReplicaId,
9226 title: String,
9227 split: bool,
9228 cx: &mut ViewContext<Workspace>,
9229 ) {
9230 // If there are multiple definitions, open them in a multibuffer
9231 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9232 let mut locations = locations.into_iter().peekable();
9233 let mut ranges_to_highlight = Vec::new();
9234 let capability = workspace.project().read(cx).capability();
9235
9236 let excerpt_buffer = cx.new_model(|cx| {
9237 let mut multibuffer = MultiBuffer::new(replica_id, capability);
9238 while let Some(location) = locations.next() {
9239 let buffer = location.buffer.read(cx);
9240 let mut ranges_for_buffer = Vec::new();
9241 let range = location.range.to_offset(buffer);
9242 ranges_for_buffer.push(range.clone());
9243
9244 while let Some(next_location) = locations.peek() {
9245 if next_location.buffer == location.buffer {
9246 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9247 locations.next();
9248 } else {
9249 break;
9250 }
9251 }
9252
9253 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9254 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9255 location.buffer.clone(),
9256 ranges_for_buffer,
9257 DEFAULT_MULTIBUFFER_CONTEXT,
9258 cx,
9259 ))
9260 }
9261
9262 multibuffer.with_title(title)
9263 });
9264
9265 let editor = cx.new_view(|cx| {
9266 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9267 });
9268 editor.update(cx, |editor, cx| {
9269 if let Some(first_range) = ranges_to_highlight.first() {
9270 editor.change_selections(None, cx, |selections| {
9271 selections.clear_disjoint();
9272 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9273 });
9274 }
9275 editor.highlight_background::<Self>(
9276 &ranges_to_highlight,
9277 |theme| theme.editor_highlighted_line_background,
9278 cx,
9279 );
9280 });
9281
9282 let item = Box::new(editor);
9283 let item_id = item.item_id();
9284
9285 if split {
9286 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9287 } else {
9288 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9289 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9290 pane.close_current_preview_item(cx)
9291 } else {
9292 None
9293 }
9294 });
9295 workspace.add_item_to_active_pane(item.clone(), destination_index, cx);
9296 }
9297 workspace.active_pane().update(cx, |pane, cx| {
9298 pane.set_preview_item_id(Some(item_id), cx);
9299 });
9300 }
9301
9302 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9303 use language::ToOffset as _;
9304
9305 let project = self.project.clone()?;
9306 let selection = self.selections.newest_anchor().clone();
9307 let (cursor_buffer, cursor_buffer_position) = self
9308 .buffer
9309 .read(cx)
9310 .text_anchor_for_position(selection.head(), cx)?;
9311 let (tail_buffer, cursor_buffer_position_end) = self
9312 .buffer
9313 .read(cx)
9314 .text_anchor_for_position(selection.tail(), cx)?;
9315 if tail_buffer != cursor_buffer {
9316 return None;
9317 }
9318
9319 let snapshot = cursor_buffer.read(cx).snapshot();
9320 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9321 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9322 let prepare_rename = project.update(cx, |project, cx| {
9323 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
9324 });
9325 drop(snapshot);
9326
9327 Some(cx.spawn(|this, mut cx| async move {
9328 let rename_range = if let Some(range) = prepare_rename.await? {
9329 Some(range)
9330 } else {
9331 this.update(&mut cx, |this, cx| {
9332 let buffer = this.buffer.read(cx).snapshot(cx);
9333 let mut buffer_highlights = this
9334 .document_highlights_for_position(selection.head(), &buffer)
9335 .filter(|highlight| {
9336 highlight.start.excerpt_id == selection.head().excerpt_id
9337 && highlight.end.excerpt_id == selection.head().excerpt_id
9338 });
9339 buffer_highlights
9340 .next()
9341 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9342 })?
9343 };
9344 if let Some(rename_range) = rename_range {
9345 this.update(&mut cx, |this, cx| {
9346 let snapshot = cursor_buffer.read(cx).snapshot();
9347 let rename_buffer_range = rename_range.to_offset(&snapshot);
9348 let cursor_offset_in_rename_range =
9349 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9350 let cursor_offset_in_rename_range_end =
9351 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9352
9353 this.take_rename(false, cx);
9354 let buffer = this.buffer.read(cx).read(cx);
9355 let cursor_offset = selection.head().to_offset(&buffer);
9356 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9357 let rename_end = rename_start + rename_buffer_range.len();
9358 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9359 let mut old_highlight_id = None;
9360 let old_name: Arc<str> = buffer
9361 .chunks(rename_start..rename_end, true)
9362 .map(|chunk| {
9363 if old_highlight_id.is_none() {
9364 old_highlight_id = chunk.syntax_highlight_id;
9365 }
9366 chunk.text
9367 })
9368 .collect::<String>()
9369 .into();
9370
9371 drop(buffer);
9372
9373 // Position the selection in the rename editor so that it matches the current selection.
9374 this.show_local_selections = false;
9375 let rename_editor = cx.new_view(|cx| {
9376 let mut editor = Editor::single_line(cx);
9377 editor.buffer.update(cx, |buffer, cx| {
9378 buffer.edit([(0..0, old_name.clone())], None, cx)
9379 });
9380 let rename_selection_range = match cursor_offset_in_rename_range
9381 .cmp(&cursor_offset_in_rename_range_end)
9382 {
9383 Ordering::Equal => {
9384 editor.select_all(&SelectAll, cx);
9385 return editor;
9386 }
9387 Ordering::Less => {
9388 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9389 }
9390 Ordering::Greater => {
9391 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9392 }
9393 };
9394 if rename_selection_range.end > old_name.len() {
9395 editor.select_all(&SelectAll, cx);
9396 } else {
9397 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9398 s.select_ranges([rename_selection_range]);
9399 });
9400 }
9401 editor
9402 });
9403
9404 let write_highlights =
9405 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
9406 let read_highlights =
9407 this.clear_background_highlights::<DocumentHighlightRead>(cx);
9408 let ranges = write_highlights
9409 .iter()
9410 .flat_map(|(_, ranges)| ranges.iter())
9411 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
9412 .cloned()
9413 .collect();
9414
9415 this.highlight_text::<Rename>(
9416 ranges,
9417 HighlightStyle {
9418 fade_out: Some(0.6),
9419 ..Default::default()
9420 },
9421 cx,
9422 );
9423 let rename_focus_handle = rename_editor.focus_handle(cx);
9424 cx.focus(&rename_focus_handle);
9425 let block_id = this.insert_blocks(
9426 [BlockProperties {
9427 style: BlockStyle::Flex,
9428 position: range.start,
9429 height: 1,
9430 render: Box::new({
9431 let rename_editor = rename_editor.clone();
9432 move |cx: &mut BlockContext| {
9433 let mut text_style = cx.editor_style.text.clone();
9434 if let Some(highlight_style) = old_highlight_id
9435 .and_then(|h| h.style(&cx.editor_style.syntax))
9436 {
9437 text_style = text_style.highlight(highlight_style);
9438 }
9439 div()
9440 .pl(cx.anchor_x)
9441 .child(EditorElement::new(
9442 &rename_editor,
9443 EditorStyle {
9444 background: cx.theme().system().transparent,
9445 local_player: cx.editor_style.local_player,
9446 text: text_style,
9447 scrollbar_width: cx.editor_style.scrollbar_width,
9448 syntax: cx.editor_style.syntax.clone(),
9449 status: cx.editor_style.status.clone(),
9450 inlay_hints_style: HighlightStyle {
9451 color: Some(cx.theme().status().hint),
9452 font_weight: Some(FontWeight::BOLD),
9453 ..HighlightStyle::default()
9454 },
9455 suggestions_style: HighlightStyle {
9456 color: Some(cx.theme().status().predictive),
9457 ..HighlightStyle::default()
9458 },
9459 },
9460 ))
9461 .into_any_element()
9462 }
9463 }),
9464 disposition: BlockDisposition::Below,
9465 }],
9466 Some(Autoscroll::fit()),
9467 cx,
9468 )[0];
9469 this.pending_rename = Some(RenameState {
9470 range,
9471 old_name,
9472 editor: rename_editor,
9473 block_id,
9474 });
9475 })?;
9476 }
9477
9478 Ok(())
9479 }))
9480 }
9481
9482 pub fn confirm_rename(
9483 &mut self,
9484 _: &ConfirmRename,
9485 cx: &mut ViewContext<Self>,
9486 ) -> Option<Task<Result<()>>> {
9487 let rename = self.take_rename(false, cx)?;
9488 let workspace = self.workspace()?;
9489 let (start_buffer, start) = self
9490 .buffer
9491 .read(cx)
9492 .text_anchor_for_position(rename.range.start, cx)?;
9493 let (end_buffer, end) = self
9494 .buffer
9495 .read(cx)
9496 .text_anchor_for_position(rename.range.end, cx)?;
9497 if start_buffer != end_buffer {
9498 return None;
9499 }
9500
9501 let buffer = start_buffer;
9502 let range = start..end;
9503 let old_name = rename.old_name;
9504 let new_name = rename.editor.read(cx).text(cx);
9505
9506 let rename = workspace
9507 .read(cx)
9508 .project()
9509 .clone()
9510 .update(cx, |project, cx| {
9511 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
9512 });
9513 let workspace = workspace.downgrade();
9514
9515 Some(cx.spawn(|editor, mut cx| async move {
9516 let project_transaction = rename.await?;
9517 Self::open_project_transaction(
9518 &editor,
9519 workspace,
9520 project_transaction,
9521 format!("Rename: {} → {}", old_name, new_name),
9522 cx.clone(),
9523 )
9524 .await?;
9525
9526 editor.update(&mut cx, |editor, cx| {
9527 editor.refresh_document_highlights(cx);
9528 })?;
9529 Ok(())
9530 }))
9531 }
9532
9533 fn take_rename(
9534 &mut self,
9535 moving_cursor: bool,
9536 cx: &mut ViewContext<Self>,
9537 ) -> Option<RenameState> {
9538 let rename = self.pending_rename.take()?;
9539 if rename.editor.focus_handle(cx).is_focused(cx) {
9540 cx.focus(&self.focus_handle);
9541 }
9542
9543 self.remove_blocks(
9544 [rename.block_id].into_iter().collect(),
9545 Some(Autoscroll::fit()),
9546 cx,
9547 );
9548 self.clear_highlights::<Rename>(cx);
9549 self.show_local_selections = true;
9550
9551 if moving_cursor {
9552 let rename_editor = rename.editor.read(cx);
9553 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
9554
9555 // Update the selection to match the position of the selection inside
9556 // the rename editor.
9557 let snapshot = self.buffer.read(cx).read(cx);
9558 let rename_range = rename.range.to_offset(&snapshot);
9559 let cursor_in_editor = snapshot
9560 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
9561 .min(rename_range.end);
9562 drop(snapshot);
9563
9564 self.change_selections(None, cx, |s| {
9565 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
9566 });
9567 } else {
9568 self.refresh_document_highlights(cx);
9569 }
9570
9571 Some(rename)
9572 }
9573
9574 pub fn pending_rename(&self) -> Option<&RenameState> {
9575 self.pending_rename.as_ref()
9576 }
9577
9578 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9579 let project = match &self.project {
9580 Some(project) => project.clone(),
9581 None => return None,
9582 };
9583
9584 Some(self.perform_format(project, FormatTrigger::Manual, cx))
9585 }
9586
9587 fn perform_format(
9588 &mut self,
9589 project: Model<Project>,
9590 trigger: FormatTrigger,
9591 cx: &mut ViewContext<Self>,
9592 ) -> Task<Result<()>> {
9593 let buffer = self.buffer().clone();
9594 let mut buffers = buffer.read(cx).all_buffers();
9595 if trigger == FormatTrigger::Save {
9596 buffers.retain(|buffer| buffer.read(cx).is_dirty());
9597 }
9598
9599 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
9600 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
9601
9602 cx.spawn(|_, mut cx| async move {
9603 let transaction = futures::select_biased! {
9604 () = timeout => {
9605 log::warn!("timed out waiting for formatting");
9606 None
9607 }
9608 transaction = format.log_err().fuse() => transaction,
9609 };
9610
9611 buffer
9612 .update(&mut cx, |buffer, cx| {
9613 if let Some(transaction) = transaction {
9614 if !buffer.is_singleton() {
9615 buffer.push_transaction(&transaction.0, cx);
9616 }
9617 }
9618
9619 cx.notify();
9620 })
9621 .ok();
9622
9623 Ok(())
9624 })
9625 }
9626
9627 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
9628 if let Some(project) = self.project.clone() {
9629 self.buffer.update(cx, |multi_buffer, cx| {
9630 project.update(cx, |project, cx| {
9631 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
9632 });
9633 })
9634 }
9635 }
9636
9637 fn cancel_language_server_work(
9638 &mut self,
9639 _: &CancelLanguageServerWork,
9640 cx: &mut ViewContext<Self>,
9641 ) {
9642 if let Some(project) = self.project.clone() {
9643 self.buffer.update(cx, |multi_buffer, cx| {
9644 project.update(cx, |project, cx| {
9645 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
9646 });
9647 })
9648 }
9649 }
9650
9651 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
9652 cx.show_character_palette();
9653 }
9654
9655 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
9656 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
9657 let buffer = self.buffer.read(cx).snapshot(cx);
9658 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
9659 let is_valid = buffer
9660 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
9661 .any(|entry| {
9662 entry.diagnostic.is_primary
9663 && !entry.range.is_empty()
9664 && entry.range.start == primary_range_start
9665 && entry.diagnostic.message == active_diagnostics.primary_message
9666 });
9667
9668 if is_valid != active_diagnostics.is_valid {
9669 active_diagnostics.is_valid = is_valid;
9670 let mut new_styles = HashMap::default();
9671 for (block_id, diagnostic) in &active_diagnostics.blocks {
9672 new_styles.insert(
9673 *block_id,
9674 (
9675 None,
9676 diagnostic_block_renderer(diagnostic.clone(), is_valid),
9677 ),
9678 );
9679 }
9680 self.display_map.update(cx, |display_map, cx| {
9681 display_map.replace_blocks(new_styles, cx)
9682 });
9683 }
9684 }
9685 }
9686
9687 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
9688 self.dismiss_diagnostics(cx);
9689 let snapshot = self.snapshot(cx);
9690 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
9691 let buffer = self.buffer.read(cx).snapshot(cx);
9692
9693 let mut primary_range = None;
9694 let mut primary_message = None;
9695 let mut group_end = Point::zero();
9696 let diagnostic_group = buffer
9697 .diagnostic_group::<MultiBufferPoint>(group_id)
9698 .filter_map(|entry| {
9699 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
9700 && (entry.range.start.row == entry.range.end.row
9701 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
9702 {
9703 return None;
9704 }
9705 if entry.range.end > group_end {
9706 group_end = entry.range.end;
9707 }
9708 if entry.diagnostic.is_primary {
9709 primary_range = Some(entry.range.clone());
9710 primary_message = Some(entry.diagnostic.message.clone());
9711 }
9712 Some(entry)
9713 })
9714 .collect::<Vec<_>>();
9715 let primary_range = primary_range?;
9716 let primary_message = primary_message?;
9717 let primary_range =
9718 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
9719
9720 let blocks = display_map
9721 .insert_blocks(
9722 diagnostic_group.iter().map(|entry| {
9723 let diagnostic = entry.diagnostic.clone();
9724 let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
9725 BlockProperties {
9726 style: BlockStyle::Fixed,
9727 position: buffer.anchor_after(entry.range.start),
9728 height: message_height,
9729 render: diagnostic_block_renderer(diagnostic, true),
9730 disposition: BlockDisposition::Below,
9731 }
9732 }),
9733 cx,
9734 )
9735 .into_iter()
9736 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
9737 .collect();
9738
9739 Some(ActiveDiagnosticGroup {
9740 primary_range,
9741 primary_message,
9742 group_id,
9743 blocks,
9744 is_valid: true,
9745 })
9746 });
9747 self.active_diagnostics.is_some()
9748 }
9749
9750 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
9751 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
9752 self.display_map.update(cx, |display_map, cx| {
9753 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
9754 });
9755 cx.notify();
9756 }
9757 }
9758
9759 pub fn set_selections_from_remote(
9760 &mut self,
9761 selections: Vec<Selection<Anchor>>,
9762 pending_selection: Option<Selection<Anchor>>,
9763 cx: &mut ViewContext<Self>,
9764 ) {
9765 let old_cursor_position = self.selections.newest_anchor().head();
9766 self.selections.change_with(cx, |s| {
9767 s.select_anchors(selections);
9768 if let Some(pending_selection) = pending_selection {
9769 s.set_pending(pending_selection, SelectMode::Character);
9770 } else {
9771 s.clear_pending();
9772 }
9773 });
9774 self.selections_did_change(false, &old_cursor_position, true, cx);
9775 }
9776
9777 fn push_to_selection_history(&mut self) {
9778 self.selection_history.push(SelectionHistoryEntry {
9779 selections: self.selections.disjoint_anchors(),
9780 select_next_state: self.select_next_state.clone(),
9781 select_prev_state: self.select_prev_state.clone(),
9782 add_selections_state: self.add_selections_state.clone(),
9783 });
9784 }
9785
9786 pub fn transact(
9787 &mut self,
9788 cx: &mut ViewContext<Self>,
9789 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
9790 ) -> Option<TransactionId> {
9791 self.start_transaction_at(Instant::now(), cx);
9792 update(self, cx);
9793 self.end_transaction_at(Instant::now(), cx)
9794 }
9795
9796 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
9797 self.end_selection(cx);
9798 if let Some(tx_id) = self
9799 .buffer
9800 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
9801 {
9802 self.selection_history
9803 .insert_transaction(tx_id, self.selections.disjoint_anchors());
9804 cx.emit(EditorEvent::TransactionBegun {
9805 transaction_id: tx_id,
9806 })
9807 }
9808 }
9809
9810 fn end_transaction_at(
9811 &mut self,
9812 now: Instant,
9813 cx: &mut ViewContext<Self>,
9814 ) -> Option<TransactionId> {
9815 if let Some(transaction_id) = self
9816 .buffer
9817 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
9818 {
9819 if let Some((_, end_selections)) =
9820 self.selection_history.transaction_mut(transaction_id)
9821 {
9822 *end_selections = Some(self.selections.disjoint_anchors());
9823 } else {
9824 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
9825 }
9826
9827 cx.emit(EditorEvent::Edited { transaction_id });
9828 Some(transaction_id)
9829 } else {
9830 None
9831 }
9832 }
9833
9834 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
9835 let mut fold_ranges = Vec::new();
9836
9837 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9838
9839 let selections = self.selections.all_adjusted(cx);
9840 for selection in selections {
9841 let range = selection.range().sorted();
9842 let buffer_start_row = range.start.row;
9843
9844 for row in (0..=range.end.row).rev() {
9845 if let Some((foldable_range, fold_text)) =
9846 display_map.foldable_range(MultiBufferRow(row))
9847 {
9848 if foldable_range.end.row >= buffer_start_row {
9849 fold_ranges.push((foldable_range, fold_text));
9850 if row <= range.start.row {
9851 break;
9852 }
9853 }
9854 }
9855 }
9856 }
9857
9858 self.fold_ranges(fold_ranges, true, cx);
9859 }
9860
9861 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
9862 let buffer_row = fold_at.buffer_row;
9863 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9864
9865 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
9866 let autoscroll = self
9867 .selections
9868 .all::<Point>(cx)
9869 .iter()
9870 .any(|selection| fold_range.overlaps(&selection.range()));
9871
9872 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
9873 }
9874 }
9875
9876 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
9877 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9878 let buffer = &display_map.buffer_snapshot;
9879 let selections = self.selections.all::<Point>(cx);
9880 let ranges = selections
9881 .iter()
9882 .map(|s| {
9883 let range = s.display_range(&display_map).sorted();
9884 let mut start = range.start.to_point(&display_map);
9885 let mut end = range.end.to_point(&display_map);
9886 start.column = 0;
9887 end.column = buffer.line_len(MultiBufferRow(end.row));
9888 start..end
9889 })
9890 .collect::<Vec<_>>();
9891
9892 self.unfold_ranges(ranges, true, true, cx);
9893 }
9894
9895 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
9896 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9897
9898 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
9899 ..Point::new(
9900 unfold_at.buffer_row.0,
9901 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
9902 );
9903
9904 let autoscroll = self
9905 .selections
9906 .all::<Point>(cx)
9907 .iter()
9908 .any(|selection| selection.range().overlaps(&intersection_range));
9909
9910 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
9911 }
9912
9913 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
9914 let selections = self.selections.all::<Point>(cx);
9915 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9916 let line_mode = self.selections.line_mode;
9917 let ranges = selections.into_iter().map(|s| {
9918 if line_mode {
9919 let start = Point::new(s.start.row, 0);
9920 let end = Point::new(
9921 s.end.row,
9922 display_map
9923 .buffer_snapshot
9924 .line_len(MultiBufferRow(s.end.row)),
9925 );
9926 (start..end, display_map.fold_placeholder.clone())
9927 } else {
9928 (s.start..s.end, display_map.fold_placeholder.clone())
9929 }
9930 });
9931 self.fold_ranges(ranges, true, cx);
9932 }
9933
9934 pub fn fold_ranges<T: ToOffset + Clone>(
9935 &mut self,
9936 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
9937 auto_scroll: bool,
9938 cx: &mut ViewContext<Self>,
9939 ) {
9940 let mut fold_ranges = Vec::new();
9941 let mut buffers_affected = HashMap::default();
9942 let multi_buffer = self.buffer().read(cx);
9943 for (fold_range, fold_text) in ranges {
9944 if let Some((_, buffer, _)) =
9945 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
9946 {
9947 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
9948 };
9949 fold_ranges.push((fold_range, fold_text));
9950 }
9951
9952 let mut ranges = fold_ranges.into_iter().peekable();
9953 if ranges.peek().is_some() {
9954 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
9955
9956 if auto_scroll {
9957 self.request_autoscroll(Autoscroll::fit(), cx);
9958 }
9959
9960 for buffer in buffers_affected.into_values() {
9961 self.sync_expanded_diff_hunks(buffer, cx);
9962 }
9963
9964 cx.notify();
9965
9966 if let Some(active_diagnostics) = self.active_diagnostics.take() {
9967 // Clear diagnostics block when folding a range that contains it.
9968 let snapshot = self.snapshot(cx);
9969 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
9970 drop(snapshot);
9971 self.active_diagnostics = Some(active_diagnostics);
9972 self.dismiss_diagnostics(cx);
9973 } else {
9974 self.active_diagnostics = Some(active_diagnostics);
9975 }
9976 }
9977
9978 self.scrollbar_marker_state.dirty = true;
9979 }
9980 }
9981
9982 pub fn unfold_ranges<T: ToOffset + Clone>(
9983 &mut self,
9984 ranges: impl IntoIterator<Item = Range<T>>,
9985 inclusive: bool,
9986 auto_scroll: bool,
9987 cx: &mut ViewContext<Self>,
9988 ) {
9989 let mut unfold_ranges = Vec::new();
9990 let mut buffers_affected = HashMap::default();
9991 let multi_buffer = self.buffer().read(cx);
9992 for range in ranges {
9993 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
9994 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
9995 };
9996 unfold_ranges.push(range);
9997 }
9998
9999 let mut ranges = unfold_ranges.into_iter().peekable();
10000 if ranges.peek().is_some() {
10001 self.display_map
10002 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10003 if auto_scroll {
10004 self.request_autoscroll(Autoscroll::fit(), cx);
10005 }
10006
10007 for buffer in buffers_affected.into_values() {
10008 self.sync_expanded_diff_hunks(buffer, cx);
10009 }
10010
10011 cx.notify();
10012 self.scrollbar_marker_state.dirty = true;
10013 self.active_indent_guides_state.dirty = true;
10014 }
10015 }
10016
10017 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10018 if hovered != self.gutter_hovered {
10019 self.gutter_hovered = hovered;
10020 cx.notify();
10021 }
10022 }
10023
10024 pub fn insert_blocks(
10025 &mut self,
10026 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10027 autoscroll: Option<Autoscroll>,
10028 cx: &mut ViewContext<Self>,
10029 ) -> Vec<BlockId> {
10030 let blocks = self
10031 .display_map
10032 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10033 if let Some(autoscroll) = autoscroll {
10034 self.request_autoscroll(autoscroll, cx);
10035 }
10036 blocks
10037 }
10038
10039 pub fn replace_blocks(
10040 &mut self,
10041 blocks: HashMap<BlockId, (Option<u8>, RenderBlock)>,
10042 autoscroll: Option<Autoscroll>,
10043 cx: &mut ViewContext<Self>,
10044 ) {
10045 self.display_map
10046 .update(cx, |display_map, cx| display_map.replace_blocks(blocks, cx));
10047 if let Some(autoscroll) = autoscroll {
10048 self.request_autoscroll(autoscroll, cx);
10049 }
10050 }
10051
10052 pub fn remove_blocks(
10053 &mut self,
10054 block_ids: HashSet<BlockId>,
10055 autoscroll: Option<Autoscroll>,
10056 cx: &mut ViewContext<Self>,
10057 ) {
10058 self.display_map.update(cx, |display_map, cx| {
10059 display_map.remove_blocks(block_ids, cx)
10060 });
10061 if let Some(autoscroll) = autoscroll {
10062 self.request_autoscroll(autoscroll, cx);
10063 }
10064 }
10065
10066 pub fn row_for_block(
10067 &self,
10068 block_id: BlockId,
10069 cx: &mut ViewContext<Self>,
10070 ) -> Option<DisplayRow> {
10071 self.display_map
10072 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10073 }
10074
10075 pub fn insert_creases(
10076 &mut self,
10077 creases: impl IntoIterator<Item = Crease>,
10078 cx: &mut ViewContext<Self>,
10079 ) -> Vec<CreaseId> {
10080 self.display_map
10081 .update(cx, |map, cx| map.insert_creases(creases, cx))
10082 }
10083
10084 pub fn remove_creases(
10085 &mut self,
10086 ids: impl IntoIterator<Item = CreaseId>,
10087 cx: &mut ViewContext<Self>,
10088 ) {
10089 self.display_map
10090 .update(cx, |map, cx| map.remove_creases(ids, cx));
10091 }
10092
10093 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10094 self.display_map
10095 .update(cx, |map, cx| map.snapshot(cx))
10096 .longest_row()
10097 }
10098
10099 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10100 self.display_map
10101 .update(cx, |map, cx| map.snapshot(cx))
10102 .max_point()
10103 }
10104
10105 pub fn text(&self, cx: &AppContext) -> String {
10106 self.buffer.read(cx).read(cx).text()
10107 }
10108
10109 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10110 let text = self.text(cx);
10111 let text = text.trim();
10112
10113 if text.is_empty() {
10114 return None;
10115 }
10116
10117 Some(text.to_string())
10118 }
10119
10120 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10121 self.transact(cx, |this, cx| {
10122 this.buffer
10123 .read(cx)
10124 .as_singleton()
10125 .expect("you can only call set_text on editors for singleton buffers")
10126 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10127 });
10128 }
10129
10130 pub fn display_text(&self, cx: &mut AppContext) -> String {
10131 self.display_map
10132 .update(cx, |map, cx| map.snapshot(cx))
10133 .text()
10134 }
10135
10136 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10137 let mut wrap_guides = smallvec::smallvec![];
10138
10139 if self.show_wrap_guides == Some(false) {
10140 return wrap_guides;
10141 }
10142
10143 let settings = self.buffer.read(cx).settings_at(0, cx);
10144 if settings.show_wrap_guides {
10145 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10146 wrap_guides.push((soft_wrap as usize, true));
10147 }
10148 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10149 }
10150
10151 wrap_guides
10152 }
10153
10154 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10155 let settings = self.buffer.read(cx).settings_at(0, cx);
10156 let mode = self
10157 .soft_wrap_mode_override
10158 .unwrap_or_else(|| settings.soft_wrap);
10159 match mode {
10160 language_settings::SoftWrap::None => SoftWrap::None,
10161 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10162 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10163 language_settings::SoftWrap::PreferredLineLength => {
10164 SoftWrap::Column(settings.preferred_line_length)
10165 }
10166 }
10167 }
10168
10169 pub fn set_soft_wrap_mode(
10170 &mut self,
10171 mode: language_settings::SoftWrap,
10172 cx: &mut ViewContext<Self>,
10173 ) {
10174 self.soft_wrap_mode_override = Some(mode);
10175 cx.notify();
10176 }
10177
10178 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10179 let rem_size = cx.rem_size();
10180 self.display_map.update(cx, |map, cx| {
10181 map.set_font(
10182 style.text.font(),
10183 style.text.font_size.to_pixels(rem_size),
10184 cx,
10185 )
10186 });
10187 self.style = Some(style);
10188 }
10189
10190 pub fn style(&self) -> Option<&EditorStyle> {
10191 self.style.as_ref()
10192 }
10193
10194 // Called by the element. This method is not designed to be called outside of the editor
10195 // element's layout code because it does not notify when rewrapping is computed synchronously.
10196 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10197 self.display_map
10198 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10199 }
10200
10201 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10202 if self.soft_wrap_mode_override.is_some() {
10203 self.soft_wrap_mode_override.take();
10204 } else {
10205 let soft_wrap = match self.soft_wrap_mode(cx) {
10206 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10207 SoftWrap::EditorWidth | SoftWrap::Column(_) => {
10208 language_settings::SoftWrap::PreferLine
10209 }
10210 };
10211 self.soft_wrap_mode_override = Some(soft_wrap);
10212 }
10213 cx.notify();
10214 }
10215
10216 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10217 let Some(workspace) = self.workspace() else {
10218 return;
10219 };
10220 let fs = workspace.read(cx).app_state().fs.clone();
10221 let current_show = TabBarSettings::get_global(cx).show;
10222 update_settings_file::<TabBarSettings>(fs, cx, move |setting| {
10223 setting.show = Some(!current_show);
10224 });
10225 }
10226
10227 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10228 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10229 self.buffer
10230 .read(cx)
10231 .settings_at(0, cx)
10232 .indent_guides
10233 .enabled
10234 });
10235 self.show_indent_guides = Some(!currently_enabled);
10236 cx.notify();
10237 }
10238
10239 fn should_show_indent_guides(&self) -> Option<bool> {
10240 self.show_indent_guides
10241 }
10242
10243 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10244 let mut editor_settings = EditorSettings::get_global(cx).clone();
10245 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10246 EditorSettings::override_global(editor_settings, cx);
10247 }
10248
10249 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10250 self.show_gutter = show_gutter;
10251 cx.notify();
10252 }
10253
10254 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10255 self.show_line_numbers = Some(show_line_numbers);
10256 cx.notify();
10257 }
10258
10259 pub fn set_show_git_diff_gutter(
10260 &mut self,
10261 show_git_diff_gutter: bool,
10262 cx: &mut ViewContext<Self>,
10263 ) {
10264 self.show_git_diff_gutter = Some(show_git_diff_gutter);
10265 cx.notify();
10266 }
10267
10268 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10269 self.show_code_actions = Some(show_code_actions);
10270 cx.notify();
10271 }
10272
10273 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10274 self.show_runnables = Some(show_runnables);
10275 cx.notify();
10276 }
10277
10278 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10279 self.show_wrap_guides = Some(show_wrap_guides);
10280 cx.notify();
10281 }
10282
10283 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10284 self.show_indent_guides = Some(show_indent_guides);
10285 cx.notify();
10286 }
10287
10288 pub fn reveal_in_finder(&mut self, _: &RevealInFinder, cx: &mut ViewContext<Self>) {
10289 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10290 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10291 cx.reveal_path(&file.abs_path(cx));
10292 }
10293 }
10294 }
10295
10296 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10297 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10298 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10299 if let Some(path) = file.abs_path(cx).to_str() {
10300 cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10301 }
10302 }
10303 }
10304 }
10305
10306 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10307 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10308 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10309 if let Some(path) = file.path().to_str() {
10310 cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10311 }
10312 }
10313 }
10314 }
10315
10316 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10317 self.show_git_blame_gutter = !self.show_git_blame_gutter;
10318
10319 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10320 self.start_git_blame(true, cx);
10321 }
10322
10323 cx.notify();
10324 }
10325
10326 pub fn toggle_git_blame_inline(
10327 &mut self,
10328 _: &ToggleGitBlameInline,
10329 cx: &mut ViewContext<Self>,
10330 ) {
10331 self.toggle_git_blame_inline_internal(true, cx);
10332 cx.notify();
10333 }
10334
10335 pub fn git_blame_inline_enabled(&self) -> bool {
10336 self.git_blame_inline_enabled
10337 }
10338
10339 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10340 self.show_selection_menu = self
10341 .show_selection_menu
10342 .map(|show_selections_menu| !show_selections_menu)
10343 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10344
10345 cx.notify();
10346 }
10347
10348 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10349 self.show_selection_menu
10350 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10351 }
10352
10353 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10354 if let Some(project) = self.project.as_ref() {
10355 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10356 return;
10357 };
10358
10359 if buffer.read(cx).file().is_none() {
10360 return;
10361 }
10362
10363 let focused = self.focus_handle(cx).contains_focused(cx);
10364
10365 let project = project.clone();
10366 let blame =
10367 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10368 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10369 self.blame = Some(blame);
10370 }
10371 }
10372
10373 fn toggle_git_blame_inline_internal(
10374 &mut self,
10375 user_triggered: bool,
10376 cx: &mut ViewContext<Self>,
10377 ) {
10378 if self.git_blame_inline_enabled {
10379 self.git_blame_inline_enabled = false;
10380 self.show_git_blame_inline = false;
10381 self.show_git_blame_inline_delay_task.take();
10382 } else {
10383 self.git_blame_inline_enabled = true;
10384 self.start_git_blame_inline(user_triggered, cx);
10385 }
10386
10387 cx.notify();
10388 }
10389
10390 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10391 self.start_git_blame(user_triggered, cx);
10392
10393 if ProjectSettings::get_global(cx)
10394 .git
10395 .inline_blame_delay()
10396 .is_some()
10397 {
10398 self.start_inline_blame_timer(cx);
10399 } else {
10400 self.show_git_blame_inline = true
10401 }
10402 }
10403
10404 pub fn blame(&self) -> Option<&Model<GitBlame>> {
10405 self.blame.as_ref()
10406 }
10407
10408 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10409 self.show_git_blame_gutter && self.has_blame_entries(cx)
10410 }
10411
10412 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10413 self.show_git_blame_inline
10414 && self.focus_handle.is_focused(cx)
10415 && !self.newest_selection_head_on_empty_line(cx)
10416 && self.has_blame_entries(cx)
10417 }
10418
10419 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10420 self.blame()
10421 .map_or(false, |blame| blame.read(cx).has_generated_entries())
10422 }
10423
10424 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10425 let cursor_anchor = self.selections.newest_anchor().head();
10426
10427 let snapshot = self.buffer.read(cx).snapshot(cx);
10428 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10429
10430 snapshot.line_len(buffer_row) == 0
10431 }
10432
10433 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10434 let (path, selection, repo) = maybe!({
10435 let project_handle = self.project.as_ref()?.clone();
10436 let project = project_handle.read(cx);
10437
10438 let selection = self.selections.newest::<Point>(cx);
10439 let selection_range = selection.range();
10440
10441 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10442 (buffer, selection_range.start.row..selection_range.end.row)
10443 } else {
10444 let buffer_ranges = self
10445 .buffer()
10446 .read(cx)
10447 .range_to_buffer_ranges(selection_range, cx);
10448
10449 let (buffer, range, _) = if selection.reversed {
10450 buffer_ranges.first()
10451 } else {
10452 buffer_ranges.last()
10453 }?;
10454
10455 let snapshot = buffer.read(cx).snapshot();
10456 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10457 ..text::ToPoint::to_point(&range.end, &snapshot).row;
10458 (buffer.clone(), selection)
10459 };
10460
10461 let path = buffer
10462 .read(cx)
10463 .file()?
10464 .as_local()?
10465 .path()
10466 .to_str()?
10467 .to_string();
10468 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10469 Some((path, selection, repo))
10470 })
10471 .ok_or_else(|| anyhow!("unable to open git repository"))?;
10472
10473 const REMOTE_NAME: &str = "origin";
10474 let origin_url = repo
10475 .remote_url(REMOTE_NAME)
10476 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10477 let sha = repo
10478 .head_sha()
10479 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10480
10481 let (provider, remote) =
10482 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10483 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10484
10485 Ok(provider.build_permalink(
10486 remote,
10487 BuildPermalinkParams {
10488 sha: &sha,
10489 path: &path,
10490 selection: Some(selection),
10491 },
10492 ))
10493 }
10494
10495 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10496 let permalink = self.get_permalink_to_line(cx);
10497
10498 match permalink {
10499 Ok(permalink) => {
10500 cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
10501 }
10502 Err(err) => {
10503 let message = format!("Failed to copy permalink: {err}");
10504
10505 Err::<(), anyhow::Error>(err).log_err();
10506
10507 if let Some(workspace) = self.workspace() {
10508 workspace.update(cx, |workspace, cx| {
10509 struct CopyPermalinkToLine;
10510
10511 workspace.show_toast(
10512 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10513 cx,
10514 )
10515 })
10516 }
10517 }
10518 }
10519 }
10520
10521 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10522 let permalink = self.get_permalink_to_line(cx);
10523
10524 match permalink {
10525 Ok(permalink) => {
10526 cx.open_url(permalink.as_ref());
10527 }
10528 Err(err) => {
10529 let message = format!("Failed to open permalink: {err}");
10530
10531 Err::<(), anyhow::Error>(err).log_err();
10532
10533 if let Some(workspace) = self.workspace() {
10534 workspace.update(cx, |workspace, cx| {
10535 struct OpenPermalinkToLine;
10536
10537 workspace.show_toast(
10538 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
10539 cx,
10540 )
10541 })
10542 }
10543 }
10544 }
10545 }
10546
10547 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
10548 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
10549 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
10550 pub fn highlight_rows<T: 'static>(
10551 &mut self,
10552 rows: RangeInclusive<Anchor>,
10553 color: Option<Hsla>,
10554 should_autoscroll: bool,
10555 cx: &mut ViewContext<Self>,
10556 ) {
10557 let snapshot = self.buffer().read(cx).snapshot(cx);
10558 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
10559 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
10560 highlight
10561 .range
10562 .start()
10563 .cmp(&rows.start(), &snapshot)
10564 .then(highlight.range.end().cmp(&rows.end(), &snapshot))
10565 });
10566 match (color, existing_highlight_index) {
10567 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
10568 ix,
10569 RowHighlight {
10570 index: post_inc(&mut self.highlight_order),
10571 range: rows,
10572 should_autoscroll,
10573 color,
10574 },
10575 ),
10576 (None, Ok(i)) => {
10577 row_highlights.remove(i);
10578 }
10579 }
10580 }
10581
10582 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
10583 pub fn clear_row_highlights<T: 'static>(&mut self) {
10584 self.highlighted_rows.remove(&TypeId::of::<T>());
10585 }
10586
10587 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
10588 pub fn highlighted_rows<T: 'static>(
10589 &self,
10590 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
10591 Some(
10592 self.highlighted_rows
10593 .get(&TypeId::of::<T>())?
10594 .iter()
10595 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
10596 )
10597 }
10598
10599 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
10600 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
10601 /// Allows to ignore certain kinds of highlights.
10602 pub fn highlighted_display_rows(
10603 &mut self,
10604 cx: &mut WindowContext,
10605 ) -> BTreeMap<DisplayRow, Hsla> {
10606 let snapshot = self.snapshot(cx);
10607 let mut used_highlight_orders = HashMap::default();
10608 self.highlighted_rows
10609 .iter()
10610 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
10611 .fold(
10612 BTreeMap::<DisplayRow, Hsla>::new(),
10613 |mut unique_rows, highlight| {
10614 let start_row = highlight.range.start().to_display_point(&snapshot).row();
10615 let end_row = highlight.range.end().to_display_point(&snapshot).row();
10616 for row in start_row.0..=end_row.0 {
10617 let used_index =
10618 used_highlight_orders.entry(row).or_insert(highlight.index);
10619 if highlight.index >= *used_index {
10620 *used_index = highlight.index;
10621 match highlight.color {
10622 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
10623 None => unique_rows.remove(&DisplayRow(row)),
10624 };
10625 }
10626 }
10627 unique_rows
10628 },
10629 )
10630 }
10631
10632 pub fn highlighted_display_row_for_autoscroll(
10633 &self,
10634 snapshot: &DisplaySnapshot,
10635 ) -> Option<DisplayRow> {
10636 self.highlighted_rows
10637 .values()
10638 .flat_map(|highlighted_rows| highlighted_rows.iter())
10639 .filter_map(|highlight| {
10640 if highlight.color.is_none() || !highlight.should_autoscroll {
10641 return None;
10642 }
10643 Some(highlight.range.start().to_display_point(&snapshot).row())
10644 })
10645 .min()
10646 }
10647
10648 pub fn set_search_within_ranges(
10649 &mut self,
10650 ranges: &[Range<Anchor>],
10651 cx: &mut ViewContext<Self>,
10652 ) {
10653 self.highlight_background::<SearchWithinRange>(
10654 ranges,
10655 |colors| colors.editor_document_highlight_read_background,
10656 cx,
10657 )
10658 }
10659
10660 pub fn set_breadcrumb_header(&mut self, new_header: String) {
10661 self.breadcrumb_header = Some(new_header);
10662 }
10663
10664 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
10665 self.clear_background_highlights::<SearchWithinRange>(cx);
10666 }
10667
10668 pub fn highlight_background<T: 'static>(
10669 &mut self,
10670 ranges: &[Range<Anchor>],
10671 color_fetcher: fn(&ThemeColors) -> Hsla,
10672 cx: &mut ViewContext<Self>,
10673 ) {
10674 let snapshot = self.snapshot(cx);
10675 // this is to try and catch a panic sooner
10676 for range in ranges {
10677 snapshot
10678 .buffer_snapshot
10679 .summary_for_anchor::<usize>(&range.start);
10680 snapshot
10681 .buffer_snapshot
10682 .summary_for_anchor::<usize>(&range.end);
10683 }
10684
10685 self.background_highlights
10686 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10687 self.scrollbar_marker_state.dirty = true;
10688 cx.notify();
10689 }
10690
10691 pub fn clear_background_highlights<T: 'static>(
10692 &mut self,
10693 cx: &mut ViewContext<Self>,
10694 ) -> Option<BackgroundHighlight> {
10695 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
10696 if !text_highlights.1.is_empty() {
10697 self.scrollbar_marker_state.dirty = true;
10698 cx.notify();
10699 }
10700 Some(text_highlights)
10701 }
10702
10703 pub fn highlight_gutter<T: 'static>(
10704 &mut self,
10705 ranges: &[Range<Anchor>],
10706 color_fetcher: fn(&AppContext) -> Hsla,
10707 cx: &mut ViewContext<Self>,
10708 ) {
10709 self.gutter_highlights
10710 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10711 cx.notify();
10712 }
10713
10714 pub fn clear_gutter_highlights<T: 'static>(
10715 &mut self,
10716 cx: &mut ViewContext<Self>,
10717 ) -> Option<GutterHighlight> {
10718 cx.notify();
10719 self.gutter_highlights.remove(&TypeId::of::<T>())
10720 }
10721
10722 #[cfg(feature = "test-support")]
10723 pub fn all_text_background_highlights(
10724 &mut self,
10725 cx: &mut ViewContext<Self>,
10726 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10727 let snapshot = self.snapshot(cx);
10728 let buffer = &snapshot.buffer_snapshot;
10729 let start = buffer.anchor_before(0);
10730 let end = buffer.anchor_after(buffer.len());
10731 let theme = cx.theme().colors();
10732 self.background_highlights_in_range(start..end, &snapshot, theme)
10733 }
10734
10735 #[cfg(feature = "test-support")]
10736 pub fn search_background_highlights(
10737 &mut self,
10738 cx: &mut ViewContext<Self>,
10739 ) -> Vec<Range<Point>> {
10740 let snapshot = self.buffer().read(cx).snapshot(cx);
10741
10742 let highlights = self
10743 .background_highlights
10744 .get(&TypeId::of::<items::BufferSearchHighlights>());
10745
10746 if let Some((_color, ranges)) = highlights {
10747 ranges
10748 .iter()
10749 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
10750 .collect_vec()
10751 } else {
10752 vec![]
10753 }
10754 }
10755
10756 fn document_highlights_for_position<'a>(
10757 &'a self,
10758 position: Anchor,
10759 buffer: &'a MultiBufferSnapshot,
10760 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
10761 let read_highlights = self
10762 .background_highlights
10763 .get(&TypeId::of::<DocumentHighlightRead>())
10764 .map(|h| &h.1);
10765 let write_highlights = self
10766 .background_highlights
10767 .get(&TypeId::of::<DocumentHighlightWrite>())
10768 .map(|h| &h.1);
10769 let left_position = position.bias_left(buffer);
10770 let right_position = position.bias_right(buffer);
10771 read_highlights
10772 .into_iter()
10773 .chain(write_highlights)
10774 .flat_map(move |ranges| {
10775 let start_ix = match ranges.binary_search_by(|probe| {
10776 let cmp = probe.end.cmp(&left_position, buffer);
10777 if cmp.is_ge() {
10778 Ordering::Greater
10779 } else {
10780 Ordering::Less
10781 }
10782 }) {
10783 Ok(i) | Err(i) => i,
10784 };
10785
10786 ranges[start_ix..]
10787 .iter()
10788 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
10789 })
10790 }
10791
10792 pub fn has_background_highlights<T: 'static>(&self) -> bool {
10793 self.background_highlights
10794 .get(&TypeId::of::<T>())
10795 .map_or(false, |(_, highlights)| !highlights.is_empty())
10796 }
10797
10798 pub fn background_highlights_in_range(
10799 &self,
10800 search_range: Range<Anchor>,
10801 display_snapshot: &DisplaySnapshot,
10802 theme: &ThemeColors,
10803 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10804 let mut results = Vec::new();
10805 for (color_fetcher, ranges) in self.background_highlights.values() {
10806 let color = color_fetcher(theme);
10807 let start_ix = match ranges.binary_search_by(|probe| {
10808 let cmp = probe
10809 .end
10810 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10811 if cmp.is_gt() {
10812 Ordering::Greater
10813 } else {
10814 Ordering::Less
10815 }
10816 }) {
10817 Ok(i) | Err(i) => i,
10818 };
10819 for range in &ranges[start_ix..] {
10820 if range
10821 .start
10822 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10823 .is_ge()
10824 {
10825 break;
10826 }
10827
10828 let start = range.start.to_display_point(&display_snapshot);
10829 let end = range.end.to_display_point(&display_snapshot);
10830 results.push((start..end, color))
10831 }
10832 }
10833 results
10834 }
10835
10836 pub fn background_highlight_row_ranges<T: 'static>(
10837 &self,
10838 search_range: Range<Anchor>,
10839 display_snapshot: &DisplaySnapshot,
10840 count: usize,
10841 ) -> Vec<RangeInclusive<DisplayPoint>> {
10842 let mut results = Vec::new();
10843 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
10844 return vec![];
10845 };
10846
10847 let start_ix = match ranges.binary_search_by(|probe| {
10848 let cmp = probe
10849 .end
10850 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10851 if cmp.is_gt() {
10852 Ordering::Greater
10853 } else {
10854 Ordering::Less
10855 }
10856 }) {
10857 Ok(i) | Err(i) => i,
10858 };
10859 let mut push_region = |start: Option<Point>, end: Option<Point>| {
10860 if let (Some(start_display), Some(end_display)) = (start, end) {
10861 results.push(
10862 start_display.to_display_point(display_snapshot)
10863 ..=end_display.to_display_point(display_snapshot),
10864 );
10865 }
10866 };
10867 let mut start_row: Option<Point> = None;
10868 let mut end_row: Option<Point> = None;
10869 if ranges.len() > count {
10870 return Vec::new();
10871 }
10872 for range in &ranges[start_ix..] {
10873 if range
10874 .start
10875 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10876 .is_ge()
10877 {
10878 break;
10879 }
10880 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
10881 if let Some(current_row) = &end_row {
10882 if end.row == current_row.row {
10883 continue;
10884 }
10885 }
10886 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
10887 if start_row.is_none() {
10888 assert_eq!(end_row, None);
10889 start_row = Some(start);
10890 end_row = Some(end);
10891 continue;
10892 }
10893 if let Some(current_end) = end_row.as_mut() {
10894 if start.row > current_end.row + 1 {
10895 push_region(start_row, end_row);
10896 start_row = Some(start);
10897 end_row = Some(end);
10898 } else {
10899 // Merge two hunks.
10900 *current_end = end;
10901 }
10902 } else {
10903 unreachable!();
10904 }
10905 }
10906 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
10907 push_region(start_row, end_row);
10908 results
10909 }
10910
10911 pub fn gutter_highlights_in_range(
10912 &self,
10913 search_range: Range<Anchor>,
10914 display_snapshot: &DisplaySnapshot,
10915 cx: &AppContext,
10916 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10917 let mut results = Vec::new();
10918 for (color_fetcher, ranges) in self.gutter_highlights.values() {
10919 let color = color_fetcher(cx);
10920 let start_ix = match ranges.binary_search_by(|probe| {
10921 let cmp = probe
10922 .end
10923 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10924 if cmp.is_gt() {
10925 Ordering::Greater
10926 } else {
10927 Ordering::Less
10928 }
10929 }) {
10930 Ok(i) | Err(i) => i,
10931 };
10932 for range in &ranges[start_ix..] {
10933 if range
10934 .start
10935 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10936 .is_ge()
10937 {
10938 break;
10939 }
10940
10941 let start = range.start.to_display_point(&display_snapshot);
10942 let end = range.end.to_display_point(&display_snapshot);
10943 results.push((start..end, color))
10944 }
10945 }
10946 results
10947 }
10948
10949 /// Get the text ranges corresponding to the redaction query
10950 pub fn redacted_ranges(
10951 &self,
10952 search_range: Range<Anchor>,
10953 display_snapshot: &DisplaySnapshot,
10954 cx: &WindowContext,
10955 ) -> Vec<Range<DisplayPoint>> {
10956 display_snapshot
10957 .buffer_snapshot
10958 .redacted_ranges(search_range, |file| {
10959 if let Some(file) = file {
10960 file.is_private()
10961 && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
10962 } else {
10963 false
10964 }
10965 })
10966 .map(|range| {
10967 range.start.to_display_point(display_snapshot)
10968 ..range.end.to_display_point(display_snapshot)
10969 })
10970 .collect()
10971 }
10972
10973 pub fn highlight_text<T: 'static>(
10974 &mut self,
10975 ranges: Vec<Range<Anchor>>,
10976 style: HighlightStyle,
10977 cx: &mut ViewContext<Self>,
10978 ) {
10979 self.display_map.update(cx, |map, _| {
10980 map.highlight_text(TypeId::of::<T>(), ranges, style)
10981 });
10982 cx.notify();
10983 }
10984
10985 pub(crate) fn highlight_inlays<T: 'static>(
10986 &mut self,
10987 highlights: Vec<InlayHighlight>,
10988 style: HighlightStyle,
10989 cx: &mut ViewContext<Self>,
10990 ) {
10991 self.display_map.update(cx, |map, _| {
10992 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
10993 });
10994 cx.notify();
10995 }
10996
10997 pub fn text_highlights<'a, T: 'static>(
10998 &'a self,
10999 cx: &'a AppContext,
11000 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11001 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11002 }
11003
11004 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11005 let cleared = self
11006 .display_map
11007 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11008 if cleared {
11009 cx.notify();
11010 }
11011 }
11012
11013 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11014 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11015 && self.focus_handle.is_focused(cx)
11016 }
11017
11018 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11019 self.show_cursor_when_unfocused = is_enabled;
11020 cx.notify();
11021 }
11022
11023 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11024 cx.notify();
11025 }
11026
11027 fn on_buffer_event(
11028 &mut self,
11029 multibuffer: Model<MultiBuffer>,
11030 event: &multi_buffer::Event,
11031 cx: &mut ViewContext<Self>,
11032 ) {
11033 match event {
11034 multi_buffer::Event::Edited {
11035 singleton_buffer_edited,
11036 } => {
11037 self.scrollbar_marker_state.dirty = true;
11038 self.active_indent_guides_state.dirty = true;
11039 self.refresh_active_diagnostics(cx);
11040 self.refresh_code_actions(cx);
11041 if self.has_active_inline_completion(cx) {
11042 self.update_visible_inline_completion(cx);
11043 }
11044 cx.emit(EditorEvent::BufferEdited);
11045 cx.emit(SearchEvent::MatchesInvalidated);
11046 if *singleton_buffer_edited {
11047 if let Some(project) = &self.project {
11048 let project = project.read(cx);
11049 let languages_affected = multibuffer
11050 .read(cx)
11051 .all_buffers()
11052 .into_iter()
11053 .filter_map(|buffer| {
11054 let buffer = buffer.read(cx);
11055 let language = buffer.language()?;
11056 if project.is_local()
11057 && project.language_servers_for_buffer(buffer, cx).count() == 0
11058 {
11059 None
11060 } else {
11061 Some(language)
11062 }
11063 })
11064 .cloned()
11065 .collect::<HashSet<_>>();
11066 if !languages_affected.is_empty() {
11067 self.refresh_inlay_hints(
11068 InlayHintRefreshReason::BufferEdited(languages_affected),
11069 cx,
11070 );
11071 }
11072 }
11073 }
11074
11075 let Some(project) = &self.project else { return };
11076 let telemetry = project.read(cx).client().telemetry().clone();
11077 refresh_linked_ranges(self, cx);
11078 telemetry.log_edit_event("editor");
11079 }
11080 multi_buffer::Event::ExcerptsAdded {
11081 buffer,
11082 predecessor,
11083 excerpts,
11084 } => {
11085 self.tasks_update_task = Some(self.refresh_runnables(cx));
11086 cx.emit(EditorEvent::ExcerptsAdded {
11087 buffer: buffer.clone(),
11088 predecessor: *predecessor,
11089 excerpts: excerpts.clone(),
11090 });
11091 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11092 }
11093 multi_buffer::Event::ExcerptsRemoved { ids } => {
11094 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11095 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11096 }
11097 multi_buffer::Event::ExcerptsEdited { ids } => {
11098 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11099 }
11100 multi_buffer::Event::ExcerptsExpanded { ids } => {
11101 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11102 }
11103 multi_buffer::Event::Reparsed(buffer_id) => {
11104 self.tasks_update_task = Some(self.refresh_runnables(cx));
11105
11106 cx.emit(EditorEvent::Reparsed(*buffer_id));
11107 }
11108 multi_buffer::Event::LanguageChanged(buffer_id) => {
11109 linked_editing_ranges::refresh_linked_ranges(self, cx);
11110 cx.emit(EditorEvent::Reparsed(*buffer_id));
11111 cx.notify();
11112 }
11113 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11114 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11115 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11116 cx.emit(EditorEvent::TitleChanged)
11117 }
11118 multi_buffer::Event::DiffBaseChanged => {
11119 self.scrollbar_marker_state.dirty = true;
11120 cx.emit(EditorEvent::DiffBaseChanged);
11121 cx.notify();
11122 }
11123 multi_buffer::Event::DiffUpdated { buffer } => {
11124 self.sync_expanded_diff_hunks(buffer.clone(), cx);
11125 cx.notify();
11126 }
11127 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11128 multi_buffer::Event::DiagnosticsUpdated => {
11129 self.refresh_active_diagnostics(cx);
11130 self.scrollbar_marker_state.dirty = true;
11131 cx.notify();
11132 }
11133 _ => {}
11134 };
11135 }
11136
11137 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11138 cx.notify();
11139 }
11140
11141 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11142 self.tasks_update_task = Some(self.refresh_runnables(cx));
11143 self.refresh_inline_completion(true, cx);
11144 self.refresh_inlay_hints(
11145 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11146 self.selections.newest_anchor().head(),
11147 &self.buffer.read(cx).snapshot(cx),
11148 cx,
11149 )),
11150 cx,
11151 );
11152 let editor_settings = EditorSettings::get_global(cx);
11153 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11154 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11155
11156 if self.mode == EditorMode::Full {
11157 let inline_blame_enabled = ProjectSettings::get_global(cx).git.inline_blame_enabled();
11158 if self.git_blame_inline_enabled != inline_blame_enabled {
11159 self.toggle_git_blame_inline_internal(false, cx);
11160 }
11161 }
11162
11163 cx.notify();
11164 }
11165
11166 pub fn set_searchable(&mut self, searchable: bool) {
11167 self.searchable = searchable;
11168 }
11169
11170 pub fn searchable(&self) -> bool {
11171 self.searchable
11172 }
11173
11174 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11175 self.open_excerpts_common(true, cx)
11176 }
11177
11178 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11179 self.open_excerpts_common(false, cx)
11180 }
11181
11182 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11183 let buffer = self.buffer.read(cx);
11184 if buffer.is_singleton() {
11185 cx.propagate();
11186 return;
11187 }
11188
11189 let Some(workspace) = self.workspace() else {
11190 cx.propagate();
11191 return;
11192 };
11193
11194 let mut new_selections_by_buffer = HashMap::default();
11195 for selection in self.selections.all::<usize>(cx) {
11196 for (buffer, mut range, _) in
11197 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11198 {
11199 if selection.reversed {
11200 mem::swap(&mut range.start, &mut range.end);
11201 }
11202 new_selections_by_buffer
11203 .entry(buffer)
11204 .or_insert(Vec::new())
11205 .push(range)
11206 }
11207 }
11208
11209 // We defer the pane interaction because we ourselves are a workspace item
11210 // and activating a new item causes the pane to call a method on us reentrantly,
11211 // which panics if we're on the stack.
11212 cx.window_context().defer(move |cx| {
11213 workspace.update(cx, |workspace, cx| {
11214 let pane = if split {
11215 workspace.adjacent_pane(cx)
11216 } else {
11217 workspace.active_pane().clone()
11218 };
11219
11220 for (buffer, ranges) in new_selections_by_buffer {
11221 let editor = workspace.open_project_item::<Self>(pane.clone(), buffer, cx);
11222 editor.update(cx, |editor, cx| {
11223 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11224 s.select_ranges(ranges);
11225 });
11226 });
11227 }
11228 })
11229 });
11230 }
11231
11232 fn jump(
11233 &mut self,
11234 path: ProjectPath,
11235 position: Point,
11236 anchor: language::Anchor,
11237 offset_from_top: u32,
11238 cx: &mut ViewContext<Self>,
11239 ) {
11240 let workspace = self.workspace();
11241 cx.spawn(|_, mut cx| async move {
11242 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11243 let editor = workspace.update(&mut cx, |workspace, cx| {
11244 // Reset the preview item id before opening the new item
11245 workspace.active_pane().update(cx, |pane, cx| {
11246 pane.set_preview_item_id(None, cx);
11247 });
11248 workspace.open_path_preview(path, None, true, true, cx)
11249 })?;
11250 let editor = editor
11251 .await?
11252 .downcast::<Editor>()
11253 .ok_or_else(|| anyhow!("opened item was not an editor"))?
11254 .downgrade();
11255 editor.update(&mut cx, |editor, cx| {
11256 let buffer = editor
11257 .buffer()
11258 .read(cx)
11259 .as_singleton()
11260 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11261 let buffer = buffer.read(cx);
11262 let cursor = if buffer.can_resolve(&anchor) {
11263 language::ToPoint::to_point(&anchor, buffer)
11264 } else {
11265 buffer.clip_point(position, Bias::Left)
11266 };
11267
11268 let nav_history = editor.nav_history.take();
11269 editor.change_selections(
11270 Some(Autoscroll::top_relative(offset_from_top as usize)),
11271 cx,
11272 |s| {
11273 s.select_ranges([cursor..cursor]);
11274 },
11275 );
11276 editor.nav_history = nav_history;
11277
11278 anyhow::Ok(())
11279 })??;
11280
11281 anyhow::Ok(())
11282 })
11283 .detach_and_log_err(cx);
11284 }
11285
11286 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11287 let snapshot = self.buffer.read(cx).read(cx);
11288 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11289 Some(
11290 ranges
11291 .iter()
11292 .map(move |range| {
11293 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11294 })
11295 .collect(),
11296 )
11297 }
11298
11299 fn selection_replacement_ranges(
11300 &self,
11301 range: Range<OffsetUtf16>,
11302 cx: &AppContext,
11303 ) -> Vec<Range<OffsetUtf16>> {
11304 let selections = self.selections.all::<OffsetUtf16>(cx);
11305 let newest_selection = selections
11306 .iter()
11307 .max_by_key(|selection| selection.id)
11308 .unwrap();
11309 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11310 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11311 let snapshot = self.buffer.read(cx).read(cx);
11312 selections
11313 .into_iter()
11314 .map(|mut selection| {
11315 selection.start.0 =
11316 (selection.start.0 as isize).saturating_add(start_delta) as usize;
11317 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11318 snapshot.clip_offset_utf16(selection.start, Bias::Left)
11319 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11320 })
11321 .collect()
11322 }
11323
11324 fn report_editor_event(
11325 &self,
11326 operation: &'static str,
11327 file_extension: Option<String>,
11328 cx: &AppContext,
11329 ) {
11330 if cfg!(any(test, feature = "test-support")) {
11331 return;
11332 }
11333
11334 let Some(project) = &self.project else { return };
11335
11336 // If None, we are in a file without an extension
11337 let file = self
11338 .buffer
11339 .read(cx)
11340 .as_singleton()
11341 .and_then(|b| b.read(cx).file());
11342 let file_extension = file_extension.or(file
11343 .as_ref()
11344 .and_then(|file| Path::new(file.file_name(cx)).extension())
11345 .and_then(|e| e.to_str())
11346 .map(|a| a.to_string()));
11347
11348 let vim_mode = cx
11349 .global::<SettingsStore>()
11350 .raw_user_settings()
11351 .get("vim_mode")
11352 == Some(&serde_json::Value::Bool(true));
11353
11354 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11355 == language::language_settings::InlineCompletionProvider::Copilot;
11356 let copilot_enabled_for_language = self
11357 .buffer
11358 .read(cx)
11359 .settings_at(0, cx)
11360 .show_inline_completions;
11361
11362 let telemetry = project.read(cx).client().telemetry().clone();
11363 telemetry.report_editor_event(
11364 file_extension,
11365 vim_mode,
11366 operation,
11367 copilot_enabled,
11368 copilot_enabled_for_language,
11369 )
11370 }
11371
11372 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11373 /// with each line being an array of {text, highlight} objects.
11374 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11375 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11376 return;
11377 };
11378
11379 #[derive(Serialize)]
11380 struct Chunk<'a> {
11381 text: String,
11382 highlight: Option<&'a str>,
11383 }
11384
11385 let snapshot = buffer.read(cx).snapshot();
11386 let range = self
11387 .selected_text_range(cx)
11388 .and_then(|selected_range| {
11389 if selected_range.is_empty() {
11390 None
11391 } else {
11392 Some(selected_range)
11393 }
11394 })
11395 .unwrap_or_else(|| 0..snapshot.len());
11396
11397 let chunks = snapshot.chunks(range, true);
11398 let mut lines = Vec::new();
11399 let mut line: VecDeque<Chunk> = VecDeque::new();
11400
11401 let Some(style) = self.style.as_ref() else {
11402 return;
11403 };
11404
11405 for chunk in chunks {
11406 let highlight = chunk
11407 .syntax_highlight_id
11408 .and_then(|id| id.name(&style.syntax));
11409 let mut chunk_lines = chunk.text.split('\n').peekable();
11410 while let Some(text) = chunk_lines.next() {
11411 let mut merged_with_last_token = false;
11412 if let Some(last_token) = line.back_mut() {
11413 if last_token.highlight == highlight {
11414 last_token.text.push_str(text);
11415 merged_with_last_token = true;
11416 }
11417 }
11418
11419 if !merged_with_last_token {
11420 line.push_back(Chunk {
11421 text: text.into(),
11422 highlight,
11423 });
11424 }
11425
11426 if chunk_lines.peek().is_some() {
11427 if line.len() > 1 && line.front().unwrap().text.is_empty() {
11428 line.pop_front();
11429 }
11430 if line.len() > 1 && line.back().unwrap().text.is_empty() {
11431 line.pop_back();
11432 }
11433
11434 lines.push(mem::take(&mut line));
11435 }
11436 }
11437 }
11438
11439 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11440 return;
11441 };
11442 cx.write_to_clipboard(ClipboardItem::new(lines));
11443 }
11444
11445 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11446 &self.inlay_hint_cache
11447 }
11448
11449 pub fn replay_insert_event(
11450 &mut self,
11451 text: &str,
11452 relative_utf16_range: Option<Range<isize>>,
11453 cx: &mut ViewContext<Self>,
11454 ) {
11455 if !self.input_enabled {
11456 cx.emit(EditorEvent::InputIgnored { text: text.into() });
11457 return;
11458 }
11459 if let Some(relative_utf16_range) = relative_utf16_range {
11460 let selections = self.selections.all::<OffsetUtf16>(cx);
11461 self.change_selections(None, cx, |s| {
11462 let new_ranges = selections.into_iter().map(|range| {
11463 let start = OffsetUtf16(
11464 range
11465 .head()
11466 .0
11467 .saturating_add_signed(relative_utf16_range.start),
11468 );
11469 let end = OffsetUtf16(
11470 range
11471 .head()
11472 .0
11473 .saturating_add_signed(relative_utf16_range.end),
11474 );
11475 start..end
11476 });
11477 s.select_ranges(new_ranges);
11478 });
11479 }
11480
11481 self.handle_input(text, cx);
11482 }
11483
11484 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11485 let Some(project) = self.project.as_ref() else {
11486 return false;
11487 };
11488 let project = project.read(cx);
11489
11490 let mut supports = false;
11491 self.buffer().read(cx).for_each_buffer(|buffer| {
11492 if !supports {
11493 supports = project
11494 .language_servers_for_buffer(buffer.read(cx), cx)
11495 .any(
11496 |(_, server)| match server.capabilities().inlay_hint_provider {
11497 Some(lsp::OneOf::Left(enabled)) => enabled,
11498 Some(lsp::OneOf::Right(_)) => true,
11499 None => false,
11500 },
11501 )
11502 }
11503 });
11504 supports
11505 }
11506
11507 pub fn focus(&self, cx: &mut WindowContext) {
11508 cx.focus(&self.focus_handle)
11509 }
11510
11511 pub fn is_focused(&self, cx: &WindowContext) -> bool {
11512 self.focus_handle.is_focused(cx)
11513 }
11514
11515 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11516 cx.emit(EditorEvent::Focused);
11517
11518 if let Some(descendant) = self
11519 .last_focused_descendant
11520 .take()
11521 .and_then(|descendant| descendant.upgrade())
11522 {
11523 cx.focus(&descendant);
11524 } else {
11525 if let Some(blame) = self.blame.as_ref() {
11526 blame.update(cx, GitBlame::focus)
11527 }
11528
11529 self.blink_manager.update(cx, BlinkManager::enable);
11530 self.show_cursor_names(cx);
11531 self.buffer.update(cx, |buffer, cx| {
11532 buffer.finalize_last_transaction(cx);
11533 if self.leader_peer_id.is_none() {
11534 buffer.set_active_selections(
11535 &self.selections.disjoint_anchors(),
11536 self.selections.line_mode,
11537 self.cursor_shape,
11538 cx,
11539 );
11540 }
11541 });
11542 }
11543 }
11544
11545 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
11546 if event.blurred != self.focus_handle {
11547 self.last_focused_descendant = Some(event.blurred);
11548 }
11549 }
11550
11551 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
11552 self.blink_manager.update(cx, BlinkManager::disable);
11553 self.buffer
11554 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
11555
11556 if let Some(blame) = self.blame.as_ref() {
11557 blame.update(cx, GitBlame::blur)
11558 }
11559 self.hide_context_menu(cx);
11560 hide_hover(self, cx);
11561 cx.emit(EditorEvent::Blurred);
11562 cx.notify();
11563 }
11564
11565 pub fn register_action<A: Action>(
11566 &mut self,
11567 listener: impl Fn(&A, &mut WindowContext) + 'static,
11568 ) -> Subscription {
11569 let id = self.next_editor_action_id.post_inc();
11570 let listener = Arc::new(listener);
11571 self.editor_actions.borrow_mut().insert(
11572 id,
11573 Box::new(move |cx| {
11574 let _view = cx.view().clone();
11575 let cx = cx.window_context();
11576 let listener = listener.clone();
11577 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
11578 let action = action.downcast_ref().unwrap();
11579 if phase == DispatchPhase::Bubble {
11580 listener(action, cx)
11581 }
11582 })
11583 }),
11584 );
11585
11586 let editor_actions = self.editor_actions.clone();
11587 Subscription::new(move || {
11588 editor_actions.borrow_mut().remove(&id);
11589 })
11590 }
11591
11592 pub fn file_header_size(&self) -> u8 {
11593 self.file_header_size
11594 }
11595}
11596
11597fn hunks_for_selections(
11598 multi_buffer_snapshot: &MultiBufferSnapshot,
11599 selections: &[Selection<Anchor>],
11600) -> Vec<DiffHunk<MultiBufferRow>> {
11601 let mut hunks = Vec::with_capacity(selections.len());
11602 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
11603 HashMap::default();
11604 let buffer_rows_for_selections = selections.iter().map(|selection| {
11605 let head = selection.head();
11606 let tail = selection.tail();
11607 let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
11608 let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
11609 if start > end {
11610 end..start
11611 } else {
11612 start..end
11613 }
11614 });
11615
11616 for selected_multi_buffer_rows in buffer_rows_for_selections {
11617 let query_rows =
11618 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
11619 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
11620 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
11621 // when the caret is just above or just below the deleted hunk.
11622 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
11623 let related_to_selection = if allow_adjacent {
11624 hunk.associated_range.overlaps(&query_rows)
11625 || hunk.associated_range.start == query_rows.end
11626 || hunk.associated_range.end == query_rows.start
11627 } else {
11628 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
11629 // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
11630 hunk.associated_range.overlaps(&selected_multi_buffer_rows)
11631 || selected_multi_buffer_rows.end == hunk.associated_range.start
11632 };
11633 if related_to_selection {
11634 if !processed_buffer_rows
11635 .entry(hunk.buffer_id)
11636 .or_default()
11637 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
11638 {
11639 continue;
11640 }
11641 hunks.push(hunk);
11642 }
11643 }
11644 }
11645
11646 hunks
11647}
11648
11649pub trait CollaborationHub {
11650 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
11651 fn user_participant_indices<'a>(
11652 &self,
11653 cx: &'a AppContext,
11654 ) -> &'a HashMap<u64, ParticipantIndex>;
11655 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
11656}
11657
11658impl CollaborationHub for Model<Project> {
11659 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
11660 self.read(cx).collaborators()
11661 }
11662
11663 fn user_participant_indices<'a>(
11664 &self,
11665 cx: &'a AppContext,
11666 ) -> &'a HashMap<u64, ParticipantIndex> {
11667 self.read(cx).user_store().read(cx).participant_indices()
11668 }
11669
11670 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
11671 let this = self.read(cx);
11672 let user_ids = this.collaborators().values().map(|c| c.user_id);
11673 this.user_store().read_with(cx, |user_store, cx| {
11674 user_store.participant_names(user_ids, cx)
11675 })
11676 }
11677}
11678
11679pub trait CompletionProvider {
11680 fn completions(
11681 &self,
11682 buffer: &Model<Buffer>,
11683 buffer_position: text::Anchor,
11684 trigger: CompletionContext,
11685 cx: &mut ViewContext<Editor>,
11686 ) -> Task<Result<Vec<Completion>>>;
11687
11688 fn resolve_completions(
11689 &self,
11690 buffer: Model<Buffer>,
11691 completion_indices: Vec<usize>,
11692 completions: Arc<RwLock<Box<[Completion]>>>,
11693 cx: &mut ViewContext<Editor>,
11694 ) -> Task<Result<bool>>;
11695
11696 fn apply_additional_edits_for_completion(
11697 &self,
11698 buffer: Model<Buffer>,
11699 completion: Completion,
11700 push_to_history: bool,
11701 cx: &mut ViewContext<Editor>,
11702 ) -> Task<Result<Option<language::Transaction>>>;
11703
11704 fn is_completion_trigger(
11705 &self,
11706 buffer: &Model<Buffer>,
11707 position: language::Anchor,
11708 text: &str,
11709 trigger_in_words: bool,
11710 cx: &mut ViewContext<Editor>,
11711 ) -> bool;
11712}
11713
11714impl CompletionProvider for Model<Project> {
11715 fn completions(
11716 &self,
11717 buffer: &Model<Buffer>,
11718 buffer_position: text::Anchor,
11719 options: CompletionContext,
11720 cx: &mut ViewContext<Editor>,
11721 ) -> Task<Result<Vec<Completion>>> {
11722 self.update(cx, |project, cx| {
11723 project.completions(&buffer, buffer_position, options, cx)
11724 })
11725 }
11726
11727 fn resolve_completions(
11728 &self,
11729 buffer: Model<Buffer>,
11730 completion_indices: Vec<usize>,
11731 completions: Arc<RwLock<Box<[Completion]>>>,
11732 cx: &mut ViewContext<Editor>,
11733 ) -> Task<Result<bool>> {
11734 self.update(cx, |project, cx| {
11735 project.resolve_completions(buffer, completion_indices, completions, cx)
11736 })
11737 }
11738
11739 fn apply_additional_edits_for_completion(
11740 &self,
11741 buffer: Model<Buffer>,
11742 completion: Completion,
11743 push_to_history: bool,
11744 cx: &mut ViewContext<Editor>,
11745 ) -> Task<Result<Option<language::Transaction>>> {
11746 self.update(cx, |project, cx| {
11747 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
11748 })
11749 }
11750
11751 fn is_completion_trigger(
11752 &self,
11753 buffer: &Model<Buffer>,
11754 position: language::Anchor,
11755 text: &str,
11756 trigger_in_words: bool,
11757 cx: &mut ViewContext<Editor>,
11758 ) -> bool {
11759 if !EditorSettings::get_global(cx).show_completions_on_input {
11760 return false;
11761 }
11762
11763 let mut chars = text.chars();
11764 let char = if let Some(char) = chars.next() {
11765 char
11766 } else {
11767 return false;
11768 };
11769 if chars.next().is_some() {
11770 return false;
11771 }
11772
11773 let buffer = buffer.read(cx);
11774 let scope = buffer.snapshot().language_scope_at(position);
11775 if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
11776 return true;
11777 }
11778
11779 buffer
11780 .completion_triggers()
11781 .iter()
11782 .any(|string| string == text)
11783 }
11784}
11785
11786fn inlay_hint_settings(
11787 location: Anchor,
11788 snapshot: &MultiBufferSnapshot,
11789 cx: &mut ViewContext<'_, Editor>,
11790) -> InlayHintSettings {
11791 let file = snapshot.file_at(location);
11792 let language = snapshot.language_at(location);
11793 let settings = all_language_settings(file, cx);
11794 settings
11795 .language(language.map(|l| l.name()).as_deref())
11796 .inlay_hints
11797}
11798
11799fn consume_contiguous_rows(
11800 contiguous_row_selections: &mut Vec<Selection<Point>>,
11801 selection: &Selection<Point>,
11802 display_map: &DisplaySnapshot,
11803 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
11804) -> (MultiBufferRow, MultiBufferRow) {
11805 contiguous_row_selections.push(selection.clone());
11806 let start_row = MultiBufferRow(selection.start.row);
11807 let mut end_row = ending_row(selection, display_map);
11808
11809 while let Some(next_selection) = selections.peek() {
11810 if next_selection.start.row <= end_row.0 {
11811 end_row = ending_row(next_selection, display_map);
11812 contiguous_row_selections.push(selections.next().unwrap().clone());
11813 } else {
11814 break;
11815 }
11816 }
11817 (start_row, end_row)
11818}
11819
11820fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
11821 if next_selection.end.column > 0 || next_selection.is_empty() {
11822 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
11823 } else {
11824 MultiBufferRow(next_selection.end.row)
11825 }
11826}
11827
11828impl EditorSnapshot {
11829 pub fn remote_selections_in_range<'a>(
11830 &'a self,
11831 range: &'a Range<Anchor>,
11832 collaboration_hub: &dyn CollaborationHub,
11833 cx: &'a AppContext,
11834 ) -> impl 'a + Iterator<Item = RemoteSelection> {
11835 let participant_names = collaboration_hub.user_names(cx);
11836 let participant_indices = collaboration_hub.user_participant_indices(cx);
11837 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
11838 let collaborators_by_replica_id = collaborators_by_peer_id
11839 .iter()
11840 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
11841 .collect::<HashMap<_, _>>();
11842 self.buffer_snapshot
11843 .selections_in_range(range, false)
11844 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
11845 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
11846 let participant_index = participant_indices.get(&collaborator.user_id).copied();
11847 let user_name = participant_names.get(&collaborator.user_id).cloned();
11848 Some(RemoteSelection {
11849 replica_id,
11850 selection,
11851 cursor_shape,
11852 line_mode,
11853 participant_index,
11854 peer_id: collaborator.peer_id,
11855 user_name,
11856 })
11857 })
11858 }
11859
11860 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
11861 self.display_snapshot.buffer_snapshot.language_at(position)
11862 }
11863
11864 pub fn is_focused(&self) -> bool {
11865 self.is_focused
11866 }
11867
11868 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
11869 self.placeholder_text.as_ref()
11870 }
11871
11872 pub fn scroll_position(&self) -> gpui::Point<f32> {
11873 self.scroll_anchor.scroll_position(&self.display_snapshot)
11874 }
11875
11876 pub fn gutter_dimensions(
11877 &self,
11878 font_id: FontId,
11879 font_size: Pixels,
11880 em_width: Pixels,
11881 max_line_number_width: Pixels,
11882 cx: &AppContext,
11883 ) -> GutterDimensions {
11884 if !self.show_gutter {
11885 return GutterDimensions::default();
11886 }
11887 let descent = cx.text_system().descent(font_id, font_size);
11888
11889 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
11890 matches!(
11891 ProjectSettings::get_global(cx).git.git_gutter,
11892 Some(GitGutterSetting::TrackedFiles)
11893 )
11894 });
11895 let gutter_settings = EditorSettings::get_global(cx).gutter;
11896 let show_line_numbers = self
11897 .show_line_numbers
11898 .unwrap_or(gutter_settings.line_numbers);
11899 let line_gutter_width = if show_line_numbers {
11900 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
11901 let min_width_for_number_on_gutter = em_width * 4.0;
11902 max_line_number_width.max(min_width_for_number_on_gutter)
11903 } else {
11904 0.0.into()
11905 };
11906
11907 let show_code_actions = self
11908 .show_code_actions
11909 .unwrap_or(gutter_settings.code_actions);
11910
11911 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
11912
11913 let git_blame_entries_width = self
11914 .render_git_blame_gutter
11915 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
11916
11917 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
11918 left_padding += if show_code_actions || show_runnables {
11919 em_width * 3.0
11920 } else if show_git_gutter && show_line_numbers {
11921 em_width * 2.0
11922 } else if show_git_gutter || show_line_numbers {
11923 em_width
11924 } else {
11925 px(0.)
11926 };
11927
11928 let right_padding = if gutter_settings.folds && show_line_numbers {
11929 em_width * 4.0
11930 } else if gutter_settings.folds {
11931 em_width * 3.0
11932 } else if show_line_numbers {
11933 em_width
11934 } else {
11935 px(0.)
11936 };
11937
11938 GutterDimensions {
11939 left_padding,
11940 right_padding,
11941 width: line_gutter_width + left_padding + right_padding,
11942 margin: -descent,
11943 git_blame_entries_width,
11944 }
11945 }
11946
11947 pub fn render_fold_toggle(
11948 &self,
11949 buffer_row: MultiBufferRow,
11950 row_contains_cursor: bool,
11951 editor: View<Editor>,
11952 cx: &mut WindowContext,
11953 ) -> Option<AnyElement> {
11954 let folded = self.is_line_folded(buffer_row);
11955
11956 if let Some(crease) = self
11957 .crease_snapshot
11958 .query_row(buffer_row, &self.buffer_snapshot)
11959 {
11960 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
11961 if folded {
11962 editor.update(cx, |editor, cx| {
11963 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
11964 });
11965 } else {
11966 editor.update(cx, |editor, cx| {
11967 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
11968 });
11969 }
11970 });
11971
11972 Some((crease.render_toggle)(
11973 buffer_row,
11974 folded,
11975 toggle_callback,
11976 cx,
11977 ))
11978 } else if folded
11979 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
11980 {
11981 Some(
11982 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
11983 .selected(folded)
11984 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
11985 if folded {
11986 this.unfold_at(&UnfoldAt { buffer_row }, cx);
11987 } else {
11988 this.fold_at(&FoldAt { buffer_row }, cx);
11989 }
11990 }))
11991 .into_any_element(),
11992 )
11993 } else {
11994 None
11995 }
11996 }
11997
11998 pub fn render_crease_trailer(
11999 &self,
12000 buffer_row: MultiBufferRow,
12001 cx: &mut WindowContext,
12002 ) -> Option<AnyElement> {
12003 let folded = self.is_line_folded(buffer_row);
12004 let crease = self
12005 .crease_snapshot
12006 .query_row(buffer_row, &self.buffer_snapshot)?;
12007 Some((crease.render_trailer)(buffer_row, folded, cx))
12008 }
12009}
12010
12011impl Deref for EditorSnapshot {
12012 type Target = DisplaySnapshot;
12013
12014 fn deref(&self) -> &Self::Target {
12015 &self.display_snapshot
12016 }
12017}
12018
12019#[derive(Clone, Debug, PartialEq, Eq)]
12020pub enum EditorEvent {
12021 InputIgnored {
12022 text: Arc<str>,
12023 },
12024 InputHandled {
12025 utf16_range_to_replace: Option<Range<isize>>,
12026 text: Arc<str>,
12027 },
12028 ExcerptsAdded {
12029 buffer: Model<Buffer>,
12030 predecessor: ExcerptId,
12031 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12032 },
12033 ExcerptsRemoved {
12034 ids: Vec<ExcerptId>,
12035 },
12036 ExcerptsEdited {
12037 ids: Vec<ExcerptId>,
12038 },
12039 ExcerptsExpanded {
12040 ids: Vec<ExcerptId>,
12041 },
12042 BufferEdited,
12043 Edited {
12044 transaction_id: clock::Lamport,
12045 },
12046 Reparsed(BufferId),
12047 Focused,
12048 Blurred,
12049 DirtyChanged,
12050 Saved,
12051 TitleChanged,
12052 DiffBaseChanged,
12053 SelectionsChanged {
12054 local: bool,
12055 },
12056 ScrollPositionChanged {
12057 local: bool,
12058 autoscroll: bool,
12059 },
12060 Closed,
12061 TransactionUndone {
12062 transaction_id: clock::Lamport,
12063 },
12064 TransactionBegun {
12065 transaction_id: clock::Lamport,
12066 },
12067}
12068
12069impl EventEmitter<EditorEvent> for Editor {}
12070
12071impl FocusableView for Editor {
12072 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12073 self.focus_handle.clone()
12074 }
12075}
12076
12077impl Render for Editor {
12078 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12079 let settings = ThemeSettings::get_global(cx);
12080
12081 let text_style = match self.mode {
12082 EditorMode::SingleLine | EditorMode::AutoHeight { .. } => TextStyle {
12083 color: cx.theme().colors().editor_foreground,
12084 font_family: settings.ui_font.family.clone(),
12085 font_features: settings.ui_font.features.clone(),
12086 font_size: rems(0.875).into(),
12087 font_weight: settings.ui_font.weight,
12088 font_style: FontStyle::Normal,
12089 line_height: relative(settings.buffer_line_height.value()),
12090 background_color: None,
12091 underline: None,
12092 strikethrough: None,
12093 white_space: WhiteSpace::Normal,
12094 },
12095 EditorMode::Full => TextStyle {
12096 color: cx.theme().colors().editor_foreground,
12097 font_family: settings.buffer_font.family.clone(),
12098 font_features: settings.buffer_font.features.clone(),
12099 font_size: settings.buffer_font_size(cx).into(),
12100 font_weight: settings.buffer_font.weight,
12101 font_style: FontStyle::Normal,
12102 line_height: relative(settings.buffer_line_height.value()),
12103 background_color: None,
12104 underline: None,
12105 strikethrough: None,
12106 white_space: WhiteSpace::Normal,
12107 },
12108 };
12109
12110 let background = match self.mode {
12111 EditorMode::SingleLine => cx.theme().system().transparent,
12112 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12113 EditorMode::Full => cx.theme().colors().editor_background,
12114 };
12115
12116 EditorElement::new(
12117 cx.view(),
12118 EditorStyle {
12119 background,
12120 local_player: cx.theme().players().local(),
12121 text: text_style,
12122 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12123 syntax: cx.theme().syntax().clone(),
12124 status: cx.theme().status().clone(),
12125 inlay_hints_style: HighlightStyle {
12126 color: Some(cx.theme().status().hint),
12127 ..HighlightStyle::default()
12128 },
12129 suggestions_style: HighlightStyle {
12130 color: Some(cx.theme().status().predictive),
12131 ..HighlightStyle::default()
12132 },
12133 },
12134 )
12135 }
12136}
12137
12138impl ViewInputHandler for Editor {
12139 fn text_for_range(
12140 &mut self,
12141 range_utf16: Range<usize>,
12142 cx: &mut ViewContext<Self>,
12143 ) -> Option<String> {
12144 Some(
12145 self.buffer
12146 .read(cx)
12147 .read(cx)
12148 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12149 .collect(),
12150 )
12151 }
12152
12153 fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12154 // Prevent the IME menu from appearing when holding down an alphabetic key
12155 // while input is disabled.
12156 if !self.input_enabled {
12157 return None;
12158 }
12159
12160 let range = self.selections.newest::<OffsetUtf16>(cx).range();
12161 Some(range.start.0..range.end.0)
12162 }
12163
12164 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12165 let snapshot = self.buffer.read(cx).read(cx);
12166 let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
12167 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12168 }
12169
12170 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12171 self.clear_highlights::<InputComposition>(cx);
12172 self.ime_transaction.take();
12173 }
12174
12175 fn replace_text_in_range(
12176 &mut self,
12177 range_utf16: Option<Range<usize>>,
12178 text: &str,
12179 cx: &mut ViewContext<Self>,
12180 ) {
12181 if !self.input_enabled {
12182 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12183 return;
12184 }
12185
12186 self.transact(cx, |this, cx| {
12187 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12188 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12189 Some(this.selection_replacement_ranges(range_utf16, cx))
12190 } else {
12191 this.marked_text_ranges(cx)
12192 };
12193
12194 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12195 let newest_selection_id = this.selections.newest_anchor().id;
12196 this.selections
12197 .all::<OffsetUtf16>(cx)
12198 .iter()
12199 .zip(ranges_to_replace.iter())
12200 .find_map(|(selection, range)| {
12201 if selection.id == newest_selection_id {
12202 Some(
12203 (range.start.0 as isize - selection.head().0 as isize)
12204 ..(range.end.0 as isize - selection.head().0 as isize),
12205 )
12206 } else {
12207 None
12208 }
12209 })
12210 });
12211
12212 cx.emit(EditorEvent::InputHandled {
12213 utf16_range_to_replace: range_to_replace,
12214 text: text.into(),
12215 });
12216
12217 if let Some(new_selected_ranges) = new_selected_ranges {
12218 this.change_selections(None, cx, |selections| {
12219 selections.select_ranges(new_selected_ranges)
12220 });
12221 this.backspace(&Default::default(), cx);
12222 }
12223
12224 this.handle_input(text, cx);
12225 });
12226
12227 if let Some(transaction) = self.ime_transaction {
12228 self.buffer.update(cx, |buffer, cx| {
12229 buffer.group_until_transaction(transaction, cx);
12230 });
12231 }
12232
12233 self.unmark_text(cx);
12234 }
12235
12236 fn replace_and_mark_text_in_range(
12237 &mut self,
12238 range_utf16: Option<Range<usize>>,
12239 text: &str,
12240 new_selected_range_utf16: Option<Range<usize>>,
12241 cx: &mut ViewContext<Self>,
12242 ) {
12243 if !self.input_enabled {
12244 return;
12245 }
12246
12247 let transaction = self.transact(cx, |this, cx| {
12248 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12249 let snapshot = this.buffer.read(cx).read(cx);
12250 if let Some(relative_range_utf16) = range_utf16.as_ref() {
12251 for marked_range in &mut marked_ranges {
12252 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12253 marked_range.start.0 += relative_range_utf16.start;
12254 marked_range.start =
12255 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12256 marked_range.end =
12257 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12258 }
12259 }
12260 Some(marked_ranges)
12261 } else if let Some(range_utf16) = range_utf16 {
12262 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12263 Some(this.selection_replacement_ranges(range_utf16, cx))
12264 } else {
12265 None
12266 };
12267
12268 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12269 let newest_selection_id = this.selections.newest_anchor().id;
12270 this.selections
12271 .all::<OffsetUtf16>(cx)
12272 .iter()
12273 .zip(ranges_to_replace.iter())
12274 .find_map(|(selection, range)| {
12275 if selection.id == newest_selection_id {
12276 Some(
12277 (range.start.0 as isize - selection.head().0 as isize)
12278 ..(range.end.0 as isize - selection.head().0 as isize),
12279 )
12280 } else {
12281 None
12282 }
12283 })
12284 });
12285
12286 cx.emit(EditorEvent::InputHandled {
12287 utf16_range_to_replace: range_to_replace,
12288 text: text.into(),
12289 });
12290
12291 if let Some(ranges) = ranges_to_replace {
12292 this.change_selections(None, cx, |s| s.select_ranges(ranges));
12293 }
12294
12295 let marked_ranges = {
12296 let snapshot = this.buffer.read(cx).read(cx);
12297 this.selections
12298 .disjoint_anchors()
12299 .iter()
12300 .map(|selection| {
12301 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12302 })
12303 .collect::<Vec<_>>()
12304 };
12305
12306 if text.is_empty() {
12307 this.unmark_text(cx);
12308 } else {
12309 this.highlight_text::<InputComposition>(
12310 marked_ranges.clone(),
12311 HighlightStyle {
12312 underline: Some(UnderlineStyle {
12313 thickness: px(1.),
12314 color: None,
12315 wavy: false,
12316 }),
12317 ..Default::default()
12318 },
12319 cx,
12320 );
12321 }
12322
12323 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12324 let use_autoclose = this.use_autoclose;
12325 let use_auto_surround = this.use_auto_surround;
12326 this.set_use_autoclose(false);
12327 this.set_use_auto_surround(false);
12328 this.handle_input(text, cx);
12329 this.set_use_autoclose(use_autoclose);
12330 this.set_use_auto_surround(use_auto_surround);
12331
12332 if let Some(new_selected_range) = new_selected_range_utf16 {
12333 let snapshot = this.buffer.read(cx).read(cx);
12334 let new_selected_ranges = marked_ranges
12335 .into_iter()
12336 .map(|marked_range| {
12337 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
12338 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
12339 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
12340 snapshot.clip_offset_utf16(new_start, Bias::Left)
12341 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
12342 })
12343 .collect::<Vec<_>>();
12344
12345 drop(snapshot);
12346 this.change_selections(None, cx, |selections| {
12347 selections.select_ranges(new_selected_ranges)
12348 });
12349 }
12350 });
12351
12352 self.ime_transaction = self.ime_transaction.or(transaction);
12353 if let Some(transaction) = self.ime_transaction {
12354 self.buffer.update(cx, |buffer, cx| {
12355 buffer.group_until_transaction(transaction, cx);
12356 });
12357 }
12358
12359 if self.text_highlights::<InputComposition>(cx).is_none() {
12360 self.ime_transaction.take();
12361 }
12362 }
12363
12364 fn bounds_for_range(
12365 &mut self,
12366 range_utf16: Range<usize>,
12367 element_bounds: gpui::Bounds<Pixels>,
12368 cx: &mut ViewContext<Self>,
12369 ) -> Option<gpui::Bounds<Pixels>> {
12370 let text_layout_details = self.text_layout_details(cx);
12371 let style = &text_layout_details.editor_style;
12372 let font_id = cx.text_system().resolve_font(&style.text.font());
12373 let font_size = style.text.font_size.to_pixels(cx.rem_size());
12374 let line_height = style.text.line_height_in_pixels(cx.rem_size());
12375 let em_width = cx
12376 .text_system()
12377 .typographic_bounds(font_id, font_size, 'm')
12378 .unwrap()
12379 .size
12380 .width;
12381
12382 let snapshot = self.snapshot(cx);
12383 let scroll_position = snapshot.scroll_position();
12384 let scroll_left = scroll_position.x * em_width;
12385
12386 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
12387 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
12388 + self.gutter_dimensions.width;
12389 let y = line_height * (start.row().as_f32() - scroll_position.y);
12390
12391 Some(Bounds {
12392 origin: element_bounds.origin + point(x, y),
12393 size: size(em_width, line_height),
12394 })
12395 }
12396}
12397
12398trait SelectionExt {
12399 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
12400 fn spanned_rows(
12401 &self,
12402 include_end_if_at_line_start: bool,
12403 map: &DisplaySnapshot,
12404 ) -> Range<MultiBufferRow>;
12405}
12406
12407impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
12408 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
12409 let start = self
12410 .start
12411 .to_point(&map.buffer_snapshot)
12412 .to_display_point(map);
12413 let end = self
12414 .end
12415 .to_point(&map.buffer_snapshot)
12416 .to_display_point(map);
12417 if self.reversed {
12418 end..start
12419 } else {
12420 start..end
12421 }
12422 }
12423
12424 fn spanned_rows(
12425 &self,
12426 include_end_if_at_line_start: bool,
12427 map: &DisplaySnapshot,
12428 ) -> Range<MultiBufferRow> {
12429 let start = self.start.to_point(&map.buffer_snapshot);
12430 let mut end = self.end.to_point(&map.buffer_snapshot);
12431 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
12432 end.row -= 1;
12433 }
12434
12435 let buffer_start = map.prev_line_boundary(start).0;
12436 let buffer_end = map.next_line_boundary(end).0;
12437 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
12438 }
12439}
12440
12441impl<T: InvalidationRegion> InvalidationStack<T> {
12442 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
12443 where
12444 S: Clone + ToOffset,
12445 {
12446 while let Some(region) = self.last() {
12447 let all_selections_inside_invalidation_ranges =
12448 if selections.len() == region.ranges().len() {
12449 selections
12450 .iter()
12451 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
12452 .all(|(selection, invalidation_range)| {
12453 let head = selection.head().to_offset(buffer);
12454 invalidation_range.start <= head && invalidation_range.end >= head
12455 })
12456 } else {
12457 false
12458 };
12459
12460 if all_selections_inside_invalidation_ranges {
12461 break;
12462 } else {
12463 self.pop();
12464 }
12465 }
12466 }
12467}
12468
12469impl<T> Default for InvalidationStack<T> {
12470 fn default() -> Self {
12471 Self(Default::default())
12472 }
12473}
12474
12475impl<T> Deref for InvalidationStack<T> {
12476 type Target = Vec<T>;
12477
12478 fn deref(&self) -> &Self::Target {
12479 &self.0
12480 }
12481}
12482
12483impl<T> DerefMut for InvalidationStack<T> {
12484 fn deref_mut(&mut self) -> &mut Self::Target {
12485 &mut self.0
12486 }
12487}
12488
12489impl InvalidationRegion for SnippetState {
12490 fn ranges(&self) -> &[Range<Anchor>] {
12491 &self.ranges[self.active_index]
12492 }
12493}
12494
12495pub fn diagnostic_block_renderer(diagnostic: Diagnostic, _is_valid: bool) -> RenderBlock {
12496 let (text_without_backticks, code_ranges) = highlight_diagnostic_message(&diagnostic);
12497
12498 Box::new(move |cx: &mut BlockContext| {
12499 let group_id: SharedString = cx.block_id.to_string().into();
12500
12501 let mut text_style = cx.text_style().clone();
12502 text_style.color = diagnostic_style(diagnostic.severity, true, cx.theme().status());
12503 let theme_settings = ThemeSettings::get_global(cx);
12504 text_style.font_family = theme_settings.buffer_font.family.clone();
12505 text_style.font_style = theme_settings.buffer_font.style;
12506 text_style.font_features = theme_settings.buffer_font.features.clone();
12507 text_style.font_weight = theme_settings.buffer_font.weight;
12508
12509 let multi_line_diagnostic = diagnostic.message.contains('\n');
12510
12511 let buttons = |diagnostic: &Diagnostic, block_id: usize| {
12512 if multi_line_diagnostic {
12513 v_flex()
12514 } else {
12515 h_flex()
12516 }
12517 .children(diagnostic.is_primary.then(|| {
12518 IconButton::new(("close-block", block_id), IconName::XCircle)
12519 .icon_color(Color::Muted)
12520 .size(ButtonSize::Compact)
12521 .style(ButtonStyle::Transparent)
12522 .visible_on_hover(group_id.clone())
12523 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
12524 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
12525 }))
12526 .child(
12527 IconButton::new(("copy-block", block_id), IconName::Copy)
12528 .icon_color(Color::Muted)
12529 .size(ButtonSize::Compact)
12530 .style(ButtonStyle::Transparent)
12531 .visible_on_hover(group_id.clone())
12532 .on_click({
12533 let message = diagnostic.message.clone();
12534 move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
12535 })
12536 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
12537 )
12538 };
12539
12540 let icon_size = buttons(&diagnostic, cx.block_id)
12541 .into_any_element()
12542 .layout_as_root(AvailableSpace::min_size(), cx);
12543
12544 h_flex()
12545 .id(cx.block_id)
12546 .group(group_id.clone())
12547 .relative()
12548 .size_full()
12549 .pl(cx.gutter_dimensions.width)
12550 .w(cx.max_width + cx.gutter_dimensions.width)
12551 .child(
12552 div()
12553 .flex()
12554 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
12555 .flex_shrink(),
12556 )
12557 .child(buttons(&diagnostic, cx.block_id))
12558 .child(div().flex().flex_shrink_0().child(
12559 StyledText::new(text_without_backticks.clone()).with_highlights(
12560 &text_style,
12561 code_ranges.iter().map(|range| {
12562 (
12563 range.clone(),
12564 HighlightStyle {
12565 font_weight: Some(FontWeight::BOLD),
12566 ..Default::default()
12567 },
12568 )
12569 }),
12570 ),
12571 ))
12572 .into_any_element()
12573 })
12574}
12575
12576pub fn highlight_diagnostic_message(diagnostic: &Diagnostic) -> (SharedString, Vec<Range<usize>>) {
12577 let mut text_without_backticks = String::new();
12578 let mut code_ranges = Vec::new();
12579
12580 if let Some(source) = &diagnostic.source {
12581 text_without_backticks.push_str(&source);
12582 code_ranges.push(0..source.len());
12583 text_without_backticks.push_str(": ");
12584 }
12585
12586 let mut prev_offset = 0;
12587 let mut in_code_block = false;
12588 for (ix, _) in diagnostic
12589 .message
12590 .match_indices('`')
12591 .chain([(diagnostic.message.len(), "")])
12592 {
12593 let prev_len = text_without_backticks.len();
12594 text_without_backticks.push_str(&diagnostic.message[prev_offset..ix]);
12595 prev_offset = ix + 1;
12596 if in_code_block {
12597 code_ranges.push(prev_len..text_without_backticks.len());
12598 in_code_block = false;
12599 } else {
12600 in_code_block = true;
12601 }
12602 }
12603
12604 (text_without_backticks.into(), code_ranges)
12605}
12606
12607fn diagnostic_style(severity: DiagnosticSeverity, valid: bool, colors: &StatusColors) -> Hsla {
12608 match (severity, valid) {
12609 (DiagnosticSeverity::ERROR, true) => colors.error,
12610 (DiagnosticSeverity::ERROR, false) => colors.error,
12611 (DiagnosticSeverity::WARNING, true) => colors.warning,
12612 (DiagnosticSeverity::WARNING, false) => colors.warning,
12613 (DiagnosticSeverity::INFORMATION, true) => colors.info,
12614 (DiagnosticSeverity::INFORMATION, false) => colors.info,
12615 (DiagnosticSeverity::HINT, true) => colors.info,
12616 (DiagnosticSeverity::HINT, false) => colors.info,
12617 _ => colors.ignored,
12618 }
12619}
12620
12621pub fn styled_runs_for_code_label<'a>(
12622 label: &'a CodeLabel,
12623 syntax_theme: &'a theme::SyntaxTheme,
12624) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
12625 let fade_out = HighlightStyle {
12626 fade_out: Some(0.35),
12627 ..Default::default()
12628 };
12629
12630 let mut prev_end = label.filter_range.end;
12631 label
12632 .runs
12633 .iter()
12634 .enumerate()
12635 .flat_map(move |(ix, (range, highlight_id))| {
12636 let style = if let Some(style) = highlight_id.style(syntax_theme) {
12637 style
12638 } else {
12639 return Default::default();
12640 };
12641 let mut muted_style = style;
12642 muted_style.highlight(fade_out);
12643
12644 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
12645 if range.start >= label.filter_range.end {
12646 if range.start > prev_end {
12647 runs.push((prev_end..range.start, fade_out));
12648 }
12649 runs.push((range.clone(), muted_style));
12650 } else if range.end <= label.filter_range.end {
12651 runs.push((range.clone(), style));
12652 } else {
12653 runs.push((range.start..label.filter_range.end, style));
12654 runs.push((label.filter_range.end..range.end, muted_style));
12655 }
12656 prev_end = cmp::max(prev_end, range.end);
12657
12658 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
12659 runs.push((prev_end..label.text.len(), fade_out));
12660 }
12661
12662 runs
12663 })
12664}
12665
12666pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
12667 let mut prev_index = 0;
12668 let mut prev_codepoint: Option<char> = None;
12669 text.char_indices()
12670 .chain([(text.len(), '\0')])
12671 .filter_map(move |(index, codepoint)| {
12672 let prev_codepoint = prev_codepoint.replace(codepoint)?;
12673 let is_boundary = index == text.len()
12674 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
12675 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
12676 if is_boundary {
12677 let chunk = &text[prev_index..index];
12678 prev_index = index;
12679 Some(chunk)
12680 } else {
12681 None
12682 }
12683 })
12684}
12685
12686trait RangeToAnchorExt {
12687 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
12688}
12689
12690impl<T: ToOffset> RangeToAnchorExt for Range<T> {
12691 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
12692 let start_offset = self.start.to_offset(snapshot);
12693 let end_offset = self.end.to_offset(snapshot);
12694 if start_offset == end_offset {
12695 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
12696 } else {
12697 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
12698 }
12699 }
12700}
12701
12702pub trait RowExt {
12703 fn as_f32(&self) -> f32;
12704
12705 fn next_row(&self) -> Self;
12706
12707 fn previous_row(&self) -> Self;
12708
12709 fn minus(&self, other: Self) -> u32;
12710}
12711
12712impl RowExt for DisplayRow {
12713 fn as_f32(&self) -> f32 {
12714 self.0 as f32
12715 }
12716
12717 fn next_row(&self) -> Self {
12718 Self(self.0 + 1)
12719 }
12720
12721 fn previous_row(&self) -> Self {
12722 Self(self.0.saturating_sub(1))
12723 }
12724
12725 fn minus(&self, other: Self) -> u32 {
12726 self.0 - other.0
12727 }
12728}
12729
12730impl RowExt for MultiBufferRow {
12731 fn as_f32(&self) -> f32 {
12732 self.0 as f32
12733 }
12734
12735 fn next_row(&self) -> Self {
12736 Self(self.0 + 1)
12737 }
12738
12739 fn previous_row(&self) -> Self {
12740 Self(self.0.saturating_sub(1))
12741 }
12742
12743 fn minus(&self, other: Self) -> u32 {
12744 self.0 - other.0
12745 }
12746}
12747
12748trait RowRangeExt {
12749 type Row;
12750
12751 fn len(&self) -> usize;
12752
12753 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
12754}
12755
12756impl RowRangeExt for Range<MultiBufferRow> {
12757 type Row = MultiBufferRow;
12758
12759 fn len(&self) -> usize {
12760 (self.end.0 - self.start.0) as usize
12761 }
12762
12763 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
12764 (self.start.0..self.end.0).map(MultiBufferRow)
12765 }
12766}
12767
12768impl RowRangeExt for Range<DisplayRow> {
12769 type Row = DisplayRow;
12770
12771 fn len(&self) -> usize {
12772 (self.end.0 - self.start.0) as usize
12773 }
12774
12775 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
12776 (self.start.0..self.end.0).map(DisplayRow)
12777 }
12778}
12779
12780fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
12781 if hunk.diff_base_byte_range.is_empty() {
12782 DiffHunkStatus::Added
12783 } else if hunk.associated_range.is_empty() {
12784 DiffHunkStatus::Removed
12785 } else {
12786 DiffHunkStatus::Modified
12787 }
12788}