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