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