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