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 behavior.
15pub mod actions;
16mod blame_entry_tooltip;
17mod blink_manager;
18mod debounced_delay;
19pub mod display_map;
20mod editor_settings;
21mod editor_settings_controls;
22mod element;
23mod git;
24mod highlight_matching_bracket;
25mod hover_links;
26mod hover_popover;
27mod hunk_diff;
28mod indent_guides;
29mod inlay_hint_cache;
30mod inline_completion_provider;
31pub mod items;
32mod linked_editing_ranges;
33mod mouse_context_menu;
34pub mod movement;
35mod persistence;
36mod rust_analyzer_ext;
37pub mod scroll;
38mod selections_collection;
39pub mod tasks;
40
41#[cfg(test)]
42mod editor_tests;
43mod signature_help;
44#[cfg(any(test, feature = "test-support"))]
45pub mod test;
46
47use ::git::diff::{DiffHunk, DiffHunkStatus};
48use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
49pub(crate) use actions::*;
50use aho_corasick::AhoCorasick;
51use anyhow::{anyhow, Context as _, Result};
52use blink_manager::BlinkManager;
53use client::{Collaborator, ParticipantIndex};
54use clock::ReplicaId;
55use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
56use convert_case::{Case, Casing};
57use debounced_delay::DebouncedDelay;
58use display_map::*;
59pub use display_map::{DisplayPoint, FoldPlaceholder};
60pub use editor_settings::{CurrentLineHighlight, EditorSettings};
61pub use editor_settings_controls::*;
62use element::LineWithInvisibles;
63pub use element::{
64 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
65};
66use futures::FutureExt;
67use fuzzy::{StringMatch, StringMatchCandidate};
68use git::blame::GitBlame;
69use git::diff_hunk_to_display;
70use gpui::{
71 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
72 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardItem,
73 Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle, FocusOutEvent,
74 FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText, KeyContext,
75 ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString,
76 Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle, UnderlineStyle,
77 UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
78 WeakView, WindowContext,
79};
80use highlight_matching_bracket::refresh_matching_bracket_highlights;
81use hover_popover::{hide_hover, HoverState};
82use hunk_diff::ExpandedHunks;
83pub(crate) use hunk_diff::HoveredHunk;
84use indent_guides::ActiveIndentGuidesState;
85use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
86pub use inline_completion_provider::*;
87pub use items::MAX_TAB_TITLE_LEN;
88use itertools::Itertools;
89use language::{
90 char_kind,
91 language_settings::{self, all_language_settings, InlayHintSettings},
92 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
93 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
94 Point, Selection, SelectionGoal, TransactionId,
95};
96use language::{point_to_lsp, BufferRow, Runnable, RunnableRange};
97use linked_editing_ranges::refresh_linked_ranges;
98use task::{ResolvedTask, TaskTemplate, TaskVariables};
99
100use hover_links::{HoverLink, HoveredLinkState, InlayHighlight};
101pub use lsp::CompletionContext;
102use lsp::{
103 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
104 LanguageServerId,
105};
106use mouse_context_menu::MouseContextMenu;
107use movement::TextLayoutDetails;
108pub use multi_buffer::{
109 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
110 ToPoint,
111};
112use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
113use ordered_float::OrderedFloat;
114use parking_lot::{Mutex, RwLock};
115use project::project_settings::{GitGutterSetting, ProjectSettings};
116use project::{
117 CodeAction, Completion, FormatTrigger, Item, Location, Project, ProjectPath,
118 ProjectTransaction, TaskSourceKind, WorktreeId,
119};
120use rand::prelude::*;
121use rpc::{proto::*, ErrorExt};
122use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
123use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
124use serde::{Deserialize, Serialize};
125use settings::{update_settings_file, Settings, SettingsStore};
126use smallvec::SmallVec;
127use snippet::Snippet;
128use std::{
129 any::TypeId,
130 borrow::Cow,
131 cell::RefCell,
132 cmp::{self, Ordering, Reverse},
133 mem,
134 num::NonZeroU32,
135 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
136 path::{Path, PathBuf},
137 rc::Rc,
138 sync::Arc,
139 time::{Duration, Instant},
140};
141pub use sum_tree::Bias;
142use sum_tree::TreeMap;
143use text::{BufferId, OffsetUtf16, Rope};
144use theme::{
145 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
146 ThemeColors, ThemeSettings,
147};
148use ui::{
149 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
150 ListItem, Popover, Tooltip,
151};
152use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
153use workspace::item::{ItemHandle, PreviewTabsSettings};
154use workspace::notifications::{DetachAndPromptErr, NotificationId};
155use workspace::{
156 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
157};
158use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
159
160use crate::hover_links::find_url;
161use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
162
163pub const FILE_HEADER_HEIGHT: u32 = 1;
164pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
165pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
166pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
167const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
168const MAX_LINE_LEN: usize = 1024;
169const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
170const MAX_SELECTION_HISTORY_LEN: usize = 1024;
171pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
172#[doc(hidden)]
173pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
174#[doc(hidden)]
175pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
176
177pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
178
179pub fn render_parsed_markdown(
180 element_id: impl Into<ElementId>,
181 parsed: &language::ParsedMarkdown,
182 editor_style: &EditorStyle,
183 workspace: Option<WeakView<Workspace>>,
184 cx: &mut WindowContext,
185) -> InteractiveText {
186 let code_span_background_color = cx
187 .theme()
188 .colors()
189 .editor_document_highlight_read_background;
190
191 let highlights = gpui::combine_highlights(
192 parsed.highlights.iter().filter_map(|(range, highlight)| {
193 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
194 Some((range.clone(), highlight))
195 }),
196 parsed
197 .regions
198 .iter()
199 .zip(&parsed.region_ranges)
200 .filter_map(|(region, range)| {
201 if region.code {
202 Some((
203 range.clone(),
204 HighlightStyle {
205 background_color: Some(code_span_background_color),
206 ..Default::default()
207 },
208 ))
209 } else {
210 None
211 }
212 }),
213 );
214
215 let mut links = Vec::new();
216 let mut link_ranges = Vec::new();
217 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
218 if let Some(link) = region.link.clone() {
219 links.push(link);
220 link_ranges.push(range.clone());
221 }
222 }
223
224 InteractiveText::new(
225 element_id,
226 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
227 )
228 .on_click(link_ranges, move |clicked_range_ix, cx| {
229 match &links[clicked_range_ix] {
230 markdown::Link::Web { url } => cx.open_url(url),
231 markdown::Link::Path { path } => {
232 if let Some(workspace) = &workspace {
233 _ = workspace.update(cx, |workspace, cx| {
234 workspace.open_abs_path(path.clone(), false, cx).detach();
235 });
236 }
237 }
238 }
239 })
240}
241
242#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
243pub(crate) enum InlayId {
244 Suggestion(usize),
245 Hint(usize),
246}
247
248impl InlayId {
249 fn id(&self) -> usize {
250 match self {
251 Self::Suggestion(id) => *id,
252 Self::Hint(id) => *id,
253 }
254 }
255}
256
257enum DiffRowHighlight {}
258enum DocumentHighlightRead {}
259enum DocumentHighlightWrite {}
260enum InputComposition {}
261
262#[derive(Copy, Clone, PartialEq, Eq)]
263pub enum Direction {
264 Prev,
265 Next,
266}
267
268pub fn init_settings(cx: &mut AppContext) {
269 EditorSettings::register(cx);
270}
271
272pub fn init(cx: &mut AppContext) {
273 init_settings(cx);
274
275 workspace::register_project_item::<Editor>(cx);
276 workspace::FollowableViewRegistry::register::<Editor>(cx);
277 workspace::register_serializable_item::<Editor>(cx);
278
279 cx.observe_new_views(
280 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
281 workspace.register_action(Editor::new_file);
282 workspace.register_action(Editor::new_file_in_direction);
283 },
284 )
285 .detach();
286
287 cx.on_action(move |_: &workspace::NewFile, 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 cx.on_action(move |_: &workspace::NewWindow, cx| {
297 let app_state = workspace::AppState::global(cx);
298 if let Some(app_state) = app_state.upgrade() {
299 workspace::open_new(app_state, cx, |workspace, cx| {
300 Editor::new_file(workspace, &Default::default(), cx)
301 })
302 .detach();
303 }
304 });
305}
306
307pub struct SearchWithinRange;
308
309trait InvalidationRegion {
310 fn ranges(&self) -> &[Range<Anchor>];
311}
312
313#[derive(Clone, Debug, PartialEq)]
314pub enum SelectPhase {
315 Begin {
316 position: DisplayPoint,
317 add: bool,
318 click_count: usize,
319 },
320 BeginColumnar {
321 position: DisplayPoint,
322 reset: bool,
323 goal_column: u32,
324 },
325 Extend {
326 position: DisplayPoint,
327 click_count: usize,
328 },
329 Update {
330 position: DisplayPoint,
331 goal_column: u32,
332 scroll_delta: gpui::Point<f32>,
333 },
334 End,
335}
336
337#[derive(Clone, Debug)]
338pub enum SelectMode {
339 Character,
340 Word(Range<Anchor>),
341 Line(Range<Anchor>),
342 All,
343}
344
345#[derive(Copy, Clone, PartialEq, Eq, Debug)]
346pub enum EditorMode {
347 SingleLine { auto_width: bool },
348 AutoHeight { max_lines: usize },
349 Full,
350}
351
352#[derive(Clone, Debug)]
353pub enum SoftWrap {
354 None,
355 PreferLine,
356 EditorWidth,
357 Column(u32),
358}
359
360#[derive(Clone)]
361pub struct EditorStyle {
362 pub background: Hsla,
363 pub local_player: PlayerColor,
364 pub text: TextStyle,
365 pub scrollbar_width: Pixels,
366 pub syntax: Arc<SyntaxTheme>,
367 pub status: StatusColors,
368 pub inlay_hints_style: HighlightStyle,
369 pub suggestions_style: HighlightStyle,
370}
371
372impl Default for EditorStyle {
373 fn default() -> Self {
374 Self {
375 background: Hsla::default(),
376 local_player: PlayerColor::default(),
377 text: TextStyle::default(),
378 scrollbar_width: Pixels::default(),
379 syntax: Default::default(),
380 // HACK: Status colors don't have a real default.
381 // We should look into removing the status colors from the editor
382 // style and retrieve them directly from the theme.
383 status: StatusColors::dark(),
384 inlay_hints_style: HighlightStyle::default(),
385 suggestions_style: HighlightStyle::default(),
386 }
387 }
388}
389
390type CompletionId = usize;
391
392#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
393struct EditorActionId(usize);
394
395impl EditorActionId {
396 pub fn post_inc(&mut self) -> Self {
397 let answer = self.0;
398
399 *self = Self(answer + 1);
400
401 Self(answer)
402 }
403}
404
405// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
406// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
407
408type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
409type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
410
411#[derive(Default)]
412struct ScrollbarMarkerState {
413 scrollbar_size: Size<Pixels>,
414 dirty: bool,
415 markers: Arc<[PaintQuad]>,
416 pending_refresh: Option<Task<Result<()>>>,
417}
418
419impl ScrollbarMarkerState {
420 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
421 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
422 }
423}
424
425#[derive(Clone, Debug)]
426struct RunnableTasks {
427 templates: Vec<(TaskSourceKind, TaskTemplate)>,
428 offset: MultiBufferOffset,
429 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
430 column: u32,
431 // Values of all named captures, including those starting with '_'
432 extra_variables: HashMap<String, String>,
433 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
434 context_range: Range<BufferOffset>,
435}
436
437#[derive(Clone)]
438struct ResolvedTasks {
439 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
440 position: Anchor,
441}
442#[derive(Copy, Clone, Debug)]
443struct MultiBufferOffset(usize);
444#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
445struct BufferOffset(usize);
446/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
447///
448/// See the [module level documentation](self) for more information.
449pub struct Editor {
450 focus_handle: FocusHandle,
451 last_focused_descendant: Option<WeakFocusHandle>,
452 /// The text buffer being edited
453 buffer: Model<MultiBuffer>,
454 /// Map of how text in the buffer should be displayed.
455 /// Handles soft wraps, folds, fake inlay text insertions, etc.
456 pub display_map: Model<DisplayMap>,
457 pub selections: SelectionsCollection,
458 pub scroll_manager: ScrollManager,
459 /// When inline assist editors are linked, they all render cursors because
460 /// typing enters text into each of them, even the ones that aren't focused.
461 pub(crate) show_cursor_when_unfocused: bool,
462 columnar_selection_tail: Option<Anchor>,
463 add_selections_state: Option<AddSelectionsState>,
464 select_next_state: Option<SelectNextState>,
465 select_prev_state: Option<SelectNextState>,
466 selection_history: SelectionHistory,
467 autoclose_regions: Vec<AutocloseRegion>,
468 snippet_stack: InvalidationStack<SnippetState>,
469 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
470 ime_transaction: Option<TransactionId>,
471 active_diagnostics: Option<ActiveDiagnosticGroup>,
472 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
473 project: Option<Model<Project>>,
474 completion_provider: Option<Box<dyn CompletionProvider>>,
475 collaboration_hub: Option<Box<dyn CollaborationHub>>,
476 blink_manager: Model<BlinkManager>,
477 show_cursor_names: bool,
478 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
479 pub show_local_selections: bool,
480 mode: EditorMode,
481 show_breadcrumbs: bool,
482 show_gutter: bool,
483 show_line_numbers: Option<bool>,
484 show_git_diff_gutter: Option<bool>,
485 show_code_actions: Option<bool>,
486 show_runnables: Option<bool>,
487 show_wrap_guides: Option<bool>,
488 show_indent_guides: Option<bool>,
489 placeholder_text: Option<Arc<str>>,
490 highlight_order: usize,
491 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
492 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
493 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
494 scrollbar_marker_state: ScrollbarMarkerState,
495 active_indent_guides_state: ActiveIndentGuidesState,
496 nav_history: Option<ItemNavHistory>,
497 context_menu: RwLock<Option<ContextMenu>>,
498 mouse_context_menu: Option<MouseContextMenu>,
499 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
500 signature_help_state: SignatureHelpState,
501 auto_signature_help: Option<bool>,
502 find_all_references_task_sources: Vec<Anchor>,
503 next_completion_id: CompletionId,
504 completion_documentation_pre_resolve_debounce: DebouncedDelay,
505 available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
506 code_actions_task: Option<Task<()>>,
507 document_highlights_task: Option<Task<()>>,
508 linked_editing_range_task: Option<Task<Option<()>>>,
509 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
510 pending_rename: Option<RenameState>,
511 searchable: bool,
512 cursor_shape: CursorShape,
513 current_line_highlight: Option<CurrentLineHighlight>,
514 collapse_matches: bool,
515 autoindent_mode: Option<AutoindentMode>,
516 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
517 keymap_context_layers: BTreeMap<TypeId, KeyContext>,
518 input_enabled: bool,
519 use_modal_editing: bool,
520 read_only: bool,
521 leader_peer_id: Option<PeerId>,
522 remote_id: Option<ViewId>,
523 hover_state: HoverState,
524 gutter_hovered: bool,
525 hovered_link_state: Option<HoveredLinkState>,
526 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
527 active_inline_completion: Option<(Inlay, Option<Range<Anchor>>)>,
528 show_inline_completions: bool,
529 inlay_hint_cache: InlayHintCache,
530 expanded_hunks: ExpandedHunks,
531 next_inlay_id: usize,
532 _subscriptions: Vec<Subscription>,
533 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
534 gutter_dimensions: GutterDimensions,
535 pub vim_replace_map: HashMap<Range<usize>, String>,
536 style: Option<EditorStyle>,
537 next_editor_action_id: EditorActionId,
538 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
539 use_autoclose: bool,
540 use_auto_surround: bool,
541 auto_replace_emoji_shortcode: bool,
542 show_git_blame_gutter: bool,
543 show_git_blame_inline: bool,
544 show_git_blame_inline_delay_task: Option<Task<()>>,
545 git_blame_inline_enabled: bool,
546 serialize_dirty_buffers: bool,
547 show_selection_menu: Option<bool>,
548 blame: Option<Model<GitBlame>>,
549 blame_subscription: Option<Subscription>,
550 custom_context_menu: Option<
551 Box<
552 dyn 'static
553 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
554 >,
555 >,
556 last_bounds: Option<Bounds<Pixels>>,
557 expect_bounds_change: Option<Bounds<Pixels>>,
558 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
559 tasks_update_task: Option<Task<()>>,
560 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
561 file_header_size: u32,
562 breadcrumb_header: Option<String>,
563 focused_block: Option<FocusedBlock>,
564}
565
566#[derive(Clone)]
567pub struct EditorSnapshot {
568 pub mode: EditorMode,
569 show_gutter: bool,
570 show_line_numbers: Option<bool>,
571 show_git_diff_gutter: Option<bool>,
572 show_code_actions: Option<bool>,
573 show_runnables: Option<bool>,
574 render_git_blame_gutter: bool,
575 pub display_snapshot: DisplaySnapshot,
576 pub placeholder_text: Option<Arc<str>>,
577 is_focused: bool,
578 scroll_anchor: ScrollAnchor,
579 ongoing_scroll: OngoingScroll,
580 current_line_highlight: CurrentLineHighlight,
581 gutter_hovered: bool,
582}
583
584const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
585
586#[derive(Default, Debug, Clone, Copy)]
587pub struct GutterDimensions {
588 pub left_padding: Pixels,
589 pub right_padding: Pixels,
590 pub width: Pixels,
591 pub margin: Pixels,
592 pub git_blame_entries_width: Option<Pixels>,
593}
594
595impl GutterDimensions {
596 /// The full width of the space taken up by the gutter.
597 pub fn full_width(&self) -> Pixels {
598 self.margin + self.width
599 }
600
601 /// The width of the space reserved for the fold indicators,
602 /// use alongside 'justify_end' and `gutter_width` to
603 /// right align content with the line numbers
604 pub fn fold_area_width(&self) -> Pixels {
605 self.margin + self.right_padding
606 }
607}
608
609#[derive(Debug)]
610pub struct RemoteSelection {
611 pub replica_id: ReplicaId,
612 pub selection: Selection<Anchor>,
613 pub cursor_shape: CursorShape,
614 pub peer_id: PeerId,
615 pub line_mode: bool,
616 pub participant_index: Option<ParticipantIndex>,
617 pub user_name: Option<SharedString>,
618}
619
620#[derive(Clone, Debug)]
621struct SelectionHistoryEntry {
622 selections: Arc<[Selection<Anchor>]>,
623 select_next_state: Option<SelectNextState>,
624 select_prev_state: Option<SelectNextState>,
625 add_selections_state: Option<AddSelectionsState>,
626}
627
628enum SelectionHistoryMode {
629 Normal,
630 Undoing,
631 Redoing,
632}
633
634#[derive(Clone, PartialEq, Eq, Hash)]
635struct HoveredCursor {
636 replica_id: u16,
637 selection_id: usize,
638}
639
640impl Default for SelectionHistoryMode {
641 fn default() -> Self {
642 Self::Normal
643 }
644}
645
646#[derive(Default)]
647struct SelectionHistory {
648 #[allow(clippy::type_complexity)]
649 selections_by_transaction:
650 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
651 mode: SelectionHistoryMode,
652 undo_stack: VecDeque<SelectionHistoryEntry>,
653 redo_stack: VecDeque<SelectionHistoryEntry>,
654}
655
656impl SelectionHistory {
657 fn insert_transaction(
658 &mut self,
659 transaction_id: TransactionId,
660 selections: Arc<[Selection<Anchor>]>,
661 ) {
662 self.selections_by_transaction
663 .insert(transaction_id, (selections, None));
664 }
665
666 #[allow(clippy::type_complexity)]
667 fn transaction(
668 &self,
669 transaction_id: TransactionId,
670 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
671 self.selections_by_transaction.get(&transaction_id)
672 }
673
674 #[allow(clippy::type_complexity)]
675 fn transaction_mut(
676 &mut self,
677 transaction_id: TransactionId,
678 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
679 self.selections_by_transaction.get_mut(&transaction_id)
680 }
681
682 fn push(&mut self, entry: SelectionHistoryEntry) {
683 if !entry.selections.is_empty() {
684 match self.mode {
685 SelectionHistoryMode::Normal => {
686 self.push_undo(entry);
687 self.redo_stack.clear();
688 }
689 SelectionHistoryMode::Undoing => self.push_redo(entry),
690 SelectionHistoryMode::Redoing => self.push_undo(entry),
691 }
692 }
693 }
694
695 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
696 if self
697 .undo_stack
698 .back()
699 .map_or(true, |e| e.selections != entry.selections)
700 {
701 self.undo_stack.push_back(entry);
702 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
703 self.undo_stack.pop_front();
704 }
705 }
706 }
707
708 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
709 if self
710 .redo_stack
711 .back()
712 .map_or(true, |e| e.selections != entry.selections)
713 {
714 self.redo_stack.push_back(entry);
715 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
716 self.redo_stack.pop_front();
717 }
718 }
719 }
720}
721
722struct RowHighlight {
723 index: usize,
724 range: RangeInclusive<Anchor>,
725 color: Option<Hsla>,
726 should_autoscroll: bool,
727}
728
729#[derive(Clone, Debug)]
730struct AddSelectionsState {
731 above: bool,
732 stack: Vec<usize>,
733}
734
735#[derive(Clone)]
736struct SelectNextState {
737 query: AhoCorasick,
738 wordwise: bool,
739 done: bool,
740}
741
742impl std::fmt::Debug for SelectNextState {
743 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
744 f.debug_struct(std::any::type_name::<Self>())
745 .field("wordwise", &self.wordwise)
746 .field("done", &self.done)
747 .finish()
748 }
749}
750
751#[derive(Debug)]
752struct AutocloseRegion {
753 selection_id: usize,
754 range: Range<Anchor>,
755 pair: BracketPair,
756}
757
758#[derive(Debug)]
759struct SnippetState {
760 ranges: Vec<Vec<Range<Anchor>>>,
761 active_index: usize,
762}
763
764#[doc(hidden)]
765pub struct RenameState {
766 pub range: Range<Anchor>,
767 pub old_name: Arc<str>,
768 pub editor: View<Editor>,
769 block_id: CustomBlockId,
770}
771
772struct InvalidationStack<T>(Vec<T>);
773
774struct RegisteredInlineCompletionProvider {
775 provider: Arc<dyn InlineCompletionProviderHandle>,
776 _subscription: Subscription,
777}
778
779enum ContextMenu {
780 Completions(CompletionsMenu),
781 CodeActions(CodeActionsMenu),
782}
783
784impl ContextMenu {
785 fn select_first(
786 &mut self,
787 project: Option<&Model<Project>>,
788 cx: &mut ViewContext<Editor>,
789 ) -> bool {
790 if self.visible() {
791 match self {
792 ContextMenu::Completions(menu) => menu.select_first(project, cx),
793 ContextMenu::CodeActions(menu) => menu.select_first(cx),
794 }
795 true
796 } else {
797 false
798 }
799 }
800
801 fn select_prev(
802 &mut self,
803 project: Option<&Model<Project>>,
804 cx: &mut ViewContext<Editor>,
805 ) -> bool {
806 if self.visible() {
807 match self {
808 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
809 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
810 }
811 true
812 } else {
813 false
814 }
815 }
816
817 fn select_next(
818 &mut self,
819 project: Option<&Model<Project>>,
820 cx: &mut ViewContext<Editor>,
821 ) -> bool {
822 if self.visible() {
823 match self {
824 ContextMenu::Completions(menu) => menu.select_next(project, cx),
825 ContextMenu::CodeActions(menu) => menu.select_next(cx),
826 }
827 true
828 } else {
829 false
830 }
831 }
832
833 fn select_last(
834 &mut self,
835 project: Option<&Model<Project>>,
836 cx: &mut ViewContext<Editor>,
837 ) -> bool {
838 if self.visible() {
839 match self {
840 ContextMenu::Completions(menu) => menu.select_last(project, cx),
841 ContextMenu::CodeActions(menu) => menu.select_last(cx),
842 }
843 true
844 } else {
845 false
846 }
847 }
848
849 fn visible(&self) -> bool {
850 match self {
851 ContextMenu::Completions(menu) => menu.visible(),
852 ContextMenu::CodeActions(menu) => menu.visible(),
853 }
854 }
855
856 fn render(
857 &self,
858 cursor_position: DisplayPoint,
859 style: &EditorStyle,
860 max_height: Pixels,
861 workspace: Option<WeakView<Workspace>>,
862 cx: &mut ViewContext<Editor>,
863 ) -> (ContextMenuOrigin, AnyElement) {
864 match self {
865 ContextMenu::Completions(menu) => (
866 ContextMenuOrigin::EditorPoint(cursor_position),
867 menu.render(style, max_height, workspace, cx),
868 ),
869 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
870 }
871 }
872}
873
874enum ContextMenuOrigin {
875 EditorPoint(DisplayPoint),
876 GutterIndicator(DisplayRow),
877}
878
879#[derive(Clone)]
880struct CompletionsMenu {
881 id: CompletionId,
882 initial_position: Anchor,
883 buffer: Model<Buffer>,
884 completions: Arc<RwLock<Box<[Completion]>>>,
885 match_candidates: Arc<[StringMatchCandidate]>,
886 matches: Arc<[StringMatch]>,
887 selected_item: usize,
888 scroll_handle: UniformListScrollHandle,
889 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
890}
891
892impl CompletionsMenu {
893 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
894 self.selected_item = 0;
895 self.scroll_handle.scroll_to_item(self.selected_item);
896 self.attempt_resolve_selected_completion_documentation(project, cx);
897 cx.notify();
898 }
899
900 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
901 if self.selected_item > 0 {
902 self.selected_item -= 1;
903 } else {
904 self.selected_item = self.matches.len() - 1;
905 }
906 self.scroll_handle.scroll_to_item(self.selected_item);
907 self.attempt_resolve_selected_completion_documentation(project, cx);
908 cx.notify();
909 }
910
911 fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
912 if self.selected_item + 1 < self.matches.len() {
913 self.selected_item += 1;
914 } else {
915 self.selected_item = 0;
916 }
917 self.scroll_handle.scroll_to_item(self.selected_item);
918 self.attempt_resolve_selected_completion_documentation(project, cx);
919 cx.notify();
920 }
921
922 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
923 self.selected_item = self.matches.len() - 1;
924 self.scroll_handle.scroll_to_item(self.selected_item);
925 self.attempt_resolve_selected_completion_documentation(project, cx);
926 cx.notify();
927 }
928
929 fn pre_resolve_completion_documentation(
930 buffer: Model<Buffer>,
931 completions: Arc<RwLock<Box<[Completion]>>>,
932 matches: Arc<[StringMatch]>,
933 editor: &Editor,
934 cx: &mut ViewContext<Editor>,
935 ) -> Task<()> {
936 let settings = EditorSettings::get_global(cx);
937 if !settings.show_completion_documentation {
938 return Task::ready(());
939 }
940
941 let Some(provider) = editor.completion_provider.as_ref() else {
942 return Task::ready(());
943 };
944
945 let resolve_task = provider.resolve_completions(
946 buffer,
947 matches.iter().map(|m| m.candidate_id).collect(),
948 completions.clone(),
949 cx,
950 );
951
952 return cx.spawn(move |this, mut cx| async move {
953 if let Some(true) = resolve_task.await.log_err() {
954 this.update(&mut cx, |_, cx| cx.notify()).ok();
955 }
956 });
957 }
958
959 fn attempt_resolve_selected_completion_documentation(
960 &mut self,
961 project: Option<&Model<Project>>,
962 cx: &mut ViewContext<Editor>,
963 ) {
964 let settings = EditorSettings::get_global(cx);
965 if !settings.show_completion_documentation {
966 return;
967 }
968
969 let completion_index = self.matches[self.selected_item].candidate_id;
970 let Some(project) = project else {
971 return;
972 };
973
974 let resolve_task = project.update(cx, |project, cx| {
975 project.resolve_completions(
976 self.buffer.clone(),
977 vec![completion_index],
978 self.completions.clone(),
979 cx,
980 )
981 });
982
983 let delay_ms =
984 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
985 let delay = Duration::from_millis(delay_ms);
986
987 self.selected_completion_documentation_resolve_debounce
988 .lock()
989 .fire_new(delay, cx, |_, cx| {
990 cx.spawn(move |this, mut cx| async move {
991 if let Some(true) = resolve_task.await.log_err() {
992 this.update(&mut cx, |_, cx| cx.notify()).ok();
993 }
994 })
995 });
996 }
997
998 fn visible(&self) -> bool {
999 !self.matches.is_empty()
1000 }
1001
1002 fn render(
1003 &self,
1004 style: &EditorStyle,
1005 max_height: Pixels,
1006 workspace: Option<WeakView<Workspace>>,
1007 cx: &mut ViewContext<Editor>,
1008 ) -> AnyElement {
1009 let settings = EditorSettings::get_global(cx);
1010 let show_completion_documentation = settings.show_completion_documentation;
1011
1012 let widest_completion_ix = self
1013 .matches
1014 .iter()
1015 .enumerate()
1016 .max_by_key(|(_, mat)| {
1017 let completions = self.completions.read();
1018 let completion = &completions[mat.candidate_id];
1019 let documentation = &completion.documentation;
1020
1021 let mut len = completion.label.text.chars().count();
1022 if let Some(Documentation::SingleLine(text)) = documentation {
1023 if show_completion_documentation {
1024 len += text.chars().count();
1025 }
1026 }
1027
1028 len
1029 })
1030 .map(|(ix, _)| ix);
1031
1032 let completions = self.completions.clone();
1033 let matches = self.matches.clone();
1034 let selected_item = self.selected_item;
1035 let style = style.clone();
1036
1037 let multiline_docs = if show_completion_documentation {
1038 let mat = &self.matches[selected_item];
1039 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1040 Some(Documentation::MultiLinePlainText(text)) => {
1041 Some(div().child(SharedString::from(text.clone())))
1042 }
1043 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1044 Some(div().child(render_parsed_markdown(
1045 "completions_markdown",
1046 parsed,
1047 &style,
1048 workspace,
1049 cx,
1050 )))
1051 }
1052 _ => None,
1053 };
1054 multiline_docs.map(|div| {
1055 div.id("multiline_docs")
1056 .max_h(max_height)
1057 .flex_1()
1058 .px_1p5()
1059 .py_1()
1060 .min_w(px(260.))
1061 .max_w(px(640.))
1062 .w(px(500.))
1063 .overflow_y_scroll()
1064 .occlude()
1065 })
1066 } else {
1067 None
1068 };
1069
1070 let list = uniform_list(
1071 cx.view().clone(),
1072 "completions",
1073 matches.len(),
1074 move |_editor, range, cx| {
1075 let start_ix = range.start;
1076 let completions_guard = completions.read();
1077
1078 matches[range]
1079 .iter()
1080 .enumerate()
1081 .map(|(ix, mat)| {
1082 let item_ix = start_ix + ix;
1083 let candidate_id = mat.candidate_id;
1084 let completion = &completions_guard[candidate_id];
1085
1086 let documentation = if show_completion_documentation {
1087 &completion.documentation
1088 } else {
1089 &None
1090 };
1091
1092 let highlights = gpui::combine_highlights(
1093 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1094 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1095 |(range, mut highlight)| {
1096 // Ignore font weight for syntax highlighting, as we'll use it
1097 // for fuzzy matches.
1098 highlight.font_weight = None;
1099
1100 if completion.lsp_completion.deprecated.unwrap_or(false) {
1101 highlight.strikethrough = Some(StrikethroughStyle {
1102 thickness: 1.0.into(),
1103 ..Default::default()
1104 });
1105 highlight.color = Some(cx.theme().colors().text_muted);
1106 }
1107
1108 (range, highlight)
1109 },
1110 ),
1111 );
1112 let completion_label = StyledText::new(completion.label.text.clone())
1113 .with_highlights(&style.text, highlights);
1114 let documentation_label =
1115 if let Some(Documentation::SingleLine(text)) = documentation {
1116 if text.trim().is_empty() {
1117 None
1118 } else {
1119 Some(
1120 Label::new(text.clone())
1121 .ml_4()
1122 .size(LabelSize::Small)
1123 .color(Color::Muted),
1124 )
1125 }
1126 } else {
1127 None
1128 };
1129
1130 div().min_w(px(220.)).max_w(px(540.)).child(
1131 ListItem::new(mat.candidate_id)
1132 .inset(true)
1133 .selected(item_ix == selected_item)
1134 .on_click(cx.listener(move |editor, _event, cx| {
1135 cx.stop_propagation();
1136 if let Some(task) = editor.confirm_completion(
1137 &ConfirmCompletion {
1138 item_ix: Some(item_ix),
1139 },
1140 cx,
1141 ) {
1142 task.detach_and_log_err(cx)
1143 }
1144 }))
1145 .child(h_flex().overflow_hidden().child(completion_label))
1146 .end_slot::<Label>(documentation_label),
1147 )
1148 })
1149 .collect()
1150 },
1151 )
1152 .occlude()
1153 .max_h(max_height)
1154 .track_scroll(self.scroll_handle.clone())
1155 .with_width_from_item(widest_completion_ix)
1156 .with_sizing_behavior(ListSizingBehavior::Infer);
1157
1158 Popover::new()
1159 .child(list)
1160 .when_some(multiline_docs, |popover, multiline_docs| {
1161 popover.aside(multiline_docs)
1162 })
1163 .into_any_element()
1164 }
1165
1166 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1167 let mut matches = if let Some(query) = query {
1168 fuzzy::match_strings(
1169 &self.match_candidates,
1170 query,
1171 query.chars().any(|c| c.is_uppercase()),
1172 100,
1173 &Default::default(),
1174 executor,
1175 )
1176 .await
1177 } else {
1178 self.match_candidates
1179 .iter()
1180 .enumerate()
1181 .map(|(candidate_id, candidate)| StringMatch {
1182 candidate_id,
1183 score: Default::default(),
1184 positions: Default::default(),
1185 string: candidate.string.clone(),
1186 })
1187 .collect()
1188 };
1189
1190 // Remove all candidates where the query's start does not match the start of any word in the candidate
1191 if let Some(query) = query {
1192 if let Some(query_start) = query.chars().next() {
1193 matches.retain(|string_match| {
1194 split_words(&string_match.string).any(|word| {
1195 // Check that the first codepoint of the word as lowercase matches the first
1196 // codepoint of the query as lowercase
1197 word.chars()
1198 .flat_map(|codepoint| codepoint.to_lowercase())
1199 .zip(query_start.to_lowercase())
1200 .all(|(word_cp, query_cp)| word_cp == query_cp)
1201 })
1202 });
1203 }
1204 }
1205
1206 let completions = self.completions.read();
1207 matches.sort_unstable_by_key(|mat| {
1208 // We do want to strike a balance here between what the language server tells us
1209 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1210 // `Creat` and there is a local variable called `CreateComponent`).
1211 // So what we do is: we bucket all matches into two buckets
1212 // - Strong matches
1213 // - Weak matches
1214 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1215 // and the Weak matches are the rest.
1216 //
1217 // For the strong matches, we sort by the language-servers score first and for the weak
1218 // matches, we prefer our fuzzy finder first.
1219 //
1220 // The thinking behind that: it's useless to take the sort_text the language-server gives
1221 // us into account when it's obviously a bad match.
1222
1223 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1224 enum MatchScore<'a> {
1225 Strong {
1226 sort_text: Option<&'a str>,
1227 score: Reverse<OrderedFloat<f64>>,
1228 sort_key: (usize, &'a str),
1229 },
1230 Weak {
1231 score: Reverse<OrderedFloat<f64>>,
1232 sort_text: Option<&'a str>,
1233 sort_key: (usize, &'a str),
1234 },
1235 }
1236
1237 let completion = &completions[mat.candidate_id];
1238 let sort_key = completion.sort_key();
1239 let sort_text = completion.lsp_completion.sort_text.as_deref();
1240 let score = Reverse(OrderedFloat(mat.score));
1241
1242 if mat.score >= 0.2 {
1243 MatchScore::Strong {
1244 sort_text,
1245 score,
1246 sort_key,
1247 }
1248 } else {
1249 MatchScore::Weak {
1250 score,
1251 sort_text,
1252 sort_key,
1253 }
1254 }
1255 });
1256
1257 for mat in &mut matches {
1258 let completion = &completions[mat.candidate_id];
1259 mat.string.clone_from(&completion.label.text);
1260 for position in &mut mat.positions {
1261 *position += completion.label.filter_range.start;
1262 }
1263 }
1264 drop(completions);
1265
1266 self.matches = matches.into();
1267 self.selected_item = 0;
1268 }
1269}
1270
1271#[derive(Clone)]
1272struct CodeActionContents {
1273 tasks: Option<Arc<ResolvedTasks>>,
1274 actions: Option<Arc<[CodeAction]>>,
1275}
1276
1277impl CodeActionContents {
1278 fn len(&self) -> usize {
1279 match (&self.tasks, &self.actions) {
1280 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1281 (Some(tasks), None) => tasks.templates.len(),
1282 (None, Some(actions)) => actions.len(),
1283 (None, None) => 0,
1284 }
1285 }
1286
1287 fn is_empty(&self) -> bool {
1288 match (&self.tasks, &self.actions) {
1289 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1290 (Some(tasks), None) => tasks.templates.is_empty(),
1291 (None, Some(actions)) => actions.is_empty(),
1292 (None, None) => true,
1293 }
1294 }
1295
1296 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1297 self.tasks
1298 .iter()
1299 .flat_map(|tasks| {
1300 tasks
1301 .templates
1302 .iter()
1303 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1304 })
1305 .chain(self.actions.iter().flat_map(|actions| {
1306 actions
1307 .iter()
1308 .map(|action| CodeActionsItem::CodeAction(action.clone()))
1309 }))
1310 }
1311 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1312 match (&self.tasks, &self.actions) {
1313 (Some(tasks), Some(actions)) => {
1314 if index < tasks.templates.len() {
1315 tasks
1316 .templates
1317 .get(index)
1318 .cloned()
1319 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1320 } else {
1321 actions
1322 .get(index - tasks.templates.len())
1323 .cloned()
1324 .map(CodeActionsItem::CodeAction)
1325 }
1326 }
1327 (Some(tasks), None) => tasks
1328 .templates
1329 .get(index)
1330 .cloned()
1331 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1332 (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
1333 (None, None) => None,
1334 }
1335 }
1336}
1337
1338#[allow(clippy::large_enum_variant)]
1339#[derive(Clone)]
1340enum CodeActionsItem {
1341 Task(TaskSourceKind, ResolvedTask),
1342 CodeAction(CodeAction),
1343}
1344
1345impl CodeActionsItem {
1346 fn as_task(&self) -> Option<&ResolvedTask> {
1347 let Self::Task(_, task) = self else {
1348 return None;
1349 };
1350 Some(task)
1351 }
1352 fn as_code_action(&self) -> Option<&CodeAction> {
1353 let Self::CodeAction(action) = self else {
1354 return None;
1355 };
1356 Some(action)
1357 }
1358 fn label(&self) -> String {
1359 match self {
1360 Self::CodeAction(action) => action.lsp_action.title.clone(),
1361 Self::Task(_, task) => task.resolved_label.clone(),
1362 }
1363 }
1364}
1365
1366struct CodeActionsMenu {
1367 actions: CodeActionContents,
1368 buffer: Model<Buffer>,
1369 selected_item: usize,
1370 scroll_handle: UniformListScrollHandle,
1371 deployed_from_indicator: Option<DisplayRow>,
1372}
1373
1374impl CodeActionsMenu {
1375 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1376 self.selected_item = 0;
1377 self.scroll_handle.scroll_to_item(self.selected_item);
1378 cx.notify()
1379 }
1380
1381 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1382 if self.selected_item > 0 {
1383 self.selected_item -= 1;
1384 } else {
1385 self.selected_item = self.actions.len() - 1;
1386 }
1387 self.scroll_handle.scroll_to_item(self.selected_item);
1388 cx.notify();
1389 }
1390
1391 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1392 if self.selected_item + 1 < self.actions.len() {
1393 self.selected_item += 1;
1394 } else {
1395 self.selected_item = 0;
1396 }
1397 self.scroll_handle.scroll_to_item(self.selected_item);
1398 cx.notify();
1399 }
1400
1401 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1402 self.selected_item = self.actions.len() - 1;
1403 self.scroll_handle.scroll_to_item(self.selected_item);
1404 cx.notify()
1405 }
1406
1407 fn visible(&self) -> bool {
1408 !self.actions.is_empty()
1409 }
1410
1411 fn render(
1412 &self,
1413 cursor_position: DisplayPoint,
1414 _style: &EditorStyle,
1415 max_height: Pixels,
1416 cx: &mut ViewContext<Editor>,
1417 ) -> (ContextMenuOrigin, AnyElement) {
1418 let actions = self.actions.clone();
1419 let selected_item = self.selected_item;
1420 let element = uniform_list(
1421 cx.view().clone(),
1422 "code_actions_menu",
1423 self.actions.len(),
1424 move |_this, range, cx| {
1425 actions
1426 .iter()
1427 .skip(range.start)
1428 .take(range.end - range.start)
1429 .enumerate()
1430 .map(|(ix, action)| {
1431 let item_ix = range.start + ix;
1432 let selected = selected_item == item_ix;
1433 let colors = cx.theme().colors();
1434 div()
1435 .px_2()
1436 .text_color(colors.text)
1437 .when(selected, |style| {
1438 style
1439 .bg(colors.element_active)
1440 .text_color(colors.text_accent)
1441 })
1442 .hover(|style| {
1443 style
1444 .bg(colors.element_hover)
1445 .text_color(colors.text_accent)
1446 })
1447 .whitespace_nowrap()
1448 .when_some(action.as_code_action(), |this, action| {
1449 this.on_mouse_down(
1450 MouseButton::Left,
1451 cx.listener(move |editor, _, cx| {
1452 cx.stop_propagation();
1453 if let Some(task) = editor.confirm_code_action(
1454 &ConfirmCodeAction {
1455 item_ix: Some(item_ix),
1456 },
1457 cx,
1458 ) {
1459 task.detach_and_log_err(cx)
1460 }
1461 }),
1462 )
1463 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1464 .child(SharedString::from(action.lsp_action.title.clone()))
1465 })
1466 .when_some(action.as_task(), |this, task| {
1467 this.on_mouse_down(
1468 MouseButton::Left,
1469 cx.listener(move |editor, _, cx| {
1470 cx.stop_propagation();
1471 if let Some(task) = editor.confirm_code_action(
1472 &ConfirmCodeAction {
1473 item_ix: Some(item_ix),
1474 },
1475 cx,
1476 ) {
1477 task.detach_and_log_err(cx)
1478 }
1479 }),
1480 )
1481 .child(SharedString::from(task.resolved_label.clone()))
1482 })
1483 })
1484 .collect()
1485 },
1486 )
1487 .elevation_1(cx)
1488 .px_2()
1489 .py_1()
1490 .max_h(max_height)
1491 .occlude()
1492 .track_scroll(self.scroll_handle.clone())
1493 .with_width_from_item(
1494 self.actions
1495 .iter()
1496 .enumerate()
1497 .max_by_key(|(_, action)| match action {
1498 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1499 CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
1500 })
1501 .map(|(ix, _)| ix),
1502 )
1503 .with_sizing_behavior(ListSizingBehavior::Infer)
1504 .into_any_element();
1505
1506 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1507 ContextMenuOrigin::GutterIndicator(row)
1508 } else {
1509 ContextMenuOrigin::EditorPoint(cursor_position)
1510 };
1511
1512 (cursor_position, element)
1513 }
1514}
1515
1516#[derive(Debug)]
1517struct ActiveDiagnosticGroup {
1518 primary_range: Range<Anchor>,
1519 primary_message: String,
1520 group_id: usize,
1521 blocks: HashMap<CustomBlockId, Diagnostic>,
1522 is_valid: bool,
1523}
1524
1525#[derive(Serialize, Deserialize, Clone, Debug)]
1526pub struct ClipboardSelection {
1527 pub len: usize,
1528 pub is_entire_line: bool,
1529 pub first_line_indent: u32,
1530}
1531
1532#[derive(Debug)]
1533pub(crate) struct NavigationData {
1534 cursor_anchor: Anchor,
1535 cursor_position: Point,
1536 scroll_anchor: ScrollAnchor,
1537 scroll_top_row: u32,
1538}
1539
1540enum GotoDefinitionKind {
1541 Symbol,
1542 Declaration,
1543 Type,
1544 Implementation,
1545}
1546
1547#[derive(Debug, Clone)]
1548enum InlayHintRefreshReason {
1549 Toggle(bool),
1550 SettingsChange(InlayHintSettings),
1551 NewLinesShown,
1552 BufferEdited(HashSet<Arc<Language>>),
1553 RefreshRequested,
1554 ExcerptsRemoved(Vec<ExcerptId>),
1555}
1556
1557impl InlayHintRefreshReason {
1558 fn description(&self) -> &'static str {
1559 match self {
1560 Self::Toggle(_) => "toggle",
1561 Self::SettingsChange(_) => "settings change",
1562 Self::NewLinesShown => "new lines shown",
1563 Self::BufferEdited(_) => "buffer edited",
1564 Self::RefreshRequested => "refresh requested",
1565 Self::ExcerptsRemoved(_) => "excerpts removed",
1566 }
1567 }
1568}
1569
1570pub(crate) struct FocusedBlock {
1571 id: BlockId,
1572 focus_handle: WeakFocusHandle,
1573}
1574
1575impl Editor {
1576 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1577 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1578 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1579 Self::new(
1580 EditorMode::SingleLine { auto_width: false },
1581 buffer,
1582 None,
1583 false,
1584 cx,
1585 )
1586 }
1587
1588 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1589 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1590 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1591 Self::new(EditorMode::Full, buffer, None, false, cx)
1592 }
1593
1594 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1595 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1596 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1597 Self::new(
1598 EditorMode::SingleLine { auto_width: true },
1599 buffer,
1600 None,
1601 false,
1602 cx,
1603 )
1604 }
1605
1606 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1607 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1608 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1609 Self::new(
1610 EditorMode::AutoHeight { max_lines },
1611 buffer,
1612 None,
1613 false,
1614 cx,
1615 )
1616 }
1617
1618 pub fn for_buffer(
1619 buffer: Model<Buffer>,
1620 project: Option<Model<Project>>,
1621 cx: &mut ViewContext<Self>,
1622 ) -> Self {
1623 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1624 Self::new(EditorMode::Full, buffer, project, false, cx)
1625 }
1626
1627 pub fn for_multibuffer(
1628 buffer: Model<MultiBuffer>,
1629 project: Option<Model<Project>>,
1630 show_excerpt_controls: bool,
1631 cx: &mut ViewContext<Self>,
1632 ) -> Self {
1633 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1634 }
1635
1636 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1637 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1638 let mut clone = Self::new(
1639 self.mode,
1640 self.buffer.clone(),
1641 self.project.clone(),
1642 show_excerpt_controls,
1643 cx,
1644 );
1645 self.display_map.update(cx, |display_map, cx| {
1646 let snapshot = display_map.snapshot(cx);
1647 clone.display_map.update(cx, |display_map, cx| {
1648 display_map.set_state(&snapshot, cx);
1649 });
1650 });
1651 clone.selections.clone_state(&self.selections);
1652 clone.scroll_manager.clone_state(&self.scroll_manager);
1653 clone.searchable = self.searchable;
1654 clone
1655 }
1656
1657 pub fn new(
1658 mode: EditorMode,
1659 buffer: Model<MultiBuffer>,
1660 project: Option<Model<Project>>,
1661 show_excerpt_controls: bool,
1662 cx: &mut ViewContext<Self>,
1663 ) -> Self {
1664 let style = cx.text_style();
1665 let font_size = style.font_size.to_pixels(cx.rem_size());
1666 let editor = cx.view().downgrade();
1667 let fold_placeholder = FoldPlaceholder {
1668 constrain_width: true,
1669 render: Arc::new(move |fold_id, fold_range, cx| {
1670 let editor = editor.clone();
1671 div()
1672 .id(fold_id)
1673 .bg(cx.theme().colors().ghost_element_background)
1674 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1675 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1676 .rounded_sm()
1677 .size_full()
1678 .cursor_pointer()
1679 .child("⋯")
1680 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1681 .on_click(move |_, cx| {
1682 editor
1683 .update(cx, |editor, cx| {
1684 editor.unfold_ranges(
1685 [fold_range.start..fold_range.end],
1686 true,
1687 false,
1688 cx,
1689 );
1690 cx.stop_propagation();
1691 })
1692 .ok();
1693 })
1694 .into_any()
1695 }),
1696 merge_adjacent: true,
1697 };
1698 let file_header_size = if show_excerpt_controls { 3 } else { 2 };
1699 let display_map = cx.new_model(|cx| {
1700 DisplayMap::new(
1701 buffer.clone(),
1702 style.font(),
1703 font_size,
1704 None,
1705 show_excerpt_controls,
1706 file_header_size,
1707 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1708 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1709 fold_placeholder,
1710 cx,
1711 )
1712 });
1713
1714 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1715
1716 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1717
1718 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1719 .then(|| language_settings::SoftWrap::PreferLine);
1720
1721 let mut project_subscriptions = Vec::new();
1722 if mode == EditorMode::Full {
1723 if let Some(project) = project.as_ref() {
1724 if buffer.read(cx).is_singleton() {
1725 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1726 cx.emit(EditorEvent::TitleChanged);
1727 }));
1728 }
1729 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1730 if let project::Event::RefreshInlayHints = event {
1731 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1732 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1733 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1734 let focus_handle = editor.focus_handle(cx);
1735 if focus_handle.is_focused(cx) {
1736 let snapshot = buffer.read(cx).snapshot();
1737 for (range, snippet) in snippet_edits {
1738 let editor_range =
1739 language::range_from_lsp(*range).to_offset(&snapshot);
1740 editor
1741 .insert_snippet(&[editor_range], snippet.clone(), cx)
1742 .ok();
1743 }
1744 }
1745 }
1746 }
1747 }));
1748 let task_inventory = project.read(cx).task_inventory().clone();
1749 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1750 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1751 }));
1752 }
1753 }
1754
1755 let inlay_hint_settings = inlay_hint_settings(
1756 selections.newest_anchor().head(),
1757 &buffer.read(cx).snapshot(cx),
1758 cx,
1759 );
1760 let focus_handle = cx.focus_handle();
1761 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1762 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1763 .detach();
1764 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1765 .detach();
1766 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1767
1768 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1769 Some(false)
1770 } else {
1771 None
1772 };
1773
1774 let mut this = Self {
1775 focus_handle,
1776 show_cursor_when_unfocused: false,
1777 last_focused_descendant: None,
1778 buffer: buffer.clone(),
1779 display_map: display_map.clone(),
1780 selections,
1781 scroll_manager: ScrollManager::new(cx),
1782 columnar_selection_tail: None,
1783 add_selections_state: None,
1784 select_next_state: None,
1785 select_prev_state: None,
1786 selection_history: Default::default(),
1787 autoclose_regions: Default::default(),
1788 snippet_stack: Default::default(),
1789 select_larger_syntax_node_stack: Vec::new(),
1790 ime_transaction: Default::default(),
1791 active_diagnostics: None,
1792 soft_wrap_mode_override,
1793 completion_provider: project.clone().map(|project| Box::new(project) as _),
1794 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1795 project,
1796 blink_manager: blink_manager.clone(),
1797 show_local_selections: true,
1798 mode,
1799 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1800 show_gutter: mode == EditorMode::Full,
1801 show_line_numbers: None,
1802 show_git_diff_gutter: None,
1803 show_code_actions: None,
1804 show_runnables: None,
1805 show_wrap_guides: None,
1806 show_indent_guides,
1807 placeholder_text: None,
1808 highlight_order: 0,
1809 highlighted_rows: HashMap::default(),
1810 background_highlights: Default::default(),
1811 gutter_highlights: TreeMap::default(),
1812 scrollbar_marker_state: ScrollbarMarkerState::default(),
1813 active_indent_guides_state: ActiveIndentGuidesState::default(),
1814 nav_history: None,
1815 context_menu: RwLock::new(None),
1816 mouse_context_menu: None,
1817 completion_tasks: Default::default(),
1818 signature_help_state: SignatureHelpState::default(),
1819 auto_signature_help: None,
1820 find_all_references_task_sources: Vec::new(),
1821 next_completion_id: 0,
1822 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1823 next_inlay_id: 0,
1824 available_code_actions: Default::default(),
1825 code_actions_task: Default::default(),
1826 document_highlights_task: Default::default(),
1827 linked_editing_range_task: Default::default(),
1828 pending_rename: Default::default(),
1829 searchable: true,
1830 cursor_shape: Default::default(),
1831 current_line_highlight: None,
1832 autoindent_mode: Some(AutoindentMode::EachLine),
1833 collapse_matches: false,
1834 workspace: None,
1835 keymap_context_layers: Default::default(),
1836 input_enabled: true,
1837 use_modal_editing: mode == EditorMode::Full,
1838 read_only: false,
1839 use_autoclose: true,
1840 use_auto_surround: true,
1841 auto_replace_emoji_shortcode: false,
1842 leader_peer_id: None,
1843 remote_id: None,
1844 hover_state: Default::default(),
1845 hovered_link_state: Default::default(),
1846 inline_completion_provider: None,
1847 active_inline_completion: None,
1848 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1849 expanded_hunks: ExpandedHunks::default(),
1850 gutter_hovered: false,
1851 pixel_position_of_newest_cursor: None,
1852 last_bounds: None,
1853 expect_bounds_change: None,
1854 gutter_dimensions: GutterDimensions::default(),
1855 style: None,
1856 show_cursor_names: false,
1857 hovered_cursors: Default::default(),
1858 next_editor_action_id: EditorActionId::default(),
1859 editor_actions: Rc::default(),
1860 vim_replace_map: Default::default(),
1861 show_inline_completions: mode == EditorMode::Full,
1862 custom_context_menu: None,
1863 show_git_blame_gutter: false,
1864 show_git_blame_inline: false,
1865 show_selection_menu: None,
1866 show_git_blame_inline_delay_task: None,
1867 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1868 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1869 .session
1870 .restore_unsaved_buffers,
1871 blame: None,
1872 blame_subscription: None,
1873 file_header_size,
1874 tasks: Default::default(),
1875 _subscriptions: vec![
1876 cx.observe(&buffer, Self::on_buffer_changed),
1877 cx.subscribe(&buffer, Self::on_buffer_event),
1878 cx.observe(&display_map, Self::on_display_map_changed),
1879 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1880 cx.observe_global::<SettingsStore>(Self::settings_changed),
1881 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1882 cx.observe_window_activation(|editor, cx| {
1883 let active = cx.is_window_active();
1884 editor.blink_manager.update(cx, |blink_manager, cx| {
1885 if active {
1886 blink_manager.enable(cx);
1887 } else {
1888 blink_manager.disable(cx);
1889 }
1890 });
1891 }),
1892 ],
1893 tasks_update_task: None,
1894 linked_edit_ranges: Default::default(),
1895 previous_search_ranges: None,
1896 breadcrumb_header: None,
1897 focused_block: None,
1898 };
1899 this.tasks_update_task = Some(this.refresh_runnables(cx));
1900 this._subscriptions.extend(project_subscriptions);
1901
1902 this.end_selection(cx);
1903 this.scroll_manager.show_scrollbar(cx);
1904
1905 if mode == EditorMode::Full {
1906 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1907 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1908
1909 if this.git_blame_inline_enabled {
1910 this.git_blame_inline_enabled = true;
1911 this.start_git_blame_inline(false, cx);
1912 }
1913 }
1914
1915 this.report_editor_event("open", None, cx);
1916 this
1917 }
1918
1919 pub fn mouse_menu_is_focused(&self, cx: &mut WindowContext) -> bool {
1920 self.mouse_context_menu
1921 .as_ref()
1922 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1923 }
1924
1925 fn key_context(&self, cx: &AppContext) -> KeyContext {
1926 let mut key_context = KeyContext::new_with_defaults();
1927 key_context.add("Editor");
1928 let mode = match self.mode {
1929 EditorMode::SingleLine { .. } => "single_line",
1930 EditorMode::AutoHeight { .. } => "auto_height",
1931 EditorMode::Full => "full",
1932 };
1933
1934 if EditorSettings::jupyter_enabled(cx) {
1935 key_context.add("jupyter");
1936 }
1937
1938 key_context.set("mode", mode);
1939 if self.pending_rename.is_some() {
1940 key_context.add("renaming");
1941 }
1942 if self.context_menu_visible() {
1943 match self.context_menu.read().as_ref() {
1944 Some(ContextMenu::Completions(_)) => {
1945 key_context.add("menu");
1946 key_context.add("showing_completions")
1947 }
1948 Some(ContextMenu::CodeActions(_)) => {
1949 key_context.add("menu");
1950 key_context.add("showing_code_actions")
1951 }
1952 None => {}
1953 }
1954 }
1955
1956 for layer in self.keymap_context_layers.values() {
1957 key_context.extend(layer);
1958 }
1959
1960 if let Some(extension) = self
1961 .buffer
1962 .read(cx)
1963 .as_singleton()
1964 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1965 {
1966 key_context.set("extension", extension.to_string());
1967 }
1968
1969 if self.has_active_inline_completion(cx) {
1970 key_context.add("copilot_suggestion");
1971 key_context.add("inline_completion");
1972 }
1973
1974 key_context
1975 }
1976
1977 pub fn new_file(
1978 workspace: &mut Workspace,
1979 _: &workspace::NewFile,
1980 cx: &mut ViewContext<Workspace>,
1981 ) {
1982 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
1983 "Failed to create buffer",
1984 cx,
1985 |e, _| match e.error_code() {
1986 ErrorCode::RemoteUpgradeRequired => Some(format!(
1987 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1988 e.error_tag("required").unwrap_or("the latest version")
1989 )),
1990 _ => None,
1991 },
1992 );
1993 }
1994
1995 pub fn new_in_workspace(
1996 workspace: &mut Workspace,
1997 cx: &mut ViewContext<Workspace>,
1998 ) -> Task<Result<View<Editor>>> {
1999 let project = workspace.project().clone();
2000 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2001
2002 cx.spawn(|workspace, mut cx| async move {
2003 let buffer = create.await?;
2004 workspace.update(&mut cx, |workspace, cx| {
2005 let editor =
2006 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2007 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2008 editor
2009 })
2010 })
2011 }
2012
2013 pub fn new_file_in_direction(
2014 workspace: &mut Workspace,
2015 action: &workspace::NewFileInDirection,
2016 cx: &mut ViewContext<Workspace>,
2017 ) {
2018 let project = workspace.project().clone();
2019 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2020 let direction = action.0;
2021
2022 cx.spawn(|workspace, mut cx| async move {
2023 let buffer = create.await?;
2024 workspace.update(&mut cx, move |workspace, cx| {
2025 workspace.split_item(
2026 direction,
2027 Box::new(
2028 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2029 ),
2030 cx,
2031 )
2032 })?;
2033 anyhow::Ok(())
2034 })
2035 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2036 ErrorCode::RemoteUpgradeRequired => Some(format!(
2037 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2038 e.error_tag("required").unwrap_or("the latest version")
2039 )),
2040 _ => None,
2041 });
2042 }
2043
2044 pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
2045 self.buffer.read(cx).replica_id()
2046 }
2047
2048 pub fn leader_peer_id(&self) -> Option<PeerId> {
2049 self.leader_peer_id
2050 }
2051
2052 pub fn buffer(&self) -> &Model<MultiBuffer> {
2053 &self.buffer
2054 }
2055
2056 pub fn workspace(&self) -> Option<View<Workspace>> {
2057 self.workspace.as_ref()?.0.upgrade()
2058 }
2059
2060 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2061 self.buffer().read(cx).title(cx)
2062 }
2063
2064 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2065 EditorSnapshot {
2066 mode: self.mode,
2067 show_gutter: self.show_gutter,
2068 show_line_numbers: self.show_line_numbers,
2069 show_git_diff_gutter: self.show_git_diff_gutter,
2070 show_code_actions: self.show_code_actions,
2071 show_runnables: self.show_runnables,
2072 render_git_blame_gutter: self.render_git_blame_gutter(cx),
2073 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2074 scroll_anchor: self.scroll_manager.anchor(),
2075 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2076 placeholder_text: self.placeholder_text.clone(),
2077 is_focused: self.focus_handle.is_focused(cx),
2078 current_line_highlight: self
2079 .current_line_highlight
2080 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2081 gutter_hovered: self.gutter_hovered,
2082 }
2083 }
2084
2085 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2086 self.buffer.read(cx).language_at(point, cx)
2087 }
2088
2089 pub fn file_at<T: ToOffset>(
2090 &self,
2091 point: T,
2092 cx: &AppContext,
2093 ) -> Option<Arc<dyn language::File>> {
2094 self.buffer.read(cx).read(cx).file_at(point).cloned()
2095 }
2096
2097 pub fn active_excerpt(
2098 &self,
2099 cx: &AppContext,
2100 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2101 self.buffer
2102 .read(cx)
2103 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2104 }
2105
2106 pub fn mode(&self) -> EditorMode {
2107 self.mode
2108 }
2109
2110 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2111 self.collaboration_hub.as_deref()
2112 }
2113
2114 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2115 self.collaboration_hub = Some(hub);
2116 }
2117
2118 pub fn set_custom_context_menu(
2119 &mut self,
2120 f: impl 'static
2121 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2122 ) {
2123 self.custom_context_menu = Some(Box::new(f))
2124 }
2125
2126 pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
2127 self.completion_provider = Some(provider);
2128 }
2129
2130 pub fn set_inline_completion_provider<T>(
2131 &mut self,
2132 provider: Option<Model<T>>,
2133 cx: &mut ViewContext<Self>,
2134 ) where
2135 T: InlineCompletionProvider,
2136 {
2137 self.inline_completion_provider =
2138 provider.map(|provider| RegisteredInlineCompletionProvider {
2139 _subscription: cx.observe(&provider, |this, _, cx| {
2140 if this.focus_handle.is_focused(cx) {
2141 this.update_visible_inline_completion(cx);
2142 }
2143 }),
2144 provider: Arc::new(provider),
2145 });
2146 self.refresh_inline_completion(false, cx);
2147 }
2148
2149 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2150 self.placeholder_text.as_deref()
2151 }
2152
2153 pub fn set_placeholder_text(
2154 &mut self,
2155 placeholder_text: impl Into<Arc<str>>,
2156 cx: &mut ViewContext<Self>,
2157 ) {
2158 let placeholder_text = Some(placeholder_text.into());
2159 if self.placeholder_text != placeholder_text {
2160 self.placeholder_text = placeholder_text;
2161 cx.notify();
2162 }
2163 }
2164
2165 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2166 self.cursor_shape = cursor_shape;
2167
2168 // Disrupt blink for immediate user feedback that the cursor shape has changed
2169 self.blink_manager.update(cx, BlinkManager::show_cursor);
2170
2171 cx.notify();
2172 }
2173
2174 pub fn set_current_line_highlight(
2175 &mut self,
2176 current_line_highlight: Option<CurrentLineHighlight>,
2177 ) {
2178 self.current_line_highlight = current_line_highlight;
2179 }
2180
2181 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2182 self.collapse_matches = collapse_matches;
2183 }
2184
2185 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2186 if self.collapse_matches {
2187 return range.start..range.start;
2188 }
2189 range.clone()
2190 }
2191
2192 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2193 if self.display_map.read(cx).clip_at_line_ends != clip {
2194 self.display_map
2195 .update(cx, |map, _| map.clip_at_line_ends = clip);
2196 }
2197 }
2198
2199 pub fn set_keymap_context_layer<Tag: 'static>(
2200 &mut self,
2201 context: KeyContext,
2202 cx: &mut ViewContext<Self>,
2203 ) {
2204 self.keymap_context_layers
2205 .insert(TypeId::of::<Tag>(), context);
2206 cx.notify();
2207 }
2208
2209 pub fn remove_keymap_context_layer<Tag: 'static>(&mut self, cx: &mut ViewContext<Self>) {
2210 self.keymap_context_layers.remove(&TypeId::of::<Tag>());
2211 cx.notify();
2212 }
2213
2214 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2215 self.input_enabled = input_enabled;
2216 }
2217
2218 pub fn set_autoindent(&mut self, autoindent: bool) {
2219 if autoindent {
2220 self.autoindent_mode = Some(AutoindentMode::EachLine);
2221 } else {
2222 self.autoindent_mode = None;
2223 }
2224 }
2225
2226 pub fn read_only(&self, cx: &AppContext) -> bool {
2227 self.read_only || self.buffer.read(cx).read_only()
2228 }
2229
2230 pub fn set_read_only(&mut self, read_only: bool) {
2231 self.read_only = read_only;
2232 }
2233
2234 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2235 self.use_autoclose = autoclose;
2236 }
2237
2238 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2239 self.use_auto_surround = auto_surround;
2240 }
2241
2242 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2243 self.auto_replace_emoji_shortcode = auto_replace;
2244 }
2245
2246 pub fn set_show_inline_completions(&mut self, show_inline_completions: bool) {
2247 self.show_inline_completions = show_inline_completions;
2248 }
2249
2250 pub fn set_use_modal_editing(&mut self, to: bool) {
2251 self.use_modal_editing = to;
2252 }
2253
2254 pub fn use_modal_editing(&self) -> bool {
2255 self.use_modal_editing
2256 }
2257
2258 fn selections_did_change(
2259 &mut self,
2260 local: bool,
2261 old_cursor_position: &Anchor,
2262 show_completions: bool,
2263 cx: &mut ViewContext<Self>,
2264 ) {
2265 // Copy selections to primary selection buffer
2266 #[cfg(target_os = "linux")]
2267 if local {
2268 let selections = self.selections.all::<usize>(cx);
2269 let buffer_handle = self.buffer.read(cx).read(cx);
2270
2271 let mut text = String::new();
2272 for (index, selection) in selections.iter().enumerate() {
2273 let text_for_selection = buffer_handle
2274 .text_for_range(selection.start..selection.end)
2275 .collect::<String>();
2276
2277 text.push_str(&text_for_selection);
2278 if index != selections.len() - 1 {
2279 text.push('\n');
2280 }
2281 }
2282
2283 if !text.is_empty() {
2284 cx.write_to_primary(ClipboardItem::new(text));
2285 }
2286 }
2287
2288 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2289 self.buffer.update(cx, |buffer, cx| {
2290 buffer.set_active_selections(
2291 &self.selections.disjoint_anchors(),
2292 self.selections.line_mode,
2293 self.cursor_shape,
2294 cx,
2295 )
2296 });
2297 }
2298 let display_map = self
2299 .display_map
2300 .update(cx, |display_map, cx| display_map.snapshot(cx));
2301 let buffer = &display_map.buffer_snapshot;
2302 self.add_selections_state = None;
2303 self.select_next_state = None;
2304 self.select_prev_state = None;
2305 self.select_larger_syntax_node_stack.clear();
2306 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2307 self.snippet_stack
2308 .invalidate(&self.selections.disjoint_anchors(), buffer);
2309 self.take_rename(false, cx);
2310
2311 let new_cursor_position = self.selections.newest_anchor().head();
2312
2313 self.push_to_nav_history(
2314 *old_cursor_position,
2315 Some(new_cursor_position.to_point(buffer)),
2316 cx,
2317 );
2318
2319 if local {
2320 let new_cursor_position = self.selections.newest_anchor().head();
2321 let mut context_menu = self.context_menu.write();
2322 let completion_menu = match context_menu.as_ref() {
2323 Some(ContextMenu::Completions(menu)) => Some(menu),
2324
2325 _ => {
2326 *context_menu = None;
2327 None
2328 }
2329 };
2330
2331 if let Some(completion_menu) = completion_menu {
2332 let cursor_position = new_cursor_position.to_offset(buffer);
2333 let (word_range, kind) = buffer.surrounding_word(completion_menu.initial_position);
2334 if kind == Some(CharKind::Word)
2335 && word_range.to_inclusive().contains(&cursor_position)
2336 {
2337 let mut completion_menu = completion_menu.clone();
2338 drop(context_menu);
2339
2340 let query = Self::completion_query(buffer, cursor_position);
2341 cx.spawn(move |this, mut cx| async move {
2342 completion_menu
2343 .filter(query.as_deref(), cx.background_executor().clone())
2344 .await;
2345
2346 this.update(&mut cx, |this, cx| {
2347 let mut context_menu = this.context_menu.write();
2348 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2349 return;
2350 };
2351
2352 if menu.id > completion_menu.id {
2353 return;
2354 }
2355
2356 *context_menu = Some(ContextMenu::Completions(completion_menu));
2357 drop(context_menu);
2358 cx.notify();
2359 })
2360 })
2361 .detach();
2362
2363 if show_completions {
2364 self.show_completions(&ShowCompletions { trigger: None }, cx);
2365 }
2366 } else {
2367 drop(context_menu);
2368 self.hide_context_menu(cx);
2369 }
2370 } else {
2371 drop(context_menu);
2372 }
2373
2374 hide_hover(self, cx);
2375
2376 if old_cursor_position.to_display_point(&display_map).row()
2377 != new_cursor_position.to_display_point(&display_map).row()
2378 {
2379 self.available_code_actions.take();
2380 }
2381 self.refresh_code_actions(cx);
2382 self.refresh_document_highlights(cx);
2383 refresh_matching_bracket_highlights(self, cx);
2384 self.discard_inline_completion(false, cx);
2385 linked_editing_ranges::refresh_linked_ranges(self, cx);
2386 if self.git_blame_inline_enabled {
2387 self.start_inline_blame_timer(cx);
2388 }
2389 }
2390
2391 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2392 cx.emit(EditorEvent::SelectionsChanged { local });
2393
2394 if self.selections.disjoint_anchors().len() == 1 {
2395 cx.emit(SearchEvent::ActiveMatchChanged)
2396 }
2397 cx.notify();
2398 }
2399
2400 pub fn change_selections<R>(
2401 &mut self,
2402 autoscroll: Option<Autoscroll>,
2403 cx: &mut ViewContext<Self>,
2404 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2405 ) -> R {
2406 self.change_selections_inner(autoscroll, true, cx, change)
2407 }
2408
2409 pub fn change_selections_inner<R>(
2410 &mut self,
2411 autoscroll: Option<Autoscroll>,
2412 request_completions: bool,
2413 cx: &mut ViewContext<Self>,
2414 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2415 ) -> R {
2416 let old_cursor_position = self.selections.newest_anchor().head();
2417 self.push_to_selection_history();
2418
2419 let (changed, result) = self.selections.change_with(cx, change);
2420
2421 if changed {
2422 if let Some(autoscroll) = autoscroll {
2423 self.request_autoscroll(autoscroll, cx);
2424 }
2425 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2426
2427 if self.should_open_signature_help_automatically(
2428 &old_cursor_position,
2429 self.signature_help_state.backspace_pressed(),
2430 cx,
2431 ) {
2432 self.show_signature_help(&ShowSignatureHelp, cx);
2433 }
2434 self.signature_help_state.set_backspace_pressed(false);
2435 }
2436
2437 result
2438 }
2439
2440 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2441 where
2442 I: IntoIterator<Item = (Range<S>, T)>,
2443 S: ToOffset,
2444 T: Into<Arc<str>>,
2445 {
2446 if self.read_only(cx) {
2447 return;
2448 }
2449
2450 self.buffer
2451 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2452 }
2453
2454 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2455 where
2456 I: IntoIterator<Item = (Range<S>, T)>,
2457 S: ToOffset,
2458 T: Into<Arc<str>>,
2459 {
2460 if self.read_only(cx) {
2461 return;
2462 }
2463
2464 self.buffer.update(cx, |buffer, cx| {
2465 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2466 });
2467 }
2468
2469 pub fn edit_with_block_indent<I, S, T>(
2470 &mut self,
2471 edits: I,
2472 original_indent_columns: Vec<u32>,
2473 cx: &mut ViewContext<Self>,
2474 ) where
2475 I: IntoIterator<Item = (Range<S>, T)>,
2476 S: ToOffset,
2477 T: Into<Arc<str>>,
2478 {
2479 if self.read_only(cx) {
2480 return;
2481 }
2482
2483 self.buffer.update(cx, |buffer, cx| {
2484 buffer.edit(
2485 edits,
2486 Some(AutoindentMode::Block {
2487 original_indent_columns,
2488 }),
2489 cx,
2490 )
2491 });
2492 }
2493
2494 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2495 self.hide_context_menu(cx);
2496
2497 match phase {
2498 SelectPhase::Begin {
2499 position,
2500 add,
2501 click_count,
2502 } => self.begin_selection(position, add, click_count, cx),
2503 SelectPhase::BeginColumnar {
2504 position,
2505 goal_column,
2506 reset,
2507 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2508 SelectPhase::Extend {
2509 position,
2510 click_count,
2511 } => self.extend_selection(position, click_count, cx),
2512 SelectPhase::Update {
2513 position,
2514 goal_column,
2515 scroll_delta,
2516 } => self.update_selection(position, goal_column, scroll_delta, cx),
2517 SelectPhase::End => self.end_selection(cx),
2518 }
2519 }
2520
2521 fn extend_selection(
2522 &mut self,
2523 position: DisplayPoint,
2524 click_count: usize,
2525 cx: &mut ViewContext<Self>,
2526 ) {
2527 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2528 let tail = self.selections.newest::<usize>(cx).tail();
2529 self.begin_selection(position, false, click_count, cx);
2530
2531 let position = position.to_offset(&display_map, Bias::Left);
2532 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2533
2534 let mut pending_selection = self
2535 .selections
2536 .pending_anchor()
2537 .expect("extend_selection not called with pending selection");
2538 if position >= tail {
2539 pending_selection.start = tail_anchor;
2540 } else {
2541 pending_selection.end = tail_anchor;
2542 pending_selection.reversed = true;
2543 }
2544
2545 let mut pending_mode = self.selections.pending_mode().unwrap();
2546 match &mut pending_mode {
2547 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2548 _ => {}
2549 }
2550
2551 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2552 s.set_pending(pending_selection, pending_mode)
2553 });
2554 }
2555
2556 fn begin_selection(
2557 &mut self,
2558 position: DisplayPoint,
2559 add: bool,
2560 click_count: usize,
2561 cx: &mut ViewContext<Self>,
2562 ) {
2563 if !self.focus_handle.is_focused(cx) {
2564 self.last_focused_descendant = None;
2565 cx.focus(&self.focus_handle);
2566 }
2567
2568 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2569 let buffer = &display_map.buffer_snapshot;
2570 let newest_selection = self.selections.newest_anchor().clone();
2571 let position = display_map.clip_point(position, Bias::Left);
2572
2573 let start;
2574 let end;
2575 let mode;
2576 let auto_scroll;
2577 match click_count {
2578 1 => {
2579 start = buffer.anchor_before(position.to_point(&display_map));
2580 end = start;
2581 mode = SelectMode::Character;
2582 auto_scroll = true;
2583 }
2584 2 => {
2585 let range = movement::surrounding_word(&display_map, position);
2586 start = buffer.anchor_before(range.start.to_point(&display_map));
2587 end = buffer.anchor_before(range.end.to_point(&display_map));
2588 mode = SelectMode::Word(start..end);
2589 auto_scroll = true;
2590 }
2591 3 => {
2592 let position = display_map
2593 .clip_point(position, Bias::Left)
2594 .to_point(&display_map);
2595 let line_start = display_map.prev_line_boundary(position).0;
2596 let next_line_start = buffer.clip_point(
2597 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2598 Bias::Left,
2599 );
2600 start = buffer.anchor_before(line_start);
2601 end = buffer.anchor_before(next_line_start);
2602 mode = SelectMode::Line(start..end);
2603 auto_scroll = true;
2604 }
2605 _ => {
2606 start = buffer.anchor_before(0);
2607 end = buffer.anchor_before(buffer.len());
2608 mode = SelectMode::All;
2609 auto_scroll = false;
2610 }
2611 }
2612
2613 let point_to_delete: Option<usize> = {
2614 let selected_points: Vec<Selection<Point>> =
2615 self.selections.disjoint_in_range(start..end, cx);
2616
2617 if !add || click_count > 1 {
2618 None
2619 } else if selected_points.len() > 0 {
2620 Some(selected_points[0].id)
2621 } else {
2622 let clicked_point_already_selected =
2623 self.selections.disjoint.iter().find(|selection| {
2624 selection.start.to_point(buffer) == start.to_point(buffer)
2625 || selection.end.to_point(buffer) == end.to_point(buffer)
2626 });
2627
2628 if let Some(selection) = clicked_point_already_selected {
2629 Some(selection.id)
2630 } else {
2631 None
2632 }
2633 }
2634 };
2635
2636 let selections_count = self.selections.count();
2637
2638 self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
2639 if let Some(point_to_delete) = point_to_delete {
2640 s.delete(point_to_delete);
2641
2642 if selections_count == 1 {
2643 s.set_pending_anchor_range(start..end, mode);
2644 }
2645 } else {
2646 if !add {
2647 s.clear_disjoint();
2648 } else if click_count > 1 {
2649 s.delete(newest_selection.id)
2650 }
2651
2652 s.set_pending_anchor_range(start..end, mode);
2653 }
2654 });
2655 }
2656
2657 fn begin_columnar_selection(
2658 &mut self,
2659 position: DisplayPoint,
2660 goal_column: u32,
2661 reset: bool,
2662 cx: &mut ViewContext<Self>,
2663 ) {
2664 if !self.focus_handle.is_focused(cx) {
2665 self.last_focused_descendant = None;
2666 cx.focus(&self.focus_handle);
2667 }
2668
2669 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2670
2671 if reset {
2672 let pointer_position = display_map
2673 .buffer_snapshot
2674 .anchor_before(position.to_point(&display_map));
2675
2676 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2677 s.clear_disjoint();
2678 s.set_pending_anchor_range(
2679 pointer_position..pointer_position,
2680 SelectMode::Character,
2681 );
2682 });
2683 }
2684
2685 let tail = self.selections.newest::<Point>(cx).tail();
2686 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2687
2688 if !reset {
2689 self.select_columns(
2690 tail.to_display_point(&display_map),
2691 position,
2692 goal_column,
2693 &display_map,
2694 cx,
2695 );
2696 }
2697 }
2698
2699 fn update_selection(
2700 &mut self,
2701 position: DisplayPoint,
2702 goal_column: u32,
2703 scroll_delta: gpui::Point<f32>,
2704 cx: &mut ViewContext<Self>,
2705 ) {
2706 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2707
2708 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2709 let tail = tail.to_display_point(&display_map);
2710 self.select_columns(tail, position, goal_column, &display_map, cx);
2711 } else if let Some(mut pending) = self.selections.pending_anchor() {
2712 let buffer = self.buffer.read(cx).snapshot(cx);
2713 let head;
2714 let tail;
2715 let mode = self.selections.pending_mode().unwrap();
2716 match &mode {
2717 SelectMode::Character => {
2718 head = position.to_point(&display_map);
2719 tail = pending.tail().to_point(&buffer);
2720 }
2721 SelectMode::Word(original_range) => {
2722 let original_display_range = original_range.start.to_display_point(&display_map)
2723 ..original_range.end.to_display_point(&display_map);
2724 let original_buffer_range = original_display_range.start.to_point(&display_map)
2725 ..original_display_range.end.to_point(&display_map);
2726 if movement::is_inside_word(&display_map, position)
2727 || original_display_range.contains(&position)
2728 {
2729 let word_range = movement::surrounding_word(&display_map, position);
2730 if word_range.start < original_display_range.start {
2731 head = word_range.start.to_point(&display_map);
2732 } else {
2733 head = word_range.end.to_point(&display_map);
2734 }
2735 } else {
2736 head = position.to_point(&display_map);
2737 }
2738
2739 if head <= original_buffer_range.start {
2740 tail = original_buffer_range.end;
2741 } else {
2742 tail = original_buffer_range.start;
2743 }
2744 }
2745 SelectMode::Line(original_range) => {
2746 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2747
2748 let position = display_map
2749 .clip_point(position, Bias::Left)
2750 .to_point(&display_map);
2751 let line_start = display_map.prev_line_boundary(position).0;
2752 let next_line_start = buffer.clip_point(
2753 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2754 Bias::Left,
2755 );
2756
2757 if line_start < original_range.start {
2758 head = line_start
2759 } else {
2760 head = next_line_start
2761 }
2762
2763 if head <= original_range.start {
2764 tail = original_range.end;
2765 } else {
2766 tail = original_range.start;
2767 }
2768 }
2769 SelectMode::All => {
2770 return;
2771 }
2772 };
2773
2774 if head < tail {
2775 pending.start = buffer.anchor_before(head);
2776 pending.end = buffer.anchor_before(tail);
2777 pending.reversed = true;
2778 } else {
2779 pending.start = buffer.anchor_before(tail);
2780 pending.end = buffer.anchor_before(head);
2781 pending.reversed = false;
2782 }
2783
2784 self.change_selections(None, cx, |s| {
2785 s.set_pending(pending, mode);
2786 });
2787 } else {
2788 log::error!("update_selection dispatched with no pending selection");
2789 return;
2790 }
2791
2792 self.apply_scroll_delta(scroll_delta, cx);
2793 cx.notify();
2794 }
2795
2796 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2797 self.columnar_selection_tail.take();
2798 if self.selections.pending_anchor().is_some() {
2799 let selections = self.selections.all::<usize>(cx);
2800 self.change_selections(None, cx, |s| {
2801 s.select(selections);
2802 s.clear_pending();
2803 });
2804 }
2805 }
2806
2807 fn select_columns(
2808 &mut self,
2809 tail: DisplayPoint,
2810 head: DisplayPoint,
2811 goal_column: u32,
2812 display_map: &DisplaySnapshot,
2813 cx: &mut ViewContext<Self>,
2814 ) {
2815 let start_row = cmp::min(tail.row(), head.row());
2816 let end_row = cmp::max(tail.row(), head.row());
2817 let start_column = cmp::min(tail.column(), goal_column);
2818 let end_column = cmp::max(tail.column(), goal_column);
2819 let reversed = start_column < tail.column();
2820
2821 let selection_ranges = (start_row.0..=end_row.0)
2822 .map(DisplayRow)
2823 .filter_map(|row| {
2824 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2825 let start = display_map
2826 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2827 .to_point(display_map);
2828 let end = display_map
2829 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2830 .to_point(display_map);
2831 if reversed {
2832 Some(end..start)
2833 } else {
2834 Some(start..end)
2835 }
2836 } else {
2837 None
2838 }
2839 })
2840 .collect::<Vec<_>>();
2841
2842 self.change_selections(None, cx, |s| {
2843 s.select_ranges(selection_ranges);
2844 });
2845 cx.notify();
2846 }
2847
2848 pub fn has_pending_nonempty_selection(&self) -> bool {
2849 let pending_nonempty_selection = match self.selections.pending_anchor() {
2850 Some(Selection { start, end, .. }) => start != end,
2851 None => false,
2852 };
2853
2854 pending_nonempty_selection
2855 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2856 }
2857
2858 pub fn has_pending_selection(&self) -> bool {
2859 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2860 }
2861
2862 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2863 if self.clear_clicked_diff_hunks(cx) {
2864 cx.notify();
2865 return;
2866 }
2867 if self.dismiss_menus_and_popups(true, cx) {
2868 return;
2869 }
2870
2871 if self.mode == EditorMode::Full {
2872 if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
2873 return;
2874 }
2875 }
2876
2877 cx.propagate();
2878 }
2879
2880 pub fn dismiss_menus_and_popups(
2881 &mut self,
2882 should_report_inline_completion_event: bool,
2883 cx: &mut ViewContext<Self>,
2884 ) -> bool {
2885 if self.take_rename(false, cx).is_some() {
2886 return true;
2887 }
2888
2889 if hide_hover(self, cx) {
2890 return true;
2891 }
2892
2893 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2894 return true;
2895 }
2896
2897 if self.hide_context_menu(cx).is_some() {
2898 return true;
2899 }
2900
2901 if self.mouse_context_menu.take().is_some() {
2902 return true;
2903 }
2904
2905 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2906 return true;
2907 }
2908
2909 if self.snippet_stack.pop().is_some() {
2910 return true;
2911 }
2912
2913 if self.mode == EditorMode::Full {
2914 if self.active_diagnostics.is_some() {
2915 self.dismiss_diagnostics(cx);
2916 return true;
2917 }
2918 }
2919
2920 false
2921 }
2922
2923 fn linked_editing_ranges_for(
2924 &self,
2925 selection: Range<text::Anchor>,
2926 cx: &AppContext,
2927 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2928 if self.linked_edit_ranges.is_empty() {
2929 return None;
2930 }
2931 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2932 selection.end.buffer_id.and_then(|end_buffer_id| {
2933 if selection.start.buffer_id != Some(end_buffer_id) {
2934 return None;
2935 }
2936 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2937 let snapshot = buffer.read(cx).snapshot();
2938 self.linked_edit_ranges
2939 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2940 .map(|ranges| (ranges, snapshot, buffer))
2941 })?;
2942 use text::ToOffset as TO;
2943 // find offset from the start of current range to current cursor position
2944 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2945
2946 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2947 let start_difference = start_offset - start_byte_offset;
2948 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2949 let end_difference = end_offset - start_byte_offset;
2950 // Current range has associated linked ranges.
2951 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2952 for range in linked_ranges.iter() {
2953 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2954 let end_offset = start_offset + end_difference;
2955 let start_offset = start_offset + start_difference;
2956 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2957 continue;
2958 }
2959 let start = buffer_snapshot.anchor_after(start_offset);
2960 let end = buffer_snapshot.anchor_after(end_offset);
2961 linked_edits
2962 .entry(buffer.clone())
2963 .or_default()
2964 .push(start..end);
2965 }
2966 Some(linked_edits)
2967 }
2968
2969 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2970 let text: Arc<str> = text.into();
2971
2972 if self.read_only(cx) {
2973 return;
2974 }
2975
2976 let selections = self.selections.all_adjusted(cx);
2977 let mut bracket_inserted = false;
2978 let mut edits = Vec::new();
2979 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2980 let mut new_selections = Vec::with_capacity(selections.len());
2981 let mut new_autoclose_regions = Vec::new();
2982 let snapshot = self.buffer.read(cx).read(cx);
2983
2984 for (selection, autoclose_region) in
2985 self.selections_with_autoclose_regions(selections, &snapshot)
2986 {
2987 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2988 // Determine if the inserted text matches the opening or closing
2989 // bracket of any of this language's bracket pairs.
2990 let mut bracket_pair = None;
2991 let mut is_bracket_pair_start = false;
2992 let mut is_bracket_pair_end = false;
2993 if !text.is_empty() {
2994 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2995 // and they are removing the character that triggered IME popup.
2996 for (pair, enabled) in scope.brackets() {
2997 if !pair.close && !pair.surround {
2998 continue;
2999 }
3000
3001 if enabled && pair.start.ends_with(text.as_ref()) {
3002 bracket_pair = Some(pair.clone());
3003 is_bracket_pair_start = true;
3004 break;
3005 }
3006 if pair.end.as_str() == text.as_ref() {
3007 bracket_pair = Some(pair.clone());
3008 is_bracket_pair_end = true;
3009 break;
3010 }
3011 }
3012 }
3013
3014 if let Some(bracket_pair) = bracket_pair {
3015 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3016 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3017 let auto_surround =
3018 self.use_auto_surround && snapshot_settings.use_auto_surround;
3019 if selection.is_empty() {
3020 if is_bracket_pair_start {
3021 let prefix_len = bracket_pair.start.len() - text.len();
3022
3023 // If the inserted text is a suffix of an opening bracket and the
3024 // selection is preceded by the rest of the opening bracket, then
3025 // insert the closing bracket.
3026 let following_text_allows_autoclose = snapshot
3027 .chars_at(selection.start)
3028 .next()
3029 .map_or(true, |c| scope.should_autoclose_before(c));
3030 let preceding_text_matches_prefix = prefix_len == 0
3031 || (selection.start.column >= (prefix_len as u32)
3032 && snapshot.contains_str_at(
3033 Point::new(
3034 selection.start.row,
3035 selection.start.column - (prefix_len as u32),
3036 ),
3037 &bracket_pair.start[..prefix_len],
3038 ));
3039
3040 if autoclose
3041 && bracket_pair.close
3042 && following_text_allows_autoclose
3043 && preceding_text_matches_prefix
3044 {
3045 let anchor = snapshot.anchor_before(selection.end);
3046 new_selections.push((selection.map(|_| anchor), text.len()));
3047 new_autoclose_regions.push((
3048 anchor,
3049 text.len(),
3050 selection.id,
3051 bracket_pair.clone(),
3052 ));
3053 edits.push((
3054 selection.range(),
3055 format!("{}{}", text, bracket_pair.end).into(),
3056 ));
3057 bracket_inserted = true;
3058 continue;
3059 }
3060 }
3061
3062 if let Some(region) = autoclose_region {
3063 // If the selection is followed by an auto-inserted closing bracket,
3064 // then don't insert that closing bracket again; just move the selection
3065 // past the closing bracket.
3066 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3067 && text.as_ref() == region.pair.end.as_str();
3068 if should_skip {
3069 let anchor = snapshot.anchor_after(selection.end);
3070 new_selections
3071 .push((selection.map(|_| anchor), region.pair.end.len()));
3072 continue;
3073 }
3074 }
3075
3076 let always_treat_brackets_as_autoclosed = snapshot
3077 .settings_at(selection.start, cx)
3078 .always_treat_brackets_as_autoclosed;
3079 if always_treat_brackets_as_autoclosed
3080 && is_bracket_pair_end
3081 && snapshot.contains_str_at(selection.end, text.as_ref())
3082 {
3083 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3084 // and the inserted text is a closing bracket and the selection is followed
3085 // by the closing bracket then move the selection past the closing bracket.
3086 let anchor = snapshot.anchor_after(selection.end);
3087 new_selections.push((selection.map(|_| anchor), text.len()));
3088 continue;
3089 }
3090 }
3091 // If an opening bracket is 1 character long and is typed while
3092 // text is selected, then surround that text with the bracket pair.
3093 else if auto_surround
3094 && bracket_pair.surround
3095 && is_bracket_pair_start
3096 && bracket_pair.start.chars().count() == 1
3097 {
3098 edits.push((selection.start..selection.start, text.clone()));
3099 edits.push((
3100 selection.end..selection.end,
3101 bracket_pair.end.as_str().into(),
3102 ));
3103 bracket_inserted = true;
3104 new_selections.push((
3105 Selection {
3106 id: selection.id,
3107 start: snapshot.anchor_after(selection.start),
3108 end: snapshot.anchor_before(selection.end),
3109 reversed: selection.reversed,
3110 goal: selection.goal,
3111 },
3112 0,
3113 ));
3114 continue;
3115 }
3116 }
3117 }
3118
3119 if self.auto_replace_emoji_shortcode
3120 && selection.is_empty()
3121 && text.as_ref().ends_with(':')
3122 {
3123 if let Some(possible_emoji_short_code) =
3124 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3125 {
3126 if !possible_emoji_short_code.is_empty() {
3127 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3128 let emoji_shortcode_start = Point::new(
3129 selection.start.row,
3130 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3131 );
3132
3133 // Remove shortcode from buffer
3134 edits.push((
3135 emoji_shortcode_start..selection.start,
3136 "".to_string().into(),
3137 ));
3138 new_selections.push((
3139 Selection {
3140 id: selection.id,
3141 start: snapshot.anchor_after(emoji_shortcode_start),
3142 end: snapshot.anchor_before(selection.start),
3143 reversed: selection.reversed,
3144 goal: selection.goal,
3145 },
3146 0,
3147 ));
3148
3149 // Insert emoji
3150 let selection_start_anchor = snapshot.anchor_after(selection.start);
3151 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3152 edits.push((selection.start..selection.end, emoji.to_string().into()));
3153
3154 continue;
3155 }
3156 }
3157 }
3158 }
3159
3160 // If not handling any auto-close operation, then just replace the selected
3161 // text with the given input and move the selection to the end of the
3162 // newly inserted text.
3163 let anchor = snapshot.anchor_after(selection.end);
3164 if !self.linked_edit_ranges.is_empty() {
3165 let start_anchor = snapshot.anchor_before(selection.start);
3166
3167 let is_word_char = text.chars().next().map_or(true, |char| {
3168 let scope = snapshot.language_scope_at(start_anchor.to_offset(&snapshot));
3169 let kind = char_kind(&scope, char);
3170
3171 kind == CharKind::Word
3172 });
3173
3174 if is_word_char {
3175 if let Some(ranges) = self
3176 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3177 {
3178 for (buffer, edits) in ranges {
3179 linked_edits
3180 .entry(buffer.clone())
3181 .or_default()
3182 .extend(edits.into_iter().map(|range| (range, text.clone())));
3183 }
3184 }
3185 }
3186 }
3187
3188 new_selections.push((selection.map(|_| anchor), 0));
3189 edits.push((selection.start..selection.end, text.clone()));
3190 }
3191
3192 drop(snapshot);
3193
3194 self.transact(cx, |this, cx| {
3195 this.buffer.update(cx, |buffer, cx| {
3196 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3197 });
3198 for (buffer, edits) in linked_edits {
3199 buffer.update(cx, |buffer, cx| {
3200 let snapshot = buffer.snapshot();
3201 let edits = edits
3202 .into_iter()
3203 .map(|(range, text)| {
3204 use text::ToPoint as TP;
3205 let end_point = TP::to_point(&range.end, &snapshot);
3206 let start_point = TP::to_point(&range.start, &snapshot);
3207 (start_point..end_point, text)
3208 })
3209 .sorted_by_key(|(range, _)| range.start)
3210 .collect::<Vec<_>>();
3211 buffer.edit(edits, None, cx);
3212 })
3213 }
3214 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3215 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3216 let snapshot = this.buffer.read(cx).read(cx);
3217 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3218 .zip(new_selection_deltas)
3219 .map(|(selection, delta)| Selection {
3220 id: selection.id,
3221 start: selection.start + delta,
3222 end: selection.end + delta,
3223 reversed: selection.reversed,
3224 goal: SelectionGoal::None,
3225 })
3226 .collect::<Vec<_>>();
3227
3228 let mut i = 0;
3229 for (position, delta, selection_id, pair) in new_autoclose_regions {
3230 let position = position.to_offset(&snapshot) + delta;
3231 let start = snapshot.anchor_before(position);
3232 let end = snapshot.anchor_after(position);
3233 while let Some(existing_state) = this.autoclose_regions.get(i) {
3234 match existing_state.range.start.cmp(&start, &snapshot) {
3235 Ordering::Less => i += 1,
3236 Ordering::Greater => break,
3237 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3238 Ordering::Less => i += 1,
3239 Ordering::Equal => break,
3240 Ordering::Greater => break,
3241 },
3242 }
3243 }
3244 this.autoclose_regions.insert(
3245 i,
3246 AutocloseRegion {
3247 selection_id,
3248 range: start..end,
3249 pair,
3250 },
3251 );
3252 }
3253
3254 drop(snapshot);
3255 let had_active_inline_completion = this.has_active_inline_completion(cx);
3256 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3257 s.select(new_selections)
3258 });
3259
3260 if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
3261 if let Some(on_type_format_task) =
3262 this.trigger_on_type_formatting(text.to_string(), cx)
3263 {
3264 on_type_format_task.detach_and_log_err(cx);
3265 }
3266 }
3267
3268 let editor_settings = EditorSettings::get_global(cx);
3269 if bracket_inserted
3270 && (editor_settings.auto_signature_help
3271 || editor_settings.show_signature_help_after_edits)
3272 {
3273 this.show_signature_help(&ShowSignatureHelp, cx);
3274 }
3275
3276 let trigger_in_words = !had_active_inline_completion;
3277 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3278 linked_editing_ranges::refresh_linked_ranges(this, cx);
3279 this.refresh_inline_completion(true, cx);
3280 });
3281 }
3282
3283 fn find_possible_emoji_shortcode_at_position(
3284 snapshot: &MultiBufferSnapshot,
3285 position: Point,
3286 ) -> Option<String> {
3287 let mut chars = Vec::new();
3288 let mut found_colon = false;
3289 for char in snapshot.reversed_chars_at(position).take(100) {
3290 // Found a possible emoji shortcode in the middle of the buffer
3291 if found_colon {
3292 if char.is_whitespace() {
3293 chars.reverse();
3294 return Some(chars.iter().collect());
3295 }
3296 // If the previous character is not a whitespace, we are in the middle of a word
3297 // and we only want to complete the shortcode if the word is made up of other emojis
3298 let mut containing_word = String::new();
3299 for ch in snapshot
3300 .reversed_chars_at(position)
3301 .skip(chars.len() + 1)
3302 .take(100)
3303 {
3304 if ch.is_whitespace() {
3305 break;
3306 }
3307 containing_word.push(ch);
3308 }
3309 let containing_word = containing_word.chars().rev().collect::<String>();
3310 if util::word_consists_of_emojis(containing_word.as_str()) {
3311 chars.reverse();
3312 return Some(chars.iter().collect());
3313 }
3314 }
3315
3316 if char.is_whitespace() || !char.is_ascii() {
3317 return None;
3318 }
3319 if char == ':' {
3320 found_colon = true;
3321 } else {
3322 chars.push(char);
3323 }
3324 }
3325 // Found a possible emoji shortcode at the beginning of the buffer
3326 chars.reverse();
3327 Some(chars.iter().collect())
3328 }
3329
3330 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3331 self.transact(cx, |this, cx| {
3332 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3333 let selections = this.selections.all::<usize>(cx);
3334 let multi_buffer = this.buffer.read(cx);
3335 let buffer = multi_buffer.snapshot(cx);
3336 selections
3337 .iter()
3338 .map(|selection| {
3339 let start_point = selection.start.to_point(&buffer);
3340 let mut indent =
3341 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3342 indent.len = cmp::min(indent.len, start_point.column);
3343 let start = selection.start;
3344 let end = selection.end;
3345 let selection_is_empty = start == end;
3346 let language_scope = buffer.language_scope_at(start);
3347 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3348 &language_scope
3349 {
3350 let leading_whitespace_len = buffer
3351 .reversed_chars_at(start)
3352 .take_while(|c| c.is_whitespace() && *c != '\n')
3353 .map(|c| c.len_utf8())
3354 .sum::<usize>();
3355
3356 let trailing_whitespace_len = buffer
3357 .chars_at(end)
3358 .take_while(|c| c.is_whitespace() && *c != '\n')
3359 .map(|c| c.len_utf8())
3360 .sum::<usize>();
3361
3362 let insert_extra_newline =
3363 language.brackets().any(|(pair, enabled)| {
3364 let pair_start = pair.start.trim_end();
3365 let pair_end = pair.end.trim_start();
3366
3367 enabled
3368 && pair.newline
3369 && buffer.contains_str_at(
3370 end + trailing_whitespace_len,
3371 pair_end,
3372 )
3373 && buffer.contains_str_at(
3374 (start - leading_whitespace_len)
3375 .saturating_sub(pair_start.len()),
3376 pair_start,
3377 )
3378 });
3379
3380 // Comment extension on newline is allowed only for cursor selections
3381 let comment_delimiter = maybe!({
3382 if !selection_is_empty {
3383 return None;
3384 }
3385
3386 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3387 return None;
3388 }
3389
3390 let delimiters = language.line_comment_prefixes();
3391 let max_len_of_delimiter =
3392 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3393 let (snapshot, range) =
3394 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3395
3396 let mut index_of_first_non_whitespace = 0;
3397 let comment_candidate = snapshot
3398 .chars_for_range(range)
3399 .skip_while(|c| {
3400 let should_skip = c.is_whitespace();
3401 if should_skip {
3402 index_of_first_non_whitespace += 1;
3403 }
3404 should_skip
3405 })
3406 .take(max_len_of_delimiter)
3407 .collect::<String>();
3408 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3409 comment_candidate.starts_with(comment_prefix.as_ref())
3410 })?;
3411 let cursor_is_placed_after_comment_marker =
3412 index_of_first_non_whitespace + comment_prefix.len()
3413 <= start_point.column as usize;
3414 if cursor_is_placed_after_comment_marker {
3415 Some(comment_prefix.clone())
3416 } else {
3417 None
3418 }
3419 });
3420 (comment_delimiter, insert_extra_newline)
3421 } else {
3422 (None, false)
3423 };
3424
3425 let capacity_for_delimiter = comment_delimiter
3426 .as_deref()
3427 .map(str::len)
3428 .unwrap_or_default();
3429 let mut new_text =
3430 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3431 new_text.push_str("\n");
3432 new_text.extend(indent.chars());
3433 if let Some(delimiter) = &comment_delimiter {
3434 new_text.push_str(&delimiter);
3435 }
3436 if insert_extra_newline {
3437 new_text = new_text.repeat(2);
3438 }
3439
3440 let anchor = buffer.anchor_after(end);
3441 let new_selection = selection.map(|_| anchor);
3442 (
3443 (start..end, new_text),
3444 (insert_extra_newline, new_selection),
3445 )
3446 })
3447 .unzip()
3448 };
3449
3450 this.edit_with_autoindent(edits, cx);
3451 let buffer = this.buffer.read(cx).snapshot(cx);
3452 let new_selections = selection_fixup_info
3453 .into_iter()
3454 .map(|(extra_newline_inserted, new_selection)| {
3455 let mut cursor = new_selection.end.to_point(&buffer);
3456 if extra_newline_inserted {
3457 cursor.row -= 1;
3458 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3459 }
3460 new_selection.map(|_| cursor)
3461 })
3462 .collect();
3463
3464 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3465 this.refresh_inline_completion(true, cx);
3466 });
3467 }
3468
3469 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3470 let buffer = self.buffer.read(cx);
3471 let snapshot = buffer.snapshot(cx);
3472
3473 let mut edits = Vec::new();
3474 let mut rows = Vec::new();
3475
3476 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3477 let cursor = selection.head();
3478 let row = cursor.row;
3479
3480 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3481
3482 let newline = "\n".to_string();
3483 edits.push((start_of_line..start_of_line, newline));
3484
3485 rows.push(row + rows_inserted as u32);
3486 }
3487
3488 self.transact(cx, |editor, cx| {
3489 editor.edit(edits, cx);
3490
3491 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3492 let mut index = 0;
3493 s.move_cursors_with(|map, _, _| {
3494 let row = rows[index];
3495 index += 1;
3496
3497 let point = Point::new(row, 0);
3498 let boundary = map.next_line_boundary(point).1;
3499 let clipped = map.clip_point(boundary, Bias::Left);
3500
3501 (clipped, SelectionGoal::None)
3502 });
3503 });
3504
3505 let mut indent_edits = Vec::new();
3506 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3507 for row in rows {
3508 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3509 for (row, indent) in indents {
3510 if indent.len == 0 {
3511 continue;
3512 }
3513
3514 let text = match indent.kind {
3515 IndentKind::Space => " ".repeat(indent.len as usize),
3516 IndentKind::Tab => "\t".repeat(indent.len as usize),
3517 };
3518 let point = Point::new(row.0, 0);
3519 indent_edits.push((point..point, text));
3520 }
3521 }
3522 editor.edit(indent_edits, cx);
3523 });
3524 }
3525
3526 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3527 let buffer = self.buffer.read(cx);
3528 let snapshot = buffer.snapshot(cx);
3529
3530 let mut edits = Vec::new();
3531 let mut rows = Vec::new();
3532 let mut rows_inserted = 0;
3533
3534 for selection in self.selections.all_adjusted(cx) {
3535 let cursor = selection.head();
3536 let row = cursor.row;
3537
3538 let point = Point::new(row + 1, 0);
3539 let start_of_line = snapshot.clip_point(point, Bias::Left);
3540
3541 let newline = "\n".to_string();
3542 edits.push((start_of_line..start_of_line, newline));
3543
3544 rows_inserted += 1;
3545 rows.push(row + rows_inserted);
3546 }
3547
3548 self.transact(cx, |editor, cx| {
3549 editor.edit(edits, cx);
3550
3551 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3552 let mut index = 0;
3553 s.move_cursors_with(|map, _, _| {
3554 let row = rows[index];
3555 index += 1;
3556
3557 let point = Point::new(row, 0);
3558 let boundary = map.next_line_boundary(point).1;
3559 let clipped = map.clip_point(boundary, Bias::Left);
3560
3561 (clipped, SelectionGoal::None)
3562 });
3563 });
3564
3565 let mut indent_edits = Vec::new();
3566 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3567 for row in rows {
3568 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3569 for (row, indent) in indents {
3570 if indent.len == 0 {
3571 continue;
3572 }
3573
3574 let text = match indent.kind {
3575 IndentKind::Space => " ".repeat(indent.len as usize),
3576 IndentKind::Tab => "\t".repeat(indent.len as usize),
3577 };
3578 let point = Point::new(row.0, 0);
3579 indent_edits.push((point..point, text));
3580 }
3581 }
3582 editor.edit(indent_edits, cx);
3583 });
3584 }
3585
3586 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3587 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3588 original_indent_columns: Vec::new(),
3589 });
3590 self.insert_with_autoindent_mode(text, autoindent, cx);
3591 }
3592
3593 fn insert_with_autoindent_mode(
3594 &mut self,
3595 text: &str,
3596 autoindent_mode: Option<AutoindentMode>,
3597 cx: &mut ViewContext<Self>,
3598 ) {
3599 if self.read_only(cx) {
3600 return;
3601 }
3602
3603 let text: Arc<str> = text.into();
3604 self.transact(cx, |this, cx| {
3605 let old_selections = this.selections.all_adjusted(cx);
3606 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3607 let anchors = {
3608 let snapshot = buffer.read(cx);
3609 old_selections
3610 .iter()
3611 .map(|s| {
3612 let anchor = snapshot.anchor_after(s.head());
3613 s.map(|_| anchor)
3614 })
3615 .collect::<Vec<_>>()
3616 };
3617 buffer.edit(
3618 old_selections
3619 .iter()
3620 .map(|s| (s.start..s.end, text.clone())),
3621 autoindent_mode,
3622 cx,
3623 );
3624 anchors
3625 });
3626
3627 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3628 s.select_anchors(selection_anchors);
3629 })
3630 });
3631 }
3632
3633 fn trigger_completion_on_input(
3634 &mut self,
3635 text: &str,
3636 trigger_in_words: bool,
3637 cx: &mut ViewContext<Self>,
3638 ) {
3639 if self.is_completion_trigger(text, trigger_in_words, cx) {
3640 self.show_completions(
3641 &ShowCompletions {
3642 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3643 },
3644 cx,
3645 );
3646 } else {
3647 self.hide_context_menu(cx);
3648 }
3649 }
3650
3651 fn is_completion_trigger(
3652 &self,
3653 text: &str,
3654 trigger_in_words: bool,
3655 cx: &mut ViewContext<Self>,
3656 ) -> bool {
3657 let position = self.selections.newest_anchor().head();
3658 let multibuffer = self.buffer.read(cx);
3659 let Some(buffer) = position
3660 .buffer_id
3661 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3662 else {
3663 return false;
3664 };
3665
3666 if let Some(completion_provider) = &self.completion_provider {
3667 completion_provider.is_completion_trigger(
3668 &buffer,
3669 position.text_anchor,
3670 text,
3671 trigger_in_words,
3672 cx,
3673 )
3674 } else {
3675 false
3676 }
3677 }
3678
3679 /// If any empty selections is touching the start of its innermost containing autoclose
3680 /// region, expand it to select the brackets.
3681 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3682 let selections = self.selections.all::<usize>(cx);
3683 let buffer = self.buffer.read(cx).read(cx);
3684 let new_selections = self
3685 .selections_with_autoclose_regions(selections, &buffer)
3686 .map(|(mut selection, region)| {
3687 if !selection.is_empty() {
3688 return selection;
3689 }
3690
3691 if let Some(region) = region {
3692 let mut range = region.range.to_offset(&buffer);
3693 if selection.start == range.start && range.start >= region.pair.start.len() {
3694 range.start -= region.pair.start.len();
3695 if buffer.contains_str_at(range.start, ®ion.pair.start)
3696 && buffer.contains_str_at(range.end, ®ion.pair.end)
3697 {
3698 range.end += region.pair.end.len();
3699 selection.start = range.start;
3700 selection.end = range.end;
3701
3702 return selection;
3703 }
3704 }
3705 }
3706
3707 let always_treat_brackets_as_autoclosed = buffer
3708 .settings_at(selection.start, cx)
3709 .always_treat_brackets_as_autoclosed;
3710
3711 if !always_treat_brackets_as_autoclosed {
3712 return selection;
3713 }
3714
3715 if let Some(scope) = buffer.language_scope_at(selection.start) {
3716 for (pair, enabled) in scope.brackets() {
3717 if !enabled || !pair.close {
3718 continue;
3719 }
3720
3721 if buffer.contains_str_at(selection.start, &pair.end) {
3722 let pair_start_len = pair.start.len();
3723 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3724 {
3725 selection.start -= pair_start_len;
3726 selection.end += pair.end.len();
3727
3728 return selection;
3729 }
3730 }
3731 }
3732 }
3733
3734 selection
3735 })
3736 .collect();
3737
3738 drop(buffer);
3739 self.change_selections(None, cx, |selections| selections.select(new_selections));
3740 }
3741
3742 /// Iterate the given selections, and for each one, find the smallest surrounding
3743 /// autoclose region. This uses the ordering of the selections and the autoclose
3744 /// regions to avoid repeated comparisons.
3745 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3746 &'a self,
3747 selections: impl IntoIterator<Item = Selection<D>>,
3748 buffer: &'a MultiBufferSnapshot,
3749 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3750 let mut i = 0;
3751 let mut regions = self.autoclose_regions.as_slice();
3752 selections.into_iter().map(move |selection| {
3753 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3754
3755 let mut enclosing = None;
3756 while let Some(pair_state) = regions.get(i) {
3757 if pair_state.range.end.to_offset(buffer) < range.start {
3758 regions = ®ions[i + 1..];
3759 i = 0;
3760 } else if pair_state.range.start.to_offset(buffer) > range.end {
3761 break;
3762 } else {
3763 if pair_state.selection_id == selection.id {
3764 enclosing = Some(pair_state);
3765 }
3766 i += 1;
3767 }
3768 }
3769
3770 (selection.clone(), enclosing)
3771 })
3772 }
3773
3774 /// Remove any autoclose regions that no longer contain their selection.
3775 fn invalidate_autoclose_regions(
3776 &mut self,
3777 mut selections: &[Selection<Anchor>],
3778 buffer: &MultiBufferSnapshot,
3779 ) {
3780 self.autoclose_regions.retain(|state| {
3781 let mut i = 0;
3782 while let Some(selection) = selections.get(i) {
3783 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3784 selections = &selections[1..];
3785 continue;
3786 }
3787 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3788 break;
3789 }
3790 if selection.id == state.selection_id {
3791 return true;
3792 } else {
3793 i += 1;
3794 }
3795 }
3796 false
3797 });
3798 }
3799
3800 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3801 let offset = position.to_offset(buffer);
3802 let (word_range, kind) = buffer.surrounding_word(offset);
3803 if offset > word_range.start && kind == Some(CharKind::Word) {
3804 Some(
3805 buffer
3806 .text_for_range(word_range.start..offset)
3807 .collect::<String>(),
3808 )
3809 } else {
3810 None
3811 }
3812 }
3813
3814 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3815 self.refresh_inlay_hints(
3816 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3817 cx,
3818 );
3819 }
3820
3821 pub fn inlay_hints_enabled(&self) -> bool {
3822 self.inlay_hint_cache.enabled
3823 }
3824
3825 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3826 if self.project.is_none() || self.mode != EditorMode::Full {
3827 return;
3828 }
3829
3830 let reason_description = reason.description();
3831 let ignore_debounce = matches!(
3832 reason,
3833 InlayHintRefreshReason::SettingsChange(_)
3834 | InlayHintRefreshReason::Toggle(_)
3835 | InlayHintRefreshReason::ExcerptsRemoved(_)
3836 );
3837 let (invalidate_cache, required_languages) = match reason {
3838 InlayHintRefreshReason::Toggle(enabled) => {
3839 self.inlay_hint_cache.enabled = enabled;
3840 if enabled {
3841 (InvalidationStrategy::RefreshRequested, None)
3842 } else {
3843 self.inlay_hint_cache.clear();
3844 self.splice_inlays(
3845 self.visible_inlay_hints(cx)
3846 .iter()
3847 .map(|inlay| inlay.id)
3848 .collect(),
3849 Vec::new(),
3850 cx,
3851 );
3852 return;
3853 }
3854 }
3855 InlayHintRefreshReason::SettingsChange(new_settings) => {
3856 match self.inlay_hint_cache.update_settings(
3857 &self.buffer,
3858 new_settings,
3859 self.visible_inlay_hints(cx),
3860 cx,
3861 ) {
3862 ControlFlow::Break(Some(InlaySplice {
3863 to_remove,
3864 to_insert,
3865 })) => {
3866 self.splice_inlays(to_remove, to_insert, cx);
3867 return;
3868 }
3869 ControlFlow::Break(None) => return,
3870 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3871 }
3872 }
3873 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3874 if let Some(InlaySplice {
3875 to_remove,
3876 to_insert,
3877 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3878 {
3879 self.splice_inlays(to_remove, to_insert, cx);
3880 }
3881 return;
3882 }
3883 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3884 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3885 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3886 }
3887 InlayHintRefreshReason::RefreshRequested => {
3888 (InvalidationStrategy::RefreshRequested, None)
3889 }
3890 };
3891
3892 if let Some(InlaySplice {
3893 to_remove,
3894 to_insert,
3895 }) = self.inlay_hint_cache.spawn_hint_refresh(
3896 reason_description,
3897 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3898 invalidate_cache,
3899 ignore_debounce,
3900 cx,
3901 ) {
3902 self.splice_inlays(to_remove, to_insert, cx);
3903 }
3904 }
3905
3906 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
3907 self.display_map
3908 .read(cx)
3909 .current_inlays()
3910 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3911 .cloned()
3912 .collect()
3913 }
3914
3915 pub fn excerpts_for_inlay_hints_query(
3916 &self,
3917 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3918 cx: &mut ViewContext<Editor>,
3919 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3920 let Some(project) = self.project.as_ref() else {
3921 return HashMap::default();
3922 };
3923 let project = project.read(cx);
3924 let multi_buffer = self.buffer().read(cx);
3925 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3926 let multi_buffer_visible_start = self
3927 .scroll_manager
3928 .anchor()
3929 .anchor
3930 .to_point(&multi_buffer_snapshot);
3931 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3932 multi_buffer_visible_start
3933 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3934 Bias::Left,
3935 );
3936 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3937 multi_buffer
3938 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
3939 .into_iter()
3940 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3941 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
3942 let buffer = buffer_handle.read(cx);
3943 let buffer_file = project::File::from_dyn(buffer.file())?;
3944 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3945 let worktree_entry = buffer_worktree
3946 .read(cx)
3947 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3948 if worktree_entry.is_ignored {
3949 return None;
3950 }
3951
3952 let language = buffer.language()?;
3953 if let Some(restrict_to_languages) = restrict_to_languages {
3954 if !restrict_to_languages.contains(language) {
3955 return None;
3956 }
3957 }
3958 Some((
3959 excerpt_id,
3960 (
3961 buffer_handle,
3962 buffer.version().clone(),
3963 excerpt_visible_range,
3964 ),
3965 ))
3966 })
3967 .collect()
3968 }
3969
3970 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3971 TextLayoutDetails {
3972 text_system: cx.text_system().clone(),
3973 editor_style: self.style.clone().unwrap(),
3974 rem_size: cx.rem_size(),
3975 scroll_anchor: self.scroll_manager.anchor(),
3976 visible_rows: self.visible_line_count(),
3977 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3978 }
3979 }
3980
3981 fn splice_inlays(
3982 &self,
3983 to_remove: Vec<InlayId>,
3984 to_insert: Vec<Inlay>,
3985 cx: &mut ViewContext<Self>,
3986 ) {
3987 self.display_map.update(cx, |display_map, cx| {
3988 display_map.splice_inlays(to_remove, to_insert, cx);
3989 });
3990 cx.notify();
3991 }
3992
3993 fn trigger_on_type_formatting(
3994 &self,
3995 input: String,
3996 cx: &mut ViewContext<Self>,
3997 ) -> Option<Task<Result<()>>> {
3998 if input.len() != 1 {
3999 return None;
4000 }
4001
4002 let project = self.project.as_ref()?;
4003 let position = self.selections.newest_anchor().head();
4004 let (buffer, buffer_position) = self
4005 .buffer
4006 .read(cx)
4007 .text_anchor_for_position(position, cx)?;
4008
4009 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4010 // hence we do LSP request & edit on host side only — add formats to host's history.
4011 let push_to_lsp_host_history = true;
4012 // If this is not the host, append its history with new edits.
4013 let push_to_client_history = project.read(cx).is_remote();
4014
4015 let on_type_formatting = project.update(cx, |project, cx| {
4016 project.on_type_format(
4017 buffer.clone(),
4018 buffer_position,
4019 input,
4020 push_to_lsp_host_history,
4021 cx,
4022 )
4023 });
4024 Some(cx.spawn(|editor, mut cx| async move {
4025 if let Some(transaction) = on_type_formatting.await? {
4026 if push_to_client_history {
4027 buffer
4028 .update(&mut cx, |buffer, _| {
4029 buffer.push_transaction(transaction, Instant::now());
4030 })
4031 .ok();
4032 }
4033 editor.update(&mut cx, |editor, cx| {
4034 editor.refresh_document_highlights(cx);
4035 })?;
4036 }
4037 Ok(())
4038 }))
4039 }
4040
4041 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4042 if self.pending_rename.is_some() {
4043 return;
4044 }
4045
4046 let Some(provider) = self.completion_provider.as_ref() else {
4047 return;
4048 };
4049
4050 let position = self.selections.newest_anchor().head();
4051 let (buffer, buffer_position) =
4052 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4053 output
4054 } else {
4055 return;
4056 };
4057
4058 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4059 let is_followup_invoke = {
4060 let context_menu_state = self.context_menu.read();
4061 matches!(
4062 context_menu_state.deref(),
4063 Some(ContextMenu::Completions(_))
4064 )
4065 };
4066 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4067 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4068 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(&trigger) => {
4069 CompletionTriggerKind::TRIGGER_CHARACTER
4070 }
4071
4072 _ => CompletionTriggerKind::INVOKED,
4073 };
4074 let completion_context = CompletionContext {
4075 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4076 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4077 Some(String::from(trigger))
4078 } else {
4079 None
4080 }
4081 }),
4082 trigger_kind,
4083 };
4084 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4085
4086 let id = post_inc(&mut self.next_completion_id);
4087 let task = cx.spawn(|this, mut cx| {
4088 async move {
4089 this.update(&mut cx, |this, _| {
4090 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4091 })?;
4092 let completions = completions.await.log_err();
4093 let menu = if let Some(completions) = completions {
4094 let mut menu = CompletionsMenu {
4095 id,
4096 initial_position: position,
4097 match_candidates: completions
4098 .iter()
4099 .enumerate()
4100 .map(|(id, completion)| {
4101 StringMatchCandidate::new(
4102 id,
4103 completion.label.text[completion.label.filter_range.clone()]
4104 .into(),
4105 )
4106 })
4107 .collect(),
4108 buffer: buffer.clone(),
4109 completions: Arc::new(RwLock::new(completions.into())),
4110 matches: Vec::new().into(),
4111 selected_item: 0,
4112 scroll_handle: UniformListScrollHandle::new(),
4113 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4114 DebouncedDelay::new(),
4115 )),
4116 };
4117 menu.filter(query.as_deref(), cx.background_executor().clone())
4118 .await;
4119
4120 if menu.matches.is_empty() {
4121 None
4122 } else {
4123 this.update(&mut cx, |editor, cx| {
4124 let completions = menu.completions.clone();
4125 let matches = menu.matches.clone();
4126
4127 let delay_ms = EditorSettings::get_global(cx)
4128 .completion_documentation_secondary_query_debounce;
4129 let delay = Duration::from_millis(delay_ms);
4130 editor
4131 .completion_documentation_pre_resolve_debounce
4132 .fire_new(delay, cx, |editor, cx| {
4133 CompletionsMenu::pre_resolve_completion_documentation(
4134 buffer,
4135 completions,
4136 matches,
4137 editor,
4138 cx,
4139 )
4140 });
4141 })
4142 .ok();
4143 Some(menu)
4144 }
4145 } else {
4146 None
4147 };
4148
4149 this.update(&mut cx, |this, cx| {
4150 let mut context_menu = this.context_menu.write();
4151 match context_menu.as_ref() {
4152 None => {}
4153
4154 Some(ContextMenu::Completions(prev_menu)) => {
4155 if prev_menu.id > id {
4156 return;
4157 }
4158 }
4159
4160 _ => return,
4161 }
4162
4163 if this.focus_handle.is_focused(cx) && menu.is_some() {
4164 let menu = menu.unwrap();
4165 *context_menu = Some(ContextMenu::Completions(menu));
4166 drop(context_menu);
4167 this.discard_inline_completion(false, cx);
4168 cx.notify();
4169 } else if this.completion_tasks.len() <= 1 {
4170 // If there are no more completion tasks and the last menu was
4171 // empty, we should hide it. If it was already hidden, we should
4172 // also show the copilot completion when available.
4173 drop(context_menu);
4174 if this.hide_context_menu(cx).is_none() {
4175 this.update_visible_inline_completion(cx);
4176 }
4177 }
4178 })?;
4179
4180 Ok::<_, anyhow::Error>(())
4181 }
4182 .log_err()
4183 });
4184
4185 self.completion_tasks.push((id, task));
4186 }
4187
4188 pub fn confirm_completion(
4189 &mut self,
4190 action: &ConfirmCompletion,
4191 cx: &mut ViewContext<Self>,
4192 ) -> Option<Task<Result<()>>> {
4193 use language::ToOffset as _;
4194
4195 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4196 menu
4197 } else {
4198 return None;
4199 };
4200
4201 let mat = completions_menu
4202 .matches
4203 .get(action.item_ix.unwrap_or(completions_menu.selected_item))?;
4204 let buffer_handle = completions_menu.buffer;
4205 let completions = completions_menu.completions.read();
4206 let completion = completions.get(mat.candidate_id)?;
4207 cx.stop_propagation();
4208
4209 let snippet;
4210 let text;
4211
4212 if completion.is_snippet() {
4213 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4214 text = snippet.as_ref().unwrap().text.clone();
4215 } else {
4216 snippet = None;
4217 text = completion.new_text.clone();
4218 };
4219 let selections = self.selections.all::<usize>(cx);
4220 let buffer = buffer_handle.read(cx);
4221 let old_range = completion.old_range.to_offset(buffer);
4222 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4223
4224 let newest_selection = self.selections.newest_anchor();
4225 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4226 return None;
4227 }
4228
4229 let lookbehind = newest_selection
4230 .start
4231 .text_anchor
4232 .to_offset(buffer)
4233 .saturating_sub(old_range.start);
4234 let lookahead = old_range
4235 .end
4236 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4237 let mut common_prefix_len = old_text
4238 .bytes()
4239 .zip(text.bytes())
4240 .take_while(|(a, b)| a == b)
4241 .count();
4242
4243 let snapshot = self.buffer.read(cx).snapshot(cx);
4244 let mut range_to_replace: Option<Range<isize>> = None;
4245 let mut ranges = Vec::new();
4246 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4247 for selection in &selections {
4248 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4249 let start = selection.start.saturating_sub(lookbehind);
4250 let end = selection.end + lookahead;
4251 if selection.id == newest_selection.id {
4252 range_to_replace = Some(
4253 ((start + common_prefix_len) as isize - selection.start as isize)
4254 ..(end as isize - selection.start as isize),
4255 );
4256 }
4257 ranges.push(start + common_prefix_len..end);
4258 } else {
4259 common_prefix_len = 0;
4260 ranges.clear();
4261 ranges.extend(selections.iter().map(|s| {
4262 if s.id == newest_selection.id {
4263 range_to_replace = Some(
4264 old_range.start.to_offset_utf16(&snapshot).0 as isize
4265 - selection.start as isize
4266 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4267 - selection.start as isize,
4268 );
4269 old_range.clone()
4270 } else {
4271 s.start..s.end
4272 }
4273 }));
4274 break;
4275 }
4276 if !self.linked_edit_ranges.is_empty() {
4277 let start_anchor = snapshot.anchor_before(selection.head());
4278 let end_anchor = snapshot.anchor_after(selection.tail());
4279 if let Some(ranges) = self
4280 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4281 {
4282 for (buffer, edits) in ranges {
4283 linked_edits.entry(buffer.clone()).or_default().extend(
4284 edits
4285 .into_iter()
4286 .map(|range| (range, text[common_prefix_len..].to_owned())),
4287 );
4288 }
4289 }
4290 }
4291 }
4292 let text = &text[common_prefix_len..];
4293
4294 cx.emit(EditorEvent::InputHandled {
4295 utf16_range_to_replace: range_to_replace,
4296 text: text.into(),
4297 });
4298
4299 self.transact(cx, |this, cx| {
4300 if let Some(mut snippet) = snippet {
4301 snippet.text = text.to_string();
4302 for tabstop in snippet.tabstops.iter_mut().flatten() {
4303 tabstop.start -= common_prefix_len as isize;
4304 tabstop.end -= common_prefix_len as isize;
4305 }
4306
4307 this.insert_snippet(&ranges, snippet, cx).log_err();
4308 } else {
4309 this.buffer.update(cx, |buffer, cx| {
4310 buffer.edit(
4311 ranges.iter().map(|range| (range.clone(), text)),
4312 this.autoindent_mode.clone(),
4313 cx,
4314 );
4315 });
4316 }
4317 for (buffer, edits) in linked_edits {
4318 buffer.update(cx, |buffer, cx| {
4319 let snapshot = buffer.snapshot();
4320 let edits = edits
4321 .into_iter()
4322 .map(|(range, text)| {
4323 use text::ToPoint as TP;
4324 let end_point = TP::to_point(&range.end, &snapshot);
4325 let start_point = TP::to_point(&range.start, &snapshot);
4326 (start_point..end_point, text)
4327 })
4328 .sorted_by_key(|(range, _)| range.start)
4329 .collect::<Vec<_>>();
4330 buffer.edit(edits, None, cx);
4331 })
4332 }
4333
4334 this.refresh_inline_completion(true, cx);
4335 });
4336
4337 if let Some(confirm) = completion.confirm.as_ref() {
4338 (confirm)(cx);
4339 }
4340
4341 if completion.show_new_completions_on_confirm {
4342 self.show_completions(&ShowCompletions { trigger: None }, cx);
4343 }
4344
4345 let provider = self.completion_provider.as_ref()?;
4346 let apply_edits = provider.apply_additional_edits_for_completion(
4347 buffer_handle,
4348 completion.clone(),
4349 true,
4350 cx,
4351 );
4352
4353 let editor_settings = EditorSettings::get_global(cx);
4354 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4355 // After the code completion is finished, users often want to know what signatures are needed.
4356 // so we should automatically call signature_help
4357 self.show_signature_help(&ShowSignatureHelp, cx);
4358 }
4359
4360 Some(cx.foreground_executor().spawn(async move {
4361 apply_edits.await?;
4362 Ok(())
4363 }))
4364 }
4365
4366 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4367 let mut context_menu = self.context_menu.write();
4368 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4369 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4370 // Toggle if we're selecting the same one
4371 *context_menu = None;
4372 cx.notify();
4373 return;
4374 } else {
4375 // Otherwise, clear it and start a new one
4376 *context_menu = None;
4377 cx.notify();
4378 }
4379 }
4380 drop(context_menu);
4381 let snapshot = self.snapshot(cx);
4382 let deployed_from_indicator = action.deployed_from_indicator;
4383 let mut task = self.code_actions_task.take();
4384 let action = action.clone();
4385 cx.spawn(|editor, mut cx| async move {
4386 while let Some(prev_task) = task {
4387 prev_task.await;
4388 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4389 }
4390
4391 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4392 if editor.focus_handle.is_focused(cx) {
4393 let multibuffer_point = action
4394 .deployed_from_indicator
4395 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4396 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4397 let (buffer, buffer_row) = snapshot
4398 .buffer_snapshot
4399 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4400 .and_then(|(buffer_snapshot, range)| {
4401 editor
4402 .buffer
4403 .read(cx)
4404 .buffer(buffer_snapshot.remote_id())
4405 .map(|buffer| (buffer, range.start.row))
4406 })?;
4407 let (_, code_actions) = editor
4408 .available_code_actions
4409 .clone()
4410 .and_then(|(location, code_actions)| {
4411 let snapshot = location.buffer.read(cx).snapshot();
4412 let point_range = location.range.to_point(&snapshot);
4413 let point_range = point_range.start.row..=point_range.end.row;
4414 if point_range.contains(&buffer_row) {
4415 Some((location, code_actions))
4416 } else {
4417 None
4418 }
4419 })
4420 .unzip();
4421 let buffer_id = buffer.read(cx).remote_id();
4422 let tasks = editor
4423 .tasks
4424 .get(&(buffer_id, buffer_row))
4425 .map(|t| Arc::new(t.to_owned()));
4426 if tasks.is_none() && code_actions.is_none() {
4427 return None;
4428 }
4429
4430 editor.completion_tasks.clear();
4431 editor.discard_inline_completion(false, cx);
4432 let task_context =
4433 tasks
4434 .as_ref()
4435 .zip(editor.project.clone())
4436 .map(|(tasks, project)| {
4437 let position = Point::new(buffer_row, tasks.column);
4438 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4439 let location = Location {
4440 buffer: buffer.clone(),
4441 range: range_start..range_start,
4442 };
4443 // Fill in the environmental variables from the tree-sitter captures
4444 let mut captured_task_variables = TaskVariables::default();
4445 for (capture_name, value) in tasks.extra_variables.clone() {
4446 captured_task_variables.insert(
4447 task::VariableName::Custom(capture_name.into()),
4448 value.clone(),
4449 );
4450 }
4451 project.update(cx, |project, cx| {
4452 project.task_context_for_location(
4453 captured_task_variables,
4454 location,
4455 cx,
4456 )
4457 })
4458 });
4459
4460 Some(cx.spawn(|editor, mut cx| async move {
4461 let task_context = match task_context {
4462 Some(task_context) => task_context.await,
4463 None => None,
4464 };
4465 let resolved_tasks =
4466 tasks.zip(task_context).map(|(tasks, task_context)| {
4467 Arc::new(ResolvedTasks {
4468 templates: tasks
4469 .templates
4470 .iter()
4471 .filter_map(|(kind, template)| {
4472 template
4473 .resolve_task(&kind.to_id_base(), &task_context)
4474 .map(|task| (kind.clone(), task))
4475 })
4476 .collect(),
4477 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4478 multibuffer_point.row,
4479 tasks.column,
4480 )),
4481 })
4482 });
4483 let spawn_straight_away = resolved_tasks
4484 .as_ref()
4485 .map_or(false, |tasks| tasks.templates.len() == 1)
4486 && code_actions
4487 .as_ref()
4488 .map_or(true, |actions| actions.is_empty());
4489 if let Some(task) = editor
4490 .update(&mut cx, |editor, cx| {
4491 *editor.context_menu.write() =
4492 Some(ContextMenu::CodeActions(CodeActionsMenu {
4493 buffer,
4494 actions: CodeActionContents {
4495 tasks: resolved_tasks,
4496 actions: code_actions,
4497 },
4498 selected_item: Default::default(),
4499 scroll_handle: UniformListScrollHandle::default(),
4500 deployed_from_indicator,
4501 }));
4502 if spawn_straight_away {
4503 if let Some(task) = editor.confirm_code_action(
4504 &ConfirmCodeAction { item_ix: Some(0) },
4505 cx,
4506 ) {
4507 cx.notify();
4508 return task;
4509 }
4510 }
4511 cx.notify();
4512 Task::ready(Ok(()))
4513 })
4514 .ok()
4515 {
4516 task.await
4517 } else {
4518 Ok(())
4519 }
4520 }))
4521 } else {
4522 Some(Task::ready(Ok(())))
4523 }
4524 })?;
4525 if let Some(task) = spawned_test_task {
4526 task.await?;
4527 }
4528
4529 Ok::<_, anyhow::Error>(())
4530 })
4531 .detach_and_log_err(cx);
4532 }
4533
4534 pub fn confirm_code_action(
4535 &mut self,
4536 action: &ConfirmCodeAction,
4537 cx: &mut ViewContext<Self>,
4538 ) -> Option<Task<Result<()>>> {
4539 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4540 menu
4541 } else {
4542 return None;
4543 };
4544 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4545 let action = actions_menu.actions.get(action_ix)?;
4546 let title = action.label();
4547 let buffer = actions_menu.buffer;
4548 let workspace = self.workspace()?;
4549
4550 match action {
4551 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4552 workspace.update(cx, |workspace, cx| {
4553 workspace::tasks::schedule_resolved_task(
4554 workspace,
4555 task_source_kind,
4556 resolved_task,
4557 false,
4558 cx,
4559 );
4560
4561 Some(Task::ready(Ok(())))
4562 })
4563 }
4564 CodeActionsItem::CodeAction(action) => {
4565 let apply_code_actions = workspace
4566 .read(cx)
4567 .project()
4568 .clone()
4569 .update(cx, |project, cx| {
4570 project.apply_code_action(buffer, action, true, cx)
4571 });
4572 let workspace = workspace.downgrade();
4573 Some(cx.spawn(|editor, cx| async move {
4574 let project_transaction = apply_code_actions.await?;
4575 Self::open_project_transaction(
4576 &editor,
4577 workspace,
4578 project_transaction,
4579 title,
4580 cx,
4581 )
4582 .await
4583 }))
4584 }
4585 }
4586 }
4587
4588 pub async fn open_project_transaction(
4589 this: &WeakView<Editor>,
4590 workspace: WeakView<Workspace>,
4591 transaction: ProjectTransaction,
4592 title: String,
4593 mut cx: AsyncWindowContext,
4594 ) -> Result<()> {
4595 let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
4596
4597 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4598 cx.update(|cx| {
4599 entries.sort_unstable_by_key(|(buffer, _)| {
4600 buffer.read(cx).file().map(|f| f.path().clone())
4601 });
4602 })?;
4603
4604 // If the project transaction's edits are all contained within this editor, then
4605 // avoid opening a new editor to display them.
4606
4607 if let Some((buffer, transaction)) = entries.first() {
4608 if entries.len() == 1 {
4609 let excerpt = this.update(&mut cx, |editor, cx| {
4610 editor
4611 .buffer()
4612 .read(cx)
4613 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4614 })?;
4615 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4616 if excerpted_buffer == *buffer {
4617 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4618 let excerpt_range = excerpt_range.to_offset(buffer);
4619 buffer
4620 .edited_ranges_for_transaction::<usize>(transaction)
4621 .all(|range| {
4622 excerpt_range.start <= range.start
4623 && excerpt_range.end >= range.end
4624 })
4625 })?;
4626
4627 if all_edits_within_excerpt {
4628 return Ok(());
4629 }
4630 }
4631 }
4632 }
4633 } else {
4634 return Ok(());
4635 }
4636
4637 let mut ranges_to_highlight = Vec::new();
4638 let excerpt_buffer = cx.new_model(|cx| {
4639 let mut multibuffer =
4640 MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
4641 for (buffer_handle, transaction) in &entries {
4642 let buffer = buffer_handle.read(cx);
4643 ranges_to_highlight.extend(
4644 multibuffer.push_excerpts_with_context_lines(
4645 buffer_handle.clone(),
4646 buffer
4647 .edited_ranges_for_transaction::<usize>(transaction)
4648 .collect(),
4649 DEFAULT_MULTIBUFFER_CONTEXT,
4650 cx,
4651 ),
4652 );
4653 }
4654 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4655 multibuffer
4656 })?;
4657
4658 workspace.update(&mut cx, |workspace, cx| {
4659 let project = workspace.project().clone();
4660 let editor =
4661 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4662 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4663 editor.update(cx, |editor, cx| {
4664 editor.highlight_background::<Self>(
4665 &ranges_to_highlight,
4666 |theme| theme.editor_highlighted_line_background,
4667 cx,
4668 );
4669 });
4670 })?;
4671
4672 Ok(())
4673 }
4674
4675 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4676 let project = self.project.clone()?;
4677 let buffer = self.buffer.read(cx);
4678 let newest_selection = self.selections.newest_anchor().clone();
4679 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4680 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4681 if start_buffer != end_buffer {
4682 return None;
4683 }
4684
4685 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4686 cx.background_executor()
4687 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4688 .await;
4689
4690 let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
4691 project.code_actions(&start_buffer, start..end, cx)
4692 }) {
4693 code_actions.await
4694 } else {
4695 Vec::new()
4696 };
4697
4698 this.update(&mut cx, |this, cx| {
4699 this.available_code_actions = if actions.is_empty() {
4700 None
4701 } else {
4702 Some((
4703 Location {
4704 buffer: start_buffer,
4705 range: start..end,
4706 },
4707 actions.into(),
4708 ))
4709 };
4710 cx.notify();
4711 })
4712 .log_err();
4713 }));
4714 None
4715 }
4716
4717 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4718 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4719 self.show_git_blame_inline = false;
4720
4721 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4722 cx.background_executor().timer(delay).await;
4723
4724 this.update(&mut cx, |this, cx| {
4725 this.show_git_blame_inline = true;
4726 cx.notify();
4727 })
4728 .log_err();
4729 }));
4730 }
4731 }
4732
4733 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4734 if self.pending_rename.is_some() {
4735 return None;
4736 }
4737
4738 let project = self.project.clone()?;
4739 let buffer = self.buffer.read(cx);
4740 let newest_selection = self.selections.newest_anchor().clone();
4741 let cursor_position = newest_selection.head();
4742 let (cursor_buffer, cursor_buffer_position) =
4743 buffer.text_anchor_for_position(cursor_position, cx)?;
4744 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4745 if cursor_buffer != tail_buffer {
4746 return None;
4747 }
4748
4749 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4750 cx.background_executor()
4751 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
4752 .await;
4753
4754 let highlights = if let Some(highlights) = project
4755 .update(&mut cx, |project, cx| {
4756 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4757 })
4758 .log_err()
4759 {
4760 highlights.await.log_err()
4761 } else {
4762 None
4763 };
4764
4765 if let Some(highlights) = highlights {
4766 this.update(&mut cx, |this, cx| {
4767 if this.pending_rename.is_some() {
4768 return;
4769 }
4770
4771 let buffer_id = cursor_position.buffer_id;
4772 let buffer = this.buffer.read(cx);
4773 if !buffer
4774 .text_anchor_for_position(cursor_position, cx)
4775 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4776 {
4777 return;
4778 }
4779
4780 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4781 let mut write_ranges = Vec::new();
4782 let mut read_ranges = Vec::new();
4783 for highlight in highlights {
4784 for (excerpt_id, excerpt_range) in
4785 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4786 {
4787 let start = highlight
4788 .range
4789 .start
4790 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4791 let end = highlight
4792 .range
4793 .end
4794 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4795 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4796 continue;
4797 }
4798
4799 let range = Anchor {
4800 buffer_id,
4801 excerpt_id: excerpt_id,
4802 text_anchor: start,
4803 }..Anchor {
4804 buffer_id,
4805 excerpt_id,
4806 text_anchor: end,
4807 };
4808 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4809 write_ranges.push(range);
4810 } else {
4811 read_ranges.push(range);
4812 }
4813 }
4814 }
4815
4816 this.highlight_background::<DocumentHighlightRead>(
4817 &read_ranges,
4818 |theme| theme.editor_document_highlight_read_background,
4819 cx,
4820 );
4821 this.highlight_background::<DocumentHighlightWrite>(
4822 &write_ranges,
4823 |theme| theme.editor_document_highlight_write_background,
4824 cx,
4825 );
4826 cx.notify();
4827 })
4828 .log_err();
4829 }
4830 }));
4831 None
4832 }
4833
4834 fn refresh_inline_completion(
4835 &mut self,
4836 debounce: bool,
4837 cx: &mut ViewContext<Self>,
4838 ) -> Option<()> {
4839 let provider = self.inline_completion_provider()?;
4840 let cursor = self.selections.newest_anchor().head();
4841 let (buffer, cursor_buffer_position) =
4842 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4843 if !self.show_inline_completions
4844 || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
4845 {
4846 self.discard_inline_completion(false, cx);
4847 return None;
4848 }
4849
4850 self.update_visible_inline_completion(cx);
4851 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4852 Some(())
4853 }
4854
4855 fn cycle_inline_completion(
4856 &mut self,
4857 direction: Direction,
4858 cx: &mut ViewContext<Self>,
4859 ) -> Option<()> {
4860 let provider = self.inline_completion_provider()?;
4861 let cursor = self.selections.newest_anchor().head();
4862 let (buffer, cursor_buffer_position) =
4863 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4864 if !self.show_inline_completions
4865 || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
4866 {
4867 return None;
4868 }
4869
4870 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4871 self.update_visible_inline_completion(cx);
4872
4873 Some(())
4874 }
4875
4876 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4877 if !self.has_active_inline_completion(cx) {
4878 self.refresh_inline_completion(false, cx);
4879 return;
4880 }
4881
4882 self.update_visible_inline_completion(cx);
4883 }
4884
4885 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4886 self.show_cursor_names(cx);
4887 }
4888
4889 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4890 self.show_cursor_names = true;
4891 cx.notify();
4892 cx.spawn(|this, mut cx| async move {
4893 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4894 this.update(&mut cx, |this, cx| {
4895 this.show_cursor_names = false;
4896 cx.notify()
4897 })
4898 .ok()
4899 })
4900 .detach();
4901 }
4902
4903 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4904 if self.has_active_inline_completion(cx) {
4905 self.cycle_inline_completion(Direction::Next, cx);
4906 } else {
4907 let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
4908 if is_copilot_disabled {
4909 cx.propagate();
4910 }
4911 }
4912 }
4913
4914 pub fn previous_inline_completion(
4915 &mut self,
4916 _: &PreviousInlineCompletion,
4917 cx: &mut ViewContext<Self>,
4918 ) {
4919 if self.has_active_inline_completion(cx) {
4920 self.cycle_inline_completion(Direction::Prev, cx);
4921 } else {
4922 let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
4923 if is_copilot_disabled {
4924 cx.propagate();
4925 }
4926 }
4927 }
4928
4929 pub fn accept_inline_completion(
4930 &mut self,
4931 _: &AcceptInlineCompletion,
4932 cx: &mut ViewContext<Self>,
4933 ) {
4934 let Some((completion, delete_range)) = self.take_active_inline_completion(cx) else {
4935 return;
4936 };
4937 if let Some(provider) = self.inline_completion_provider() {
4938 provider.accept(cx);
4939 }
4940
4941 cx.emit(EditorEvent::InputHandled {
4942 utf16_range_to_replace: None,
4943 text: completion.text.to_string().into(),
4944 });
4945
4946 if let Some(range) = delete_range {
4947 self.change_selections(None, cx, |s| s.select_ranges([range]))
4948 }
4949 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
4950 self.refresh_inline_completion(true, cx);
4951 cx.notify();
4952 }
4953
4954 pub fn accept_partial_inline_completion(
4955 &mut self,
4956 _: &AcceptPartialInlineCompletion,
4957 cx: &mut ViewContext<Self>,
4958 ) {
4959 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
4960 if let Some((completion, delete_range)) = self.take_active_inline_completion(cx) {
4961 let mut partial_completion = completion
4962 .text
4963 .chars()
4964 .by_ref()
4965 .take_while(|c| c.is_alphabetic())
4966 .collect::<String>();
4967 if partial_completion.is_empty() {
4968 partial_completion = completion
4969 .text
4970 .chars()
4971 .by_ref()
4972 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4973 .collect::<String>();
4974 }
4975
4976 cx.emit(EditorEvent::InputHandled {
4977 utf16_range_to_replace: None,
4978 text: partial_completion.clone().into(),
4979 });
4980
4981 if let Some(range) = delete_range {
4982 self.change_selections(None, cx, |s| s.select_ranges([range]))
4983 }
4984 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4985
4986 self.refresh_inline_completion(true, cx);
4987 cx.notify();
4988 }
4989 }
4990 }
4991
4992 fn discard_inline_completion(
4993 &mut self,
4994 should_report_inline_completion_event: bool,
4995 cx: &mut ViewContext<Self>,
4996 ) -> bool {
4997 if let Some(provider) = self.inline_completion_provider() {
4998 provider.discard(should_report_inline_completion_event, cx);
4999 }
5000
5001 self.take_active_inline_completion(cx).is_some()
5002 }
5003
5004 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5005 if let Some(completion) = self.active_inline_completion.as_ref() {
5006 let buffer = self.buffer.read(cx).read(cx);
5007 completion.0.position.is_valid(&buffer)
5008 } else {
5009 false
5010 }
5011 }
5012
5013 fn take_active_inline_completion(
5014 &mut self,
5015 cx: &mut ViewContext<Self>,
5016 ) -> Option<(Inlay, Option<Range<Anchor>>)> {
5017 let completion = self.active_inline_completion.take()?;
5018 self.display_map.update(cx, |map, cx| {
5019 map.splice_inlays(vec![completion.0.id], Default::default(), cx);
5020 });
5021 let buffer = self.buffer.read(cx).read(cx);
5022
5023 if completion.0.position.is_valid(&buffer) {
5024 Some(completion)
5025 } else {
5026 None
5027 }
5028 }
5029
5030 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5031 let selection = self.selections.newest_anchor();
5032 let cursor = selection.head();
5033
5034 let excerpt_id = cursor.excerpt_id;
5035
5036 if self.context_menu.read().is_none()
5037 && self.completion_tasks.is_empty()
5038 && selection.start == selection.end
5039 {
5040 if let Some(provider) = self.inline_completion_provider() {
5041 if let Some((buffer, cursor_buffer_position)) =
5042 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5043 {
5044 if let Some((text, text_anchor_range)) =
5045 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5046 {
5047 let text = Rope::from(text);
5048 let mut to_remove = Vec::new();
5049 if let Some(completion) = self.active_inline_completion.take() {
5050 to_remove.push(completion.0.id);
5051 }
5052
5053 let completion_inlay =
5054 Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
5055
5056 let multibuffer_anchor_range = text_anchor_range.and_then(|range| {
5057 let snapshot = self.buffer.read(cx).snapshot(cx);
5058 Some(
5059 snapshot.anchor_in_excerpt(excerpt_id, range.start)?
5060 ..snapshot.anchor_in_excerpt(excerpt_id, range.end)?,
5061 )
5062 });
5063 self.active_inline_completion =
5064 Some((completion_inlay.clone(), multibuffer_anchor_range));
5065
5066 self.display_map.update(cx, move |map, cx| {
5067 map.splice_inlays(to_remove, vec![completion_inlay], cx)
5068 });
5069 cx.notify();
5070 return;
5071 }
5072 }
5073 }
5074 }
5075
5076 self.discard_inline_completion(false, cx);
5077 }
5078
5079 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5080 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5081 }
5082
5083 fn render_code_actions_indicator(
5084 &self,
5085 _style: &EditorStyle,
5086 row: DisplayRow,
5087 is_active: bool,
5088 cx: &mut ViewContext<Self>,
5089 ) -> Option<IconButton> {
5090 if self.available_code_actions.is_some() {
5091 Some(
5092 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5093 .shape(ui::IconButtonShape::Square)
5094 .icon_size(IconSize::XSmall)
5095 .icon_color(Color::Muted)
5096 .selected(is_active)
5097 .on_click(cx.listener(move |editor, _e, cx| {
5098 editor.focus(cx);
5099 editor.toggle_code_actions(
5100 &ToggleCodeActions {
5101 deployed_from_indicator: Some(row),
5102 },
5103 cx,
5104 );
5105 })),
5106 )
5107 } else {
5108 None
5109 }
5110 }
5111
5112 fn clear_tasks(&mut self) {
5113 self.tasks.clear()
5114 }
5115
5116 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5117 if let Some(_) = self.tasks.insert(key, value) {
5118 // This case should hopefully be rare, but just in case...
5119 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5120 }
5121 }
5122
5123 fn render_run_indicator(
5124 &self,
5125 _style: &EditorStyle,
5126 is_active: bool,
5127 row: DisplayRow,
5128 cx: &mut ViewContext<Self>,
5129 ) -> IconButton {
5130 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5131 .shape(ui::IconButtonShape::Square)
5132 .icon_size(IconSize::XSmall)
5133 .icon_color(Color::Muted)
5134 .selected(is_active)
5135 .on_click(cx.listener(move |editor, _e, cx| {
5136 editor.focus(cx);
5137 editor.toggle_code_actions(
5138 &ToggleCodeActions {
5139 deployed_from_indicator: Some(row),
5140 },
5141 cx,
5142 );
5143 }))
5144 }
5145
5146 fn close_hunk_diff_button(
5147 &self,
5148 hunk: HoveredHunk,
5149 row: DisplayRow,
5150 cx: &mut ViewContext<Self>,
5151 ) -> IconButton {
5152 IconButton::new(
5153 ("close_hunk_diff_indicator", row.0 as usize),
5154 ui::IconName::Close,
5155 )
5156 .shape(ui::IconButtonShape::Square)
5157 .icon_size(IconSize::XSmall)
5158 .icon_color(Color::Muted)
5159 .tooltip(|cx| Tooltip::for_action("Close hunk diff", &ToggleHunkDiff, cx))
5160 .on_click(cx.listener(move |editor, _e, cx| editor.toggle_hovered_hunk(&hunk, cx)))
5161 }
5162
5163 pub fn context_menu_visible(&self) -> bool {
5164 self.context_menu
5165 .read()
5166 .as_ref()
5167 .map_or(false, |menu| menu.visible())
5168 }
5169
5170 fn render_context_menu(
5171 &self,
5172 cursor_position: DisplayPoint,
5173 style: &EditorStyle,
5174 max_height: Pixels,
5175 cx: &mut ViewContext<Editor>,
5176 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5177 self.context_menu.read().as_ref().map(|menu| {
5178 menu.render(
5179 cursor_position,
5180 style,
5181 max_height,
5182 self.workspace.as_ref().map(|(w, _)| w.clone()),
5183 cx,
5184 )
5185 })
5186 }
5187
5188 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5189 cx.notify();
5190 self.completion_tasks.clear();
5191 let context_menu = self.context_menu.write().take();
5192 if context_menu.is_some() {
5193 self.update_visible_inline_completion(cx);
5194 }
5195 context_menu
5196 }
5197
5198 pub fn insert_snippet(
5199 &mut self,
5200 insertion_ranges: &[Range<usize>],
5201 snippet: Snippet,
5202 cx: &mut ViewContext<Self>,
5203 ) -> Result<()> {
5204 struct Tabstop<T> {
5205 is_end_tabstop: bool,
5206 ranges: Vec<Range<T>>,
5207 }
5208
5209 let tabstops = self.buffer.update(cx, |buffer, cx| {
5210 let snippet_text: Arc<str> = snippet.text.clone().into();
5211 buffer.edit(
5212 insertion_ranges
5213 .iter()
5214 .cloned()
5215 .map(|range| (range, snippet_text.clone())),
5216 Some(AutoindentMode::EachLine),
5217 cx,
5218 );
5219
5220 let snapshot = &*buffer.read(cx);
5221 let snippet = &snippet;
5222 snippet
5223 .tabstops
5224 .iter()
5225 .map(|tabstop| {
5226 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5227 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5228 });
5229 let mut tabstop_ranges = tabstop
5230 .iter()
5231 .flat_map(|tabstop_range| {
5232 let mut delta = 0_isize;
5233 insertion_ranges.iter().map(move |insertion_range| {
5234 let insertion_start = insertion_range.start as isize + delta;
5235 delta +=
5236 snippet.text.len() as isize - insertion_range.len() as isize;
5237
5238 let start = ((insertion_start + tabstop_range.start) as usize)
5239 .min(snapshot.len());
5240 let end = ((insertion_start + tabstop_range.end) as usize)
5241 .min(snapshot.len());
5242 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5243 })
5244 })
5245 .collect::<Vec<_>>();
5246 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5247
5248 Tabstop {
5249 is_end_tabstop,
5250 ranges: tabstop_ranges,
5251 }
5252 })
5253 .collect::<Vec<_>>()
5254 });
5255 if let Some(tabstop) = tabstops.first() {
5256 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5257 s.select_ranges(tabstop.ranges.iter().cloned());
5258 });
5259
5260 // If we're already at the last tabstop and it's at the end of the snippet,
5261 // we're done, we don't need to keep the state around.
5262 if !tabstop.is_end_tabstop {
5263 let ranges = tabstops
5264 .into_iter()
5265 .map(|tabstop| tabstop.ranges)
5266 .collect::<Vec<_>>();
5267 self.snippet_stack.push(SnippetState {
5268 active_index: 0,
5269 ranges,
5270 });
5271 }
5272
5273 // Check whether the just-entered snippet ends with an auto-closable bracket.
5274 if self.autoclose_regions.is_empty() {
5275 let snapshot = self.buffer.read(cx).snapshot(cx);
5276 for selection in &mut self.selections.all::<Point>(cx) {
5277 let selection_head = selection.head();
5278 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5279 continue;
5280 };
5281
5282 let mut bracket_pair = None;
5283 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5284 let prev_chars = snapshot
5285 .reversed_chars_at(selection_head)
5286 .collect::<String>();
5287 for (pair, enabled) in scope.brackets() {
5288 if enabled
5289 && pair.close
5290 && prev_chars.starts_with(pair.start.as_str())
5291 && next_chars.starts_with(pair.end.as_str())
5292 {
5293 bracket_pair = Some(pair.clone());
5294 break;
5295 }
5296 }
5297 if let Some(pair) = bracket_pair {
5298 let start = snapshot.anchor_after(selection_head);
5299 let end = snapshot.anchor_after(selection_head);
5300 self.autoclose_regions.push(AutocloseRegion {
5301 selection_id: selection.id,
5302 range: start..end,
5303 pair,
5304 });
5305 }
5306 }
5307 }
5308 }
5309 Ok(())
5310 }
5311
5312 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5313 self.move_to_snippet_tabstop(Bias::Right, cx)
5314 }
5315
5316 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5317 self.move_to_snippet_tabstop(Bias::Left, cx)
5318 }
5319
5320 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5321 if let Some(mut snippet) = self.snippet_stack.pop() {
5322 match bias {
5323 Bias::Left => {
5324 if snippet.active_index > 0 {
5325 snippet.active_index -= 1;
5326 } else {
5327 self.snippet_stack.push(snippet);
5328 return false;
5329 }
5330 }
5331 Bias::Right => {
5332 if snippet.active_index + 1 < snippet.ranges.len() {
5333 snippet.active_index += 1;
5334 } else {
5335 self.snippet_stack.push(snippet);
5336 return false;
5337 }
5338 }
5339 }
5340 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5341 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5342 s.select_anchor_ranges(current_ranges.iter().cloned())
5343 });
5344 // If snippet state is not at the last tabstop, push it back on the stack
5345 if snippet.active_index + 1 < snippet.ranges.len() {
5346 self.snippet_stack.push(snippet);
5347 }
5348 return true;
5349 }
5350 }
5351
5352 false
5353 }
5354
5355 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5356 self.transact(cx, |this, cx| {
5357 this.select_all(&SelectAll, cx);
5358 this.insert("", cx);
5359 });
5360 }
5361
5362 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5363 self.transact(cx, |this, cx| {
5364 this.select_autoclose_pair(cx);
5365 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5366 if !this.linked_edit_ranges.is_empty() {
5367 let selections = this.selections.all::<MultiBufferPoint>(cx);
5368 let snapshot = this.buffer.read(cx).snapshot(cx);
5369
5370 for selection in selections.iter() {
5371 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5372 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5373 if selection_start.buffer_id != selection_end.buffer_id {
5374 continue;
5375 }
5376 if let Some(ranges) =
5377 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5378 {
5379 for (buffer, entries) in ranges {
5380 linked_ranges.entry(buffer).or_default().extend(entries);
5381 }
5382 }
5383 }
5384 }
5385
5386 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5387 if !this.selections.line_mode {
5388 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5389 for selection in &mut selections {
5390 if selection.is_empty() {
5391 let old_head = selection.head();
5392 let mut new_head =
5393 movement::left(&display_map, old_head.to_display_point(&display_map))
5394 .to_point(&display_map);
5395 if let Some((buffer, line_buffer_range)) = display_map
5396 .buffer_snapshot
5397 .buffer_line_for_row(MultiBufferRow(old_head.row))
5398 {
5399 let indent_size =
5400 buffer.indent_size_for_line(line_buffer_range.start.row);
5401 let indent_len = match indent_size.kind {
5402 IndentKind::Space => {
5403 buffer.settings_at(line_buffer_range.start, cx).tab_size
5404 }
5405 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5406 };
5407 if old_head.column <= indent_size.len && old_head.column > 0 {
5408 let indent_len = indent_len.get();
5409 new_head = cmp::min(
5410 new_head,
5411 MultiBufferPoint::new(
5412 old_head.row,
5413 ((old_head.column - 1) / indent_len) * indent_len,
5414 ),
5415 );
5416 }
5417 }
5418
5419 selection.set_head(new_head, SelectionGoal::None);
5420 }
5421 }
5422 }
5423
5424 this.signature_help_state.set_backspace_pressed(true);
5425 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5426 this.insert("", cx);
5427 let empty_str: Arc<str> = Arc::from("");
5428 for (buffer, edits) in linked_ranges {
5429 let snapshot = buffer.read(cx).snapshot();
5430 use text::ToPoint as TP;
5431
5432 let edits = edits
5433 .into_iter()
5434 .map(|range| {
5435 let end_point = TP::to_point(&range.end, &snapshot);
5436 let mut start_point = TP::to_point(&range.start, &snapshot);
5437
5438 if end_point == start_point {
5439 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5440 .saturating_sub(1);
5441 start_point = TP::to_point(&offset, &snapshot);
5442 };
5443
5444 (start_point..end_point, empty_str.clone())
5445 })
5446 .sorted_by_key(|(range, _)| range.start)
5447 .collect::<Vec<_>>();
5448 buffer.update(cx, |this, cx| {
5449 this.edit(edits, None, cx);
5450 })
5451 }
5452 this.refresh_inline_completion(true, cx);
5453 linked_editing_ranges::refresh_linked_ranges(this, cx);
5454 });
5455 }
5456
5457 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5458 self.transact(cx, |this, cx| {
5459 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5460 let line_mode = s.line_mode;
5461 s.move_with(|map, selection| {
5462 if selection.is_empty() && !line_mode {
5463 let cursor = movement::right(map, selection.head());
5464 selection.end = cursor;
5465 selection.reversed = true;
5466 selection.goal = SelectionGoal::None;
5467 }
5468 })
5469 });
5470 this.insert("", cx);
5471 this.refresh_inline_completion(true, cx);
5472 });
5473 }
5474
5475 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5476 if self.move_to_prev_snippet_tabstop(cx) {
5477 return;
5478 }
5479
5480 self.outdent(&Outdent, cx);
5481 }
5482
5483 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5484 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5485 return;
5486 }
5487
5488 let mut selections = self.selections.all_adjusted(cx);
5489 let buffer = self.buffer.read(cx);
5490 let snapshot = buffer.snapshot(cx);
5491 let rows_iter = selections.iter().map(|s| s.head().row);
5492 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5493
5494 let mut edits = Vec::new();
5495 let mut prev_edited_row = 0;
5496 let mut row_delta = 0;
5497 for selection in &mut selections {
5498 if selection.start.row != prev_edited_row {
5499 row_delta = 0;
5500 }
5501 prev_edited_row = selection.end.row;
5502
5503 // If the selection is non-empty, then increase the indentation of the selected lines.
5504 if !selection.is_empty() {
5505 row_delta =
5506 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5507 continue;
5508 }
5509
5510 // If the selection is empty and the cursor is in the leading whitespace before the
5511 // suggested indentation, then auto-indent the line.
5512 let cursor = selection.head();
5513 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5514 if let Some(suggested_indent) =
5515 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5516 {
5517 if cursor.column < suggested_indent.len
5518 && cursor.column <= current_indent.len
5519 && current_indent.len <= suggested_indent.len
5520 {
5521 selection.start = Point::new(cursor.row, suggested_indent.len);
5522 selection.end = selection.start;
5523 if row_delta == 0 {
5524 edits.extend(Buffer::edit_for_indent_size_adjustment(
5525 cursor.row,
5526 current_indent,
5527 suggested_indent,
5528 ));
5529 row_delta = suggested_indent.len - current_indent.len;
5530 }
5531 continue;
5532 }
5533 }
5534
5535 // Otherwise, insert a hard or soft tab.
5536 let settings = buffer.settings_at(cursor, cx);
5537 let tab_size = if settings.hard_tabs {
5538 IndentSize::tab()
5539 } else {
5540 let tab_size = settings.tab_size.get();
5541 let char_column = snapshot
5542 .text_for_range(Point::new(cursor.row, 0)..cursor)
5543 .flat_map(str::chars)
5544 .count()
5545 + row_delta as usize;
5546 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5547 IndentSize::spaces(chars_to_next_tab_stop)
5548 };
5549 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5550 selection.end = selection.start;
5551 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5552 row_delta += tab_size.len;
5553 }
5554
5555 self.transact(cx, |this, cx| {
5556 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5557 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5558 this.refresh_inline_completion(true, cx);
5559 });
5560 }
5561
5562 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5563 if self.read_only(cx) {
5564 return;
5565 }
5566 let mut selections = self.selections.all::<Point>(cx);
5567 let mut prev_edited_row = 0;
5568 let mut row_delta = 0;
5569 let mut edits = Vec::new();
5570 let buffer = self.buffer.read(cx);
5571 let snapshot = buffer.snapshot(cx);
5572 for selection in &mut selections {
5573 if selection.start.row != prev_edited_row {
5574 row_delta = 0;
5575 }
5576 prev_edited_row = selection.end.row;
5577
5578 row_delta =
5579 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5580 }
5581
5582 self.transact(cx, |this, cx| {
5583 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5584 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5585 });
5586 }
5587
5588 fn indent_selection(
5589 buffer: &MultiBuffer,
5590 snapshot: &MultiBufferSnapshot,
5591 selection: &mut Selection<Point>,
5592 edits: &mut Vec<(Range<Point>, String)>,
5593 delta_for_start_row: u32,
5594 cx: &AppContext,
5595 ) -> u32 {
5596 let settings = buffer.settings_at(selection.start, cx);
5597 let tab_size = settings.tab_size.get();
5598 let indent_kind = if settings.hard_tabs {
5599 IndentKind::Tab
5600 } else {
5601 IndentKind::Space
5602 };
5603 let mut start_row = selection.start.row;
5604 let mut end_row = selection.end.row + 1;
5605
5606 // If a selection ends at the beginning of a line, don't indent
5607 // that last line.
5608 if selection.end.column == 0 && selection.end.row > selection.start.row {
5609 end_row -= 1;
5610 }
5611
5612 // Avoid re-indenting a row that has already been indented by a
5613 // previous selection, but still update this selection's column
5614 // to reflect that indentation.
5615 if delta_for_start_row > 0 {
5616 start_row += 1;
5617 selection.start.column += delta_for_start_row;
5618 if selection.end.row == selection.start.row {
5619 selection.end.column += delta_for_start_row;
5620 }
5621 }
5622
5623 let mut delta_for_end_row = 0;
5624 let has_multiple_rows = start_row + 1 != end_row;
5625 for row in start_row..end_row {
5626 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5627 let indent_delta = match (current_indent.kind, indent_kind) {
5628 (IndentKind::Space, IndentKind::Space) => {
5629 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5630 IndentSize::spaces(columns_to_next_tab_stop)
5631 }
5632 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5633 (_, IndentKind::Tab) => IndentSize::tab(),
5634 };
5635
5636 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5637 0
5638 } else {
5639 selection.start.column
5640 };
5641 let row_start = Point::new(row, start);
5642 edits.push((
5643 row_start..row_start,
5644 indent_delta.chars().collect::<String>(),
5645 ));
5646
5647 // Update this selection's endpoints to reflect the indentation.
5648 if row == selection.start.row {
5649 selection.start.column += indent_delta.len;
5650 }
5651 if row == selection.end.row {
5652 selection.end.column += indent_delta.len;
5653 delta_for_end_row = indent_delta.len;
5654 }
5655 }
5656
5657 if selection.start.row == selection.end.row {
5658 delta_for_start_row + delta_for_end_row
5659 } else {
5660 delta_for_end_row
5661 }
5662 }
5663
5664 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5665 if self.read_only(cx) {
5666 return;
5667 }
5668 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5669 let selections = self.selections.all::<Point>(cx);
5670 let mut deletion_ranges = Vec::new();
5671 let mut last_outdent = None;
5672 {
5673 let buffer = self.buffer.read(cx);
5674 let snapshot = buffer.snapshot(cx);
5675 for selection in &selections {
5676 let settings = buffer.settings_at(selection.start, cx);
5677 let tab_size = settings.tab_size.get();
5678 let mut rows = selection.spanned_rows(false, &display_map);
5679
5680 // Avoid re-outdenting a row that has already been outdented by a
5681 // previous selection.
5682 if let Some(last_row) = last_outdent {
5683 if last_row == rows.start {
5684 rows.start = rows.start.next_row();
5685 }
5686 }
5687 let has_multiple_rows = rows.len() > 1;
5688 for row in rows.iter_rows() {
5689 let indent_size = snapshot.indent_size_for_line(row);
5690 if indent_size.len > 0 {
5691 let deletion_len = match indent_size.kind {
5692 IndentKind::Space => {
5693 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5694 if columns_to_prev_tab_stop == 0 {
5695 tab_size
5696 } else {
5697 columns_to_prev_tab_stop
5698 }
5699 }
5700 IndentKind::Tab => 1,
5701 };
5702 let start = if has_multiple_rows
5703 || deletion_len > selection.start.column
5704 || indent_size.len < selection.start.column
5705 {
5706 0
5707 } else {
5708 selection.start.column - deletion_len
5709 };
5710 deletion_ranges.push(
5711 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5712 );
5713 last_outdent = Some(row);
5714 }
5715 }
5716 }
5717 }
5718
5719 self.transact(cx, |this, cx| {
5720 this.buffer.update(cx, |buffer, cx| {
5721 let empty_str: Arc<str> = Arc::default();
5722 buffer.edit(
5723 deletion_ranges
5724 .into_iter()
5725 .map(|range| (range, empty_str.clone())),
5726 None,
5727 cx,
5728 );
5729 });
5730 let selections = this.selections.all::<usize>(cx);
5731 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5732 });
5733 }
5734
5735 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5736 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5737 let selections = self.selections.all::<Point>(cx);
5738
5739 let mut new_cursors = Vec::new();
5740 let mut edit_ranges = Vec::new();
5741 let mut selections = selections.iter().peekable();
5742 while let Some(selection) = selections.next() {
5743 let mut rows = selection.spanned_rows(false, &display_map);
5744 let goal_display_column = selection.head().to_display_point(&display_map).column();
5745
5746 // Accumulate contiguous regions of rows that we want to delete.
5747 while let Some(next_selection) = selections.peek() {
5748 let next_rows = next_selection.spanned_rows(false, &display_map);
5749 if next_rows.start <= rows.end {
5750 rows.end = next_rows.end;
5751 selections.next().unwrap();
5752 } else {
5753 break;
5754 }
5755 }
5756
5757 let buffer = &display_map.buffer_snapshot;
5758 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5759 let edit_end;
5760 let cursor_buffer_row;
5761 if buffer.max_point().row >= rows.end.0 {
5762 // If there's a line after the range, delete the \n from the end of the row range
5763 // and position the cursor on the next line.
5764 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5765 cursor_buffer_row = rows.end;
5766 } else {
5767 // If there isn't a line after the range, delete the \n from the line before the
5768 // start of the row range and position the cursor there.
5769 edit_start = edit_start.saturating_sub(1);
5770 edit_end = buffer.len();
5771 cursor_buffer_row = rows.start.previous_row();
5772 }
5773
5774 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5775 *cursor.column_mut() =
5776 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5777
5778 new_cursors.push((
5779 selection.id,
5780 buffer.anchor_after(cursor.to_point(&display_map)),
5781 ));
5782 edit_ranges.push(edit_start..edit_end);
5783 }
5784
5785 self.transact(cx, |this, cx| {
5786 let buffer = this.buffer.update(cx, |buffer, cx| {
5787 let empty_str: Arc<str> = Arc::default();
5788 buffer.edit(
5789 edit_ranges
5790 .into_iter()
5791 .map(|range| (range, empty_str.clone())),
5792 None,
5793 cx,
5794 );
5795 buffer.snapshot(cx)
5796 });
5797 let new_selections = new_cursors
5798 .into_iter()
5799 .map(|(id, cursor)| {
5800 let cursor = cursor.to_point(&buffer);
5801 Selection {
5802 id,
5803 start: cursor,
5804 end: cursor,
5805 reversed: false,
5806 goal: SelectionGoal::None,
5807 }
5808 })
5809 .collect();
5810
5811 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5812 s.select(new_selections);
5813 });
5814 });
5815 }
5816
5817 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5818 if self.read_only(cx) {
5819 return;
5820 }
5821 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5822 for selection in self.selections.all::<Point>(cx) {
5823 let start = MultiBufferRow(selection.start.row);
5824 let end = if selection.start.row == selection.end.row {
5825 MultiBufferRow(selection.start.row + 1)
5826 } else {
5827 MultiBufferRow(selection.end.row)
5828 };
5829
5830 if let Some(last_row_range) = row_ranges.last_mut() {
5831 if start <= last_row_range.end {
5832 last_row_range.end = end;
5833 continue;
5834 }
5835 }
5836 row_ranges.push(start..end);
5837 }
5838
5839 let snapshot = self.buffer.read(cx).snapshot(cx);
5840 let mut cursor_positions = Vec::new();
5841 for row_range in &row_ranges {
5842 let anchor = snapshot.anchor_before(Point::new(
5843 row_range.end.previous_row().0,
5844 snapshot.line_len(row_range.end.previous_row()),
5845 ));
5846 cursor_positions.push(anchor..anchor);
5847 }
5848
5849 self.transact(cx, |this, cx| {
5850 for row_range in row_ranges.into_iter().rev() {
5851 for row in row_range.iter_rows().rev() {
5852 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5853 let next_line_row = row.next_row();
5854 let indent = snapshot.indent_size_for_line(next_line_row);
5855 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5856
5857 let replace = if snapshot.line_len(next_line_row) > indent.len {
5858 " "
5859 } else {
5860 ""
5861 };
5862
5863 this.buffer.update(cx, |buffer, cx| {
5864 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5865 });
5866 }
5867 }
5868
5869 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5870 s.select_anchor_ranges(cursor_positions)
5871 });
5872 });
5873 }
5874
5875 pub fn sort_lines_case_sensitive(
5876 &mut self,
5877 _: &SortLinesCaseSensitive,
5878 cx: &mut ViewContext<Self>,
5879 ) {
5880 self.manipulate_lines(cx, |lines| lines.sort())
5881 }
5882
5883 pub fn sort_lines_case_insensitive(
5884 &mut self,
5885 _: &SortLinesCaseInsensitive,
5886 cx: &mut ViewContext<Self>,
5887 ) {
5888 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5889 }
5890
5891 pub fn unique_lines_case_insensitive(
5892 &mut self,
5893 _: &UniqueLinesCaseInsensitive,
5894 cx: &mut ViewContext<Self>,
5895 ) {
5896 self.manipulate_lines(cx, |lines| {
5897 let mut seen = HashSet::default();
5898 lines.retain(|line| seen.insert(line.to_lowercase()));
5899 })
5900 }
5901
5902 pub fn unique_lines_case_sensitive(
5903 &mut self,
5904 _: &UniqueLinesCaseSensitive,
5905 cx: &mut ViewContext<Self>,
5906 ) {
5907 self.manipulate_lines(cx, |lines| {
5908 let mut seen = HashSet::default();
5909 lines.retain(|line| seen.insert(*line));
5910 })
5911 }
5912
5913 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
5914 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
5915 if !revert_changes.is_empty() {
5916 self.transact(cx, |editor, cx| {
5917 editor.revert(revert_changes, cx);
5918 });
5919 }
5920 }
5921
5922 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
5923 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
5924 let project_path = buffer.read(cx).project_path(cx)?;
5925 let project = self.project.as_ref()?.read(cx);
5926 let entry = project.entry_for_path(&project_path, cx)?;
5927 let abs_path = project.absolute_path(&project_path, cx)?;
5928 let parent = if entry.is_symlink {
5929 abs_path.canonicalize().ok()?
5930 } else {
5931 abs_path
5932 }
5933 .parent()?
5934 .to_path_buf();
5935 Some(parent)
5936 }) {
5937 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
5938 }
5939 }
5940
5941 fn gather_revert_changes(
5942 &mut self,
5943 selections: &[Selection<Anchor>],
5944 cx: &mut ViewContext<'_, Editor>,
5945 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
5946 let mut revert_changes = HashMap::default();
5947 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
5948 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
5949 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
5950 }
5951 revert_changes
5952 }
5953
5954 pub fn prepare_revert_change(
5955 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
5956 multi_buffer: &Model<MultiBuffer>,
5957 hunk: &DiffHunk<MultiBufferRow>,
5958 cx: &AppContext,
5959 ) -> Option<()> {
5960 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
5961 let buffer = buffer.read(cx);
5962 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
5963 let buffer_snapshot = buffer.snapshot();
5964 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
5965 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
5966 probe
5967 .0
5968 .start
5969 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
5970 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
5971 }) {
5972 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
5973 Some(())
5974 } else {
5975 None
5976 }
5977 }
5978
5979 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
5980 self.manipulate_lines(cx, |lines| lines.reverse())
5981 }
5982
5983 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
5984 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
5985 }
5986
5987 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
5988 where
5989 Fn: FnMut(&mut Vec<&str>),
5990 {
5991 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5992 let buffer = self.buffer.read(cx).snapshot(cx);
5993
5994 let mut edits = Vec::new();
5995
5996 let selections = self.selections.all::<Point>(cx);
5997 let mut selections = selections.iter().peekable();
5998 let mut contiguous_row_selections = Vec::new();
5999 let mut new_selections = Vec::new();
6000 let mut added_lines = 0;
6001 let mut removed_lines = 0;
6002
6003 while let Some(selection) = selections.next() {
6004 let (start_row, end_row) = consume_contiguous_rows(
6005 &mut contiguous_row_selections,
6006 selection,
6007 &display_map,
6008 &mut selections,
6009 );
6010
6011 let start_point = Point::new(start_row.0, 0);
6012 let end_point = Point::new(
6013 end_row.previous_row().0,
6014 buffer.line_len(end_row.previous_row()),
6015 );
6016 let text = buffer
6017 .text_for_range(start_point..end_point)
6018 .collect::<String>();
6019
6020 let mut lines = text.split('\n').collect_vec();
6021
6022 let lines_before = lines.len();
6023 callback(&mut lines);
6024 let lines_after = lines.len();
6025
6026 edits.push((start_point..end_point, lines.join("\n")));
6027
6028 // Selections must change based on added and removed line count
6029 let start_row =
6030 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6031 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6032 new_selections.push(Selection {
6033 id: selection.id,
6034 start: start_row,
6035 end: end_row,
6036 goal: SelectionGoal::None,
6037 reversed: selection.reversed,
6038 });
6039
6040 if lines_after > lines_before {
6041 added_lines += lines_after - lines_before;
6042 } else if lines_before > lines_after {
6043 removed_lines += lines_before - lines_after;
6044 }
6045 }
6046
6047 self.transact(cx, |this, cx| {
6048 let buffer = this.buffer.update(cx, |buffer, cx| {
6049 buffer.edit(edits, None, cx);
6050 buffer.snapshot(cx)
6051 });
6052
6053 // Recalculate offsets on newly edited buffer
6054 let new_selections = new_selections
6055 .iter()
6056 .map(|s| {
6057 let start_point = Point::new(s.start.0, 0);
6058 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6059 Selection {
6060 id: s.id,
6061 start: buffer.point_to_offset(start_point),
6062 end: buffer.point_to_offset(end_point),
6063 goal: s.goal,
6064 reversed: s.reversed,
6065 }
6066 })
6067 .collect();
6068
6069 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6070 s.select(new_selections);
6071 });
6072
6073 this.request_autoscroll(Autoscroll::fit(), cx);
6074 });
6075 }
6076
6077 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6078 self.manipulate_text(cx, |text| text.to_uppercase())
6079 }
6080
6081 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6082 self.manipulate_text(cx, |text| text.to_lowercase())
6083 }
6084
6085 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6086 self.manipulate_text(cx, |text| {
6087 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6088 // https://github.com/rutrum/convert-case/issues/16
6089 text.split('\n')
6090 .map(|line| line.to_case(Case::Title))
6091 .join("\n")
6092 })
6093 }
6094
6095 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6096 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6097 }
6098
6099 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6100 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6101 }
6102
6103 pub fn convert_to_upper_camel_case(
6104 &mut self,
6105 _: &ConvertToUpperCamelCase,
6106 cx: &mut ViewContext<Self>,
6107 ) {
6108 self.manipulate_text(cx, |text| {
6109 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6110 // https://github.com/rutrum/convert-case/issues/16
6111 text.split('\n')
6112 .map(|line| line.to_case(Case::UpperCamel))
6113 .join("\n")
6114 })
6115 }
6116
6117 pub fn convert_to_lower_camel_case(
6118 &mut self,
6119 _: &ConvertToLowerCamelCase,
6120 cx: &mut ViewContext<Self>,
6121 ) {
6122 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6123 }
6124
6125 pub fn convert_to_opposite_case(
6126 &mut self,
6127 _: &ConvertToOppositeCase,
6128 cx: &mut ViewContext<Self>,
6129 ) {
6130 self.manipulate_text(cx, |text| {
6131 text.chars()
6132 .fold(String::with_capacity(text.len()), |mut t, c| {
6133 if c.is_uppercase() {
6134 t.extend(c.to_lowercase());
6135 } else {
6136 t.extend(c.to_uppercase());
6137 }
6138 t
6139 })
6140 })
6141 }
6142
6143 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6144 where
6145 Fn: FnMut(&str) -> String,
6146 {
6147 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6148 let buffer = self.buffer.read(cx).snapshot(cx);
6149
6150 let mut new_selections = Vec::new();
6151 let mut edits = Vec::new();
6152 let mut selection_adjustment = 0i32;
6153
6154 for selection in self.selections.all::<usize>(cx) {
6155 let selection_is_empty = selection.is_empty();
6156
6157 let (start, end) = if selection_is_empty {
6158 let word_range = movement::surrounding_word(
6159 &display_map,
6160 selection.start.to_display_point(&display_map),
6161 );
6162 let start = word_range.start.to_offset(&display_map, Bias::Left);
6163 let end = word_range.end.to_offset(&display_map, Bias::Left);
6164 (start, end)
6165 } else {
6166 (selection.start, selection.end)
6167 };
6168
6169 let text = buffer.text_for_range(start..end).collect::<String>();
6170 let old_length = text.len() as i32;
6171 let text = callback(&text);
6172
6173 new_selections.push(Selection {
6174 start: (start as i32 - selection_adjustment) as usize,
6175 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6176 goal: SelectionGoal::None,
6177 ..selection
6178 });
6179
6180 selection_adjustment += old_length - text.len() as i32;
6181
6182 edits.push((start..end, text));
6183 }
6184
6185 self.transact(cx, |this, cx| {
6186 this.buffer.update(cx, |buffer, cx| {
6187 buffer.edit(edits, None, cx);
6188 });
6189
6190 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6191 s.select(new_selections);
6192 });
6193
6194 this.request_autoscroll(Autoscroll::fit(), cx);
6195 });
6196 }
6197
6198 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6199 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6200 let buffer = &display_map.buffer_snapshot;
6201 let selections = self.selections.all::<Point>(cx);
6202
6203 let mut edits = Vec::new();
6204 let mut selections_iter = selections.iter().peekable();
6205 while let Some(selection) = selections_iter.next() {
6206 // Avoid duplicating the same lines twice.
6207 let mut rows = selection.spanned_rows(false, &display_map);
6208
6209 while let Some(next_selection) = selections_iter.peek() {
6210 let next_rows = next_selection.spanned_rows(false, &display_map);
6211 if next_rows.start < rows.end {
6212 rows.end = next_rows.end;
6213 selections_iter.next().unwrap();
6214 } else {
6215 break;
6216 }
6217 }
6218
6219 // Copy the text from the selected row region and splice it either at the start
6220 // or end of the region.
6221 let start = Point::new(rows.start.0, 0);
6222 let end = Point::new(
6223 rows.end.previous_row().0,
6224 buffer.line_len(rows.end.previous_row()),
6225 );
6226 let text = buffer
6227 .text_for_range(start..end)
6228 .chain(Some("\n"))
6229 .collect::<String>();
6230 let insert_location = if upwards {
6231 Point::new(rows.end.0, 0)
6232 } else {
6233 start
6234 };
6235 edits.push((insert_location..insert_location, text));
6236 }
6237
6238 self.transact(cx, |this, cx| {
6239 this.buffer.update(cx, |buffer, cx| {
6240 buffer.edit(edits, None, cx);
6241 });
6242
6243 this.request_autoscroll(Autoscroll::fit(), cx);
6244 });
6245 }
6246
6247 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6248 self.duplicate_line(true, cx);
6249 }
6250
6251 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6252 self.duplicate_line(false, cx);
6253 }
6254
6255 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6256 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6257 let buffer = self.buffer.read(cx).snapshot(cx);
6258
6259 let mut edits = Vec::new();
6260 let mut unfold_ranges = Vec::new();
6261 let mut refold_ranges = Vec::new();
6262
6263 let selections = self.selections.all::<Point>(cx);
6264 let mut selections = selections.iter().peekable();
6265 let mut contiguous_row_selections = Vec::new();
6266 let mut new_selections = Vec::new();
6267
6268 while let Some(selection) = selections.next() {
6269 // Find all the selections that span a contiguous row range
6270 let (start_row, end_row) = consume_contiguous_rows(
6271 &mut contiguous_row_selections,
6272 selection,
6273 &display_map,
6274 &mut selections,
6275 );
6276
6277 // Move the text spanned by the row range to be before the line preceding the row range
6278 if start_row.0 > 0 {
6279 let range_to_move = Point::new(
6280 start_row.previous_row().0,
6281 buffer.line_len(start_row.previous_row()),
6282 )
6283 ..Point::new(
6284 end_row.previous_row().0,
6285 buffer.line_len(end_row.previous_row()),
6286 );
6287 let insertion_point = display_map
6288 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6289 .0;
6290
6291 // Don't move lines across excerpts
6292 if buffer
6293 .excerpt_boundaries_in_range((
6294 Bound::Excluded(insertion_point),
6295 Bound::Included(range_to_move.end),
6296 ))
6297 .next()
6298 .is_none()
6299 {
6300 let text = buffer
6301 .text_for_range(range_to_move.clone())
6302 .flat_map(|s| s.chars())
6303 .skip(1)
6304 .chain(['\n'])
6305 .collect::<String>();
6306
6307 edits.push((
6308 buffer.anchor_after(range_to_move.start)
6309 ..buffer.anchor_before(range_to_move.end),
6310 String::new(),
6311 ));
6312 let insertion_anchor = buffer.anchor_after(insertion_point);
6313 edits.push((insertion_anchor..insertion_anchor, text));
6314
6315 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6316
6317 // Move selections up
6318 new_selections.extend(contiguous_row_selections.drain(..).map(
6319 |mut selection| {
6320 selection.start.row -= row_delta;
6321 selection.end.row -= row_delta;
6322 selection
6323 },
6324 ));
6325
6326 // Move folds up
6327 unfold_ranges.push(range_to_move.clone());
6328 for fold in display_map.folds_in_range(
6329 buffer.anchor_before(range_to_move.start)
6330 ..buffer.anchor_after(range_to_move.end),
6331 ) {
6332 let mut start = fold.range.start.to_point(&buffer);
6333 let mut end = fold.range.end.to_point(&buffer);
6334 start.row -= row_delta;
6335 end.row -= row_delta;
6336 refold_ranges.push((start..end, fold.placeholder.clone()));
6337 }
6338 }
6339 }
6340
6341 // If we didn't move line(s), preserve the existing selections
6342 new_selections.append(&mut contiguous_row_selections);
6343 }
6344
6345 self.transact(cx, |this, cx| {
6346 this.unfold_ranges(unfold_ranges, true, true, cx);
6347 this.buffer.update(cx, |buffer, cx| {
6348 for (range, text) in edits {
6349 buffer.edit([(range, text)], None, cx);
6350 }
6351 });
6352 this.fold_ranges(refold_ranges, true, cx);
6353 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6354 s.select(new_selections);
6355 })
6356 });
6357 }
6358
6359 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6360 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6361 let buffer = self.buffer.read(cx).snapshot(cx);
6362
6363 let mut edits = Vec::new();
6364 let mut unfold_ranges = Vec::new();
6365 let mut refold_ranges = Vec::new();
6366
6367 let selections = self.selections.all::<Point>(cx);
6368 let mut selections = selections.iter().peekable();
6369 let mut contiguous_row_selections = Vec::new();
6370 let mut new_selections = Vec::new();
6371
6372 while let Some(selection) = selections.next() {
6373 // Find all the selections that span a contiguous row range
6374 let (start_row, end_row) = consume_contiguous_rows(
6375 &mut contiguous_row_selections,
6376 selection,
6377 &display_map,
6378 &mut selections,
6379 );
6380
6381 // Move the text spanned by the row range to be after the last line of the row range
6382 if end_row.0 <= buffer.max_point().row {
6383 let range_to_move =
6384 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6385 let insertion_point = display_map
6386 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6387 .0;
6388
6389 // Don't move lines across excerpt boundaries
6390 if buffer
6391 .excerpt_boundaries_in_range((
6392 Bound::Excluded(range_to_move.start),
6393 Bound::Included(insertion_point),
6394 ))
6395 .next()
6396 .is_none()
6397 {
6398 let mut text = String::from("\n");
6399 text.extend(buffer.text_for_range(range_to_move.clone()));
6400 text.pop(); // Drop trailing newline
6401 edits.push((
6402 buffer.anchor_after(range_to_move.start)
6403 ..buffer.anchor_before(range_to_move.end),
6404 String::new(),
6405 ));
6406 let insertion_anchor = buffer.anchor_after(insertion_point);
6407 edits.push((insertion_anchor..insertion_anchor, text));
6408
6409 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6410
6411 // Move selections down
6412 new_selections.extend(contiguous_row_selections.drain(..).map(
6413 |mut selection| {
6414 selection.start.row += row_delta;
6415 selection.end.row += row_delta;
6416 selection
6417 },
6418 ));
6419
6420 // Move folds down
6421 unfold_ranges.push(range_to_move.clone());
6422 for fold in display_map.folds_in_range(
6423 buffer.anchor_before(range_to_move.start)
6424 ..buffer.anchor_after(range_to_move.end),
6425 ) {
6426 let mut start = fold.range.start.to_point(&buffer);
6427 let mut end = fold.range.end.to_point(&buffer);
6428 start.row += row_delta;
6429 end.row += row_delta;
6430 refold_ranges.push((start..end, fold.placeholder.clone()));
6431 }
6432 }
6433 }
6434
6435 // If we didn't move line(s), preserve the existing selections
6436 new_selections.append(&mut contiguous_row_selections);
6437 }
6438
6439 self.transact(cx, |this, cx| {
6440 this.unfold_ranges(unfold_ranges, true, true, cx);
6441 this.buffer.update(cx, |buffer, cx| {
6442 for (range, text) in edits {
6443 buffer.edit([(range, text)], None, cx);
6444 }
6445 });
6446 this.fold_ranges(refold_ranges, true, cx);
6447 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6448 });
6449 }
6450
6451 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6452 let text_layout_details = &self.text_layout_details(cx);
6453 self.transact(cx, |this, cx| {
6454 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6455 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6456 let line_mode = s.line_mode;
6457 s.move_with(|display_map, selection| {
6458 if !selection.is_empty() || line_mode {
6459 return;
6460 }
6461
6462 let mut head = selection.head();
6463 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6464 if head.column() == display_map.line_len(head.row()) {
6465 transpose_offset = display_map
6466 .buffer_snapshot
6467 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6468 }
6469
6470 if transpose_offset == 0 {
6471 return;
6472 }
6473
6474 *head.column_mut() += 1;
6475 head = display_map.clip_point(head, Bias::Right);
6476 let goal = SelectionGoal::HorizontalPosition(
6477 display_map
6478 .x_for_display_point(head, &text_layout_details)
6479 .into(),
6480 );
6481 selection.collapse_to(head, goal);
6482
6483 let transpose_start = display_map
6484 .buffer_snapshot
6485 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6486 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6487 let transpose_end = display_map
6488 .buffer_snapshot
6489 .clip_offset(transpose_offset + 1, Bias::Right);
6490 if let Some(ch) =
6491 display_map.buffer_snapshot.chars_at(transpose_start).next()
6492 {
6493 edits.push((transpose_start..transpose_offset, String::new()));
6494 edits.push((transpose_end..transpose_end, ch.to_string()));
6495 }
6496 }
6497 });
6498 edits
6499 });
6500 this.buffer
6501 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6502 let selections = this.selections.all::<usize>(cx);
6503 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6504 s.select(selections);
6505 });
6506 });
6507 }
6508
6509 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6510 let mut text = String::new();
6511 let buffer = self.buffer.read(cx).snapshot(cx);
6512 let mut selections = self.selections.all::<Point>(cx);
6513 let mut clipboard_selections = Vec::with_capacity(selections.len());
6514 {
6515 let max_point = buffer.max_point();
6516 let mut is_first = true;
6517 for selection in &mut selections {
6518 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6519 if is_entire_line {
6520 selection.start = Point::new(selection.start.row, 0);
6521 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6522 selection.goal = SelectionGoal::None;
6523 }
6524 if is_first {
6525 is_first = false;
6526 } else {
6527 text += "\n";
6528 }
6529 let mut len = 0;
6530 for chunk in buffer.text_for_range(selection.start..selection.end) {
6531 text.push_str(chunk);
6532 len += chunk.len();
6533 }
6534 clipboard_selections.push(ClipboardSelection {
6535 len,
6536 is_entire_line,
6537 first_line_indent: buffer
6538 .indent_size_for_line(MultiBufferRow(selection.start.row))
6539 .len,
6540 });
6541 }
6542 }
6543
6544 self.transact(cx, |this, cx| {
6545 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6546 s.select(selections);
6547 });
6548 this.insert("", cx);
6549 cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
6550 });
6551 }
6552
6553 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6554 let selections = self.selections.all::<Point>(cx);
6555 let buffer = self.buffer.read(cx).read(cx);
6556 let mut text = String::new();
6557
6558 let mut clipboard_selections = Vec::with_capacity(selections.len());
6559 {
6560 let max_point = buffer.max_point();
6561 let mut is_first = true;
6562 for selection in selections.iter() {
6563 let mut start = selection.start;
6564 let mut end = selection.end;
6565 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6566 if is_entire_line {
6567 start = Point::new(start.row, 0);
6568 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6569 }
6570 if is_first {
6571 is_first = false;
6572 } else {
6573 text += "\n";
6574 }
6575 let mut len = 0;
6576 for chunk in buffer.text_for_range(start..end) {
6577 text.push_str(chunk);
6578 len += chunk.len();
6579 }
6580 clipboard_selections.push(ClipboardSelection {
6581 len,
6582 is_entire_line,
6583 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6584 });
6585 }
6586 }
6587
6588 cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
6589 }
6590
6591 pub fn do_paste(
6592 &mut self,
6593 text: &String,
6594 clipboard_selections: Option<Vec<ClipboardSelection>>,
6595 handle_entire_lines: bool,
6596 cx: &mut ViewContext<Self>,
6597 ) {
6598 if self.read_only(cx) {
6599 return;
6600 }
6601
6602 let clipboard_text = Cow::Borrowed(text);
6603
6604 self.transact(cx, |this, cx| {
6605 if let Some(mut clipboard_selections) = clipboard_selections {
6606 let old_selections = this.selections.all::<usize>(cx);
6607 let all_selections_were_entire_line =
6608 clipboard_selections.iter().all(|s| s.is_entire_line);
6609 let first_selection_indent_column =
6610 clipboard_selections.first().map(|s| s.first_line_indent);
6611 if clipboard_selections.len() != old_selections.len() {
6612 clipboard_selections.drain(..);
6613 }
6614
6615 this.buffer.update(cx, |buffer, cx| {
6616 let snapshot = buffer.read(cx);
6617 let mut start_offset = 0;
6618 let mut edits = Vec::new();
6619 let mut original_indent_columns = Vec::new();
6620 for (ix, selection) in old_selections.iter().enumerate() {
6621 let to_insert;
6622 let entire_line;
6623 let original_indent_column;
6624 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6625 let end_offset = start_offset + clipboard_selection.len;
6626 to_insert = &clipboard_text[start_offset..end_offset];
6627 entire_line = clipboard_selection.is_entire_line;
6628 start_offset = end_offset + 1;
6629 original_indent_column = Some(clipboard_selection.first_line_indent);
6630 } else {
6631 to_insert = clipboard_text.as_str();
6632 entire_line = all_selections_were_entire_line;
6633 original_indent_column = first_selection_indent_column
6634 }
6635
6636 // If the corresponding selection was empty when this slice of the
6637 // clipboard text was written, then the entire line containing the
6638 // selection was copied. If this selection is also currently empty,
6639 // then paste the line before the current line of the buffer.
6640 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6641 let column = selection.start.to_point(&snapshot).column as usize;
6642 let line_start = selection.start - column;
6643 line_start..line_start
6644 } else {
6645 selection.range()
6646 };
6647
6648 edits.push((range, to_insert));
6649 original_indent_columns.extend(original_indent_column);
6650 }
6651 drop(snapshot);
6652
6653 buffer.edit(
6654 edits,
6655 Some(AutoindentMode::Block {
6656 original_indent_columns,
6657 }),
6658 cx,
6659 );
6660 });
6661
6662 let selections = this.selections.all::<usize>(cx);
6663 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6664 } else {
6665 this.insert(&clipboard_text, cx);
6666 }
6667 });
6668 }
6669
6670 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
6671 if let Some(item) = cx.read_from_clipboard() {
6672 self.do_paste(
6673 item.text(),
6674 item.metadata::<Vec<ClipboardSelection>>(),
6675 true,
6676 cx,
6677 )
6678 };
6679 }
6680
6681 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
6682 if self.read_only(cx) {
6683 return;
6684 }
6685
6686 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
6687 if let Some((selections, _)) =
6688 self.selection_history.transaction(transaction_id).cloned()
6689 {
6690 self.change_selections(None, cx, |s| {
6691 s.select_anchors(selections.to_vec());
6692 });
6693 }
6694 self.request_autoscroll(Autoscroll::fit(), cx);
6695 self.unmark_text(cx);
6696 self.refresh_inline_completion(true, cx);
6697 cx.emit(EditorEvent::Edited { transaction_id });
6698 cx.emit(EditorEvent::TransactionUndone { transaction_id });
6699 }
6700 }
6701
6702 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
6703 if self.read_only(cx) {
6704 return;
6705 }
6706
6707 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
6708 if let Some((_, Some(selections))) =
6709 self.selection_history.transaction(transaction_id).cloned()
6710 {
6711 self.change_selections(None, cx, |s| {
6712 s.select_anchors(selections.to_vec());
6713 });
6714 }
6715 self.request_autoscroll(Autoscroll::fit(), cx);
6716 self.unmark_text(cx);
6717 self.refresh_inline_completion(true, cx);
6718 cx.emit(EditorEvent::Edited { transaction_id });
6719 }
6720 }
6721
6722 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
6723 self.buffer
6724 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
6725 }
6726
6727 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
6728 self.buffer
6729 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
6730 }
6731
6732 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
6733 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6734 let line_mode = s.line_mode;
6735 s.move_with(|map, selection| {
6736 let cursor = if selection.is_empty() && !line_mode {
6737 movement::left(map, selection.start)
6738 } else {
6739 selection.start
6740 };
6741 selection.collapse_to(cursor, SelectionGoal::None);
6742 });
6743 })
6744 }
6745
6746 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
6747 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6748 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
6749 })
6750 }
6751
6752 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
6753 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6754 let line_mode = s.line_mode;
6755 s.move_with(|map, selection| {
6756 let cursor = if selection.is_empty() && !line_mode {
6757 movement::right(map, selection.end)
6758 } else {
6759 selection.end
6760 };
6761 selection.collapse_to(cursor, SelectionGoal::None)
6762 });
6763 })
6764 }
6765
6766 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
6767 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6768 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
6769 })
6770 }
6771
6772 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
6773 if self.take_rename(true, cx).is_some() {
6774 return;
6775 }
6776
6777 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6778 cx.propagate();
6779 return;
6780 }
6781
6782 let text_layout_details = &self.text_layout_details(cx);
6783 let selection_count = self.selections.count();
6784 let first_selection = self.selections.first_anchor();
6785
6786 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6787 let line_mode = s.line_mode;
6788 s.move_with(|map, selection| {
6789 if !selection.is_empty() && !line_mode {
6790 selection.goal = SelectionGoal::None;
6791 }
6792 let (cursor, goal) = movement::up(
6793 map,
6794 selection.start,
6795 selection.goal,
6796 false,
6797 &text_layout_details,
6798 );
6799 selection.collapse_to(cursor, goal);
6800 });
6801 });
6802
6803 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
6804 {
6805 cx.propagate();
6806 }
6807 }
6808
6809 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
6810 if self.take_rename(true, cx).is_some() {
6811 return;
6812 }
6813
6814 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6815 cx.propagate();
6816 return;
6817 }
6818
6819 let text_layout_details = &self.text_layout_details(cx);
6820
6821 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6822 let line_mode = s.line_mode;
6823 s.move_with(|map, selection| {
6824 if !selection.is_empty() && !line_mode {
6825 selection.goal = SelectionGoal::None;
6826 }
6827 let (cursor, goal) = movement::up_by_rows(
6828 map,
6829 selection.start,
6830 action.lines,
6831 selection.goal,
6832 false,
6833 &text_layout_details,
6834 );
6835 selection.collapse_to(cursor, goal);
6836 });
6837 })
6838 }
6839
6840 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
6841 if self.take_rename(true, cx).is_some() {
6842 return;
6843 }
6844
6845 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6846 cx.propagate();
6847 return;
6848 }
6849
6850 let text_layout_details = &self.text_layout_details(cx);
6851
6852 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6853 let line_mode = s.line_mode;
6854 s.move_with(|map, selection| {
6855 if !selection.is_empty() && !line_mode {
6856 selection.goal = SelectionGoal::None;
6857 }
6858 let (cursor, goal) = movement::down_by_rows(
6859 map,
6860 selection.start,
6861 action.lines,
6862 selection.goal,
6863 false,
6864 &text_layout_details,
6865 );
6866 selection.collapse_to(cursor, goal);
6867 });
6868 })
6869 }
6870
6871 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
6872 let text_layout_details = &self.text_layout_details(cx);
6873 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6874 s.move_heads_with(|map, head, goal| {
6875 movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
6876 })
6877 })
6878 }
6879
6880 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
6881 let text_layout_details = &self.text_layout_details(cx);
6882 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6883 s.move_heads_with(|map, head, goal| {
6884 movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
6885 })
6886 })
6887 }
6888
6889 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
6890 let Some(row_count) = self.visible_row_count() else {
6891 return;
6892 };
6893
6894 let text_layout_details = &self.text_layout_details(cx);
6895
6896 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6897 s.move_heads_with(|map, head, goal| {
6898 movement::up_by_rows(map, head, row_count, goal, false, &text_layout_details)
6899 })
6900 })
6901 }
6902
6903 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
6904 if self.take_rename(true, cx).is_some() {
6905 return;
6906 }
6907
6908 if self
6909 .context_menu
6910 .write()
6911 .as_mut()
6912 .map(|menu| menu.select_first(self.project.as_ref(), cx))
6913 .unwrap_or(false)
6914 {
6915 return;
6916 }
6917
6918 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6919 cx.propagate();
6920 return;
6921 }
6922
6923 let Some(row_count) = self.visible_row_count() else {
6924 return;
6925 };
6926
6927 let autoscroll = if action.center_cursor {
6928 Autoscroll::center()
6929 } else {
6930 Autoscroll::fit()
6931 };
6932
6933 let text_layout_details = &self.text_layout_details(cx);
6934
6935 self.change_selections(Some(autoscroll), cx, |s| {
6936 let line_mode = s.line_mode;
6937 s.move_with(|map, selection| {
6938 if !selection.is_empty() && !line_mode {
6939 selection.goal = SelectionGoal::None;
6940 }
6941 let (cursor, goal) = movement::up_by_rows(
6942 map,
6943 selection.end,
6944 row_count,
6945 selection.goal,
6946 false,
6947 &text_layout_details,
6948 );
6949 selection.collapse_to(cursor, goal);
6950 });
6951 });
6952 }
6953
6954 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
6955 let text_layout_details = &self.text_layout_details(cx);
6956 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6957 s.move_heads_with(|map, head, goal| {
6958 movement::up(map, head, goal, false, &text_layout_details)
6959 })
6960 })
6961 }
6962
6963 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
6964 self.take_rename(true, cx);
6965
6966 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6967 cx.propagate();
6968 return;
6969 }
6970
6971 let text_layout_details = &self.text_layout_details(cx);
6972 let selection_count = self.selections.count();
6973 let first_selection = self.selections.first_anchor();
6974
6975 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6976 let line_mode = s.line_mode;
6977 s.move_with(|map, selection| {
6978 if !selection.is_empty() && !line_mode {
6979 selection.goal = SelectionGoal::None;
6980 }
6981 let (cursor, goal) = movement::down(
6982 map,
6983 selection.end,
6984 selection.goal,
6985 false,
6986 &text_layout_details,
6987 );
6988 selection.collapse_to(cursor, goal);
6989 });
6990 });
6991
6992 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
6993 {
6994 cx.propagate();
6995 }
6996 }
6997
6998 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
6999 let Some(row_count) = self.visible_row_count() else {
7000 return;
7001 };
7002
7003 let text_layout_details = &self.text_layout_details(cx);
7004
7005 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7006 s.move_heads_with(|map, head, goal| {
7007 movement::down_by_rows(map, head, row_count, goal, false, &text_layout_details)
7008 })
7009 })
7010 }
7011
7012 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7013 if self.take_rename(true, cx).is_some() {
7014 return;
7015 }
7016
7017 if self
7018 .context_menu
7019 .write()
7020 .as_mut()
7021 .map(|menu| menu.select_last(self.project.as_ref(), cx))
7022 .unwrap_or(false)
7023 {
7024 return;
7025 }
7026
7027 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7028 cx.propagate();
7029 return;
7030 }
7031
7032 let Some(row_count) = self.visible_row_count() else {
7033 return;
7034 };
7035
7036 let autoscroll = if action.center_cursor {
7037 Autoscroll::center()
7038 } else {
7039 Autoscroll::fit()
7040 };
7041
7042 let text_layout_details = &self.text_layout_details(cx);
7043 self.change_selections(Some(autoscroll), cx, |s| {
7044 let line_mode = s.line_mode;
7045 s.move_with(|map, selection| {
7046 if !selection.is_empty() && !line_mode {
7047 selection.goal = SelectionGoal::None;
7048 }
7049 let (cursor, goal) = movement::down_by_rows(
7050 map,
7051 selection.end,
7052 row_count,
7053 selection.goal,
7054 false,
7055 &text_layout_details,
7056 );
7057 selection.collapse_to(cursor, goal);
7058 });
7059 });
7060 }
7061
7062 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7063 let text_layout_details = &self.text_layout_details(cx);
7064 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7065 s.move_heads_with(|map, head, goal| {
7066 movement::down(map, head, goal, false, &text_layout_details)
7067 })
7068 });
7069 }
7070
7071 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7072 if let Some(context_menu) = self.context_menu.write().as_mut() {
7073 context_menu.select_first(self.project.as_ref(), cx);
7074 }
7075 }
7076
7077 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7078 if let Some(context_menu) = self.context_menu.write().as_mut() {
7079 context_menu.select_prev(self.project.as_ref(), cx);
7080 }
7081 }
7082
7083 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7084 if let Some(context_menu) = self.context_menu.write().as_mut() {
7085 context_menu.select_next(self.project.as_ref(), cx);
7086 }
7087 }
7088
7089 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7090 if let Some(context_menu) = self.context_menu.write().as_mut() {
7091 context_menu.select_last(self.project.as_ref(), cx);
7092 }
7093 }
7094
7095 pub fn move_to_previous_word_start(
7096 &mut self,
7097 _: &MoveToPreviousWordStart,
7098 cx: &mut ViewContext<Self>,
7099 ) {
7100 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7101 s.move_cursors_with(|map, head, _| {
7102 (
7103 movement::previous_word_start(map, head),
7104 SelectionGoal::None,
7105 )
7106 });
7107 })
7108 }
7109
7110 pub fn move_to_previous_subword_start(
7111 &mut self,
7112 _: &MoveToPreviousSubwordStart,
7113 cx: &mut ViewContext<Self>,
7114 ) {
7115 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7116 s.move_cursors_with(|map, head, _| {
7117 (
7118 movement::previous_subword_start(map, head),
7119 SelectionGoal::None,
7120 )
7121 });
7122 })
7123 }
7124
7125 pub fn select_to_previous_word_start(
7126 &mut self,
7127 _: &SelectToPreviousWordStart,
7128 cx: &mut ViewContext<Self>,
7129 ) {
7130 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7131 s.move_heads_with(|map, head, _| {
7132 (
7133 movement::previous_word_start(map, head),
7134 SelectionGoal::None,
7135 )
7136 });
7137 })
7138 }
7139
7140 pub fn select_to_previous_subword_start(
7141 &mut self,
7142 _: &SelectToPreviousSubwordStart,
7143 cx: &mut ViewContext<Self>,
7144 ) {
7145 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7146 s.move_heads_with(|map, head, _| {
7147 (
7148 movement::previous_subword_start(map, head),
7149 SelectionGoal::None,
7150 )
7151 });
7152 })
7153 }
7154
7155 pub fn delete_to_previous_word_start(
7156 &mut self,
7157 _: &DeleteToPreviousWordStart,
7158 cx: &mut ViewContext<Self>,
7159 ) {
7160 self.transact(cx, |this, cx| {
7161 this.select_autoclose_pair(cx);
7162 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7163 let line_mode = s.line_mode;
7164 s.move_with(|map, selection| {
7165 if selection.is_empty() && !line_mode {
7166 let cursor = movement::previous_word_start(map, selection.head());
7167 selection.set_head(cursor, SelectionGoal::None);
7168 }
7169 });
7170 });
7171 this.insert("", cx);
7172 });
7173 }
7174
7175 pub fn delete_to_previous_subword_start(
7176 &mut self,
7177 _: &DeleteToPreviousSubwordStart,
7178 cx: &mut ViewContext<Self>,
7179 ) {
7180 self.transact(cx, |this, cx| {
7181 this.select_autoclose_pair(cx);
7182 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7183 let line_mode = s.line_mode;
7184 s.move_with(|map, selection| {
7185 if selection.is_empty() && !line_mode {
7186 let cursor = movement::previous_subword_start(map, selection.head());
7187 selection.set_head(cursor, SelectionGoal::None);
7188 }
7189 });
7190 });
7191 this.insert("", cx);
7192 });
7193 }
7194
7195 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7196 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7197 s.move_cursors_with(|map, head, _| {
7198 (movement::next_word_end(map, head), SelectionGoal::None)
7199 });
7200 })
7201 }
7202
7203 pub fn move_to_next_subword_end(
7204 &mut self,
7205 _: &MoveToNextSubwordEnd,
7206 cx: &mut ViewContext<Self>,
7207 ) {
7208 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7209 s.move_cursors_with(|map, head, _| {
7210 (movement::next_subword_end(map, head), SelectionGoal::None)
7211 });
7212 })
7213 }
7214
7215 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7216 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7217 s.move_heads_with(|map, head, _| {
7218 (movement::next_word_end(map, head), SelectionGoal::None)
7219 });
7220 })
7221 }
7222
7223 pub fn select_to_next_subword_end(
7224 &mut self,
7225 _: &SelectToNextSubwordEnd,
7226 cx: &mut ViewContext<Self>,
7227 ) {
7228 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7229 s.move_heads_with(|map, head, _| {
7230 (movement::next_subword_end(map, head), SelectionGoal::None)
7231 });
7232 })
7233 }
7234
7235 pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
7236 self.transact(cx, |this, cx| {
7237 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7238 let line_mode = s.line_mode;
7239 s.move_with(|map, selection| {
7240 if selection.is_empty() && !line_mode {
7241 let cursor = movement::next_word_end(map, selection.head());
7242 selection.set_head(cursor, SelectionGoal::None);
7243 }
7244 });
7245 });
7246 this.insert("", cx);
7247 });
7248 }
7249
7250 pub fn delete_to_next_subword_end(
7251 &mut self,
7252 _: &DeleteToNextSubwordEnd,
7253 cx: &mut ViewContext<Self>,
7254 ) {
7255 self.transact(cx, |this, cx| {
7256 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7257 s.move_with(|map, selection| {
7258 if selection.is_empty() {
7259 let cursor = movement::next_subword_end(map, selection.head());
7260 selection.set_head(cursor, SelectionGoal::None);
7261 }
7262 });
7263 });
7264 this.insert("", cx);
7265 });
7266 }
7267
7268 pub fn move_to_beginning_of_line(
7269 &mut self,
7270 action: &MoveToBeginningOfLine,
7271 cx: &mut ViewContext<Self>,
7272 ) {
7273 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7274 s.move_cursors_with(|map, head, _| {
7275 (
7276 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7277 SelectionGoal::None,
7278 )
7279 });
7280 })
7281 }
7282
7283 pub fn select_to_beginning_of_line(
7284 &mut self,
7285 action: &SelectToBeginningOfLine,
7286 cx: &mut ViewContext<Self>,
7287 ) {
7288 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7289 s.move_heads_with(|map, head, _| {
7290 (
7291 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7292 SelectionGoal::None,
7293 )
7294 });
7295 });
7296 }
7297
7298 pub fn delete_to_beginning_of_line(
7299 &mut self,
7300 _: &DeleteToBeginningOfLine,
7301 cx: &mut ViewContext<Self>,
7302 ) {
7303 self.transact(cx, |this, cx| {
7304 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7305 s.move_with(|_, selection| {
7306 selection.reversed = true;
7307 });
7308 });
7309
7310 this.select_to_beginning_of_line(
7311 &SelectToBeginningOfLine {
7312 stop_at_soft_wraps: false,
7313 },
7314 cx,
7315 );
7316 this.backspace(&Backspace, cx);
7317 });
7318 }
7319
7320 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7321 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7322 s.move_cursors_with(|map, head, _| {
7323 (
7324 movement::line_end(map, head, action.stop_at_soft_wraps),
7325 SelectionGoal::None,
7326 )
7327 });
7328 })
7329 }
7330
7331 pub fn select_to_end_of_line(
7332 &mut self,
7333 action: &SelectToEndOfLine,
7334 cx: &mut ViewContext<Self>,
7335 ) {
7336 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7337 s.move_heads_with(|map, head, _| {
7338 (
7339 movement::line_end(map, head, action.stop_at_soft_wraps),
7340 SelectionGoal::None,
7341 )
7342 });
7343 })
7344 }
7345
7346 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7347 self.transact(cx, |this, cx| {
7348 this.select_to_end_of_line(
7349 &SelectToEndOfLine {
7350 stop_at_soft_wraps: false,
7351 },
7352 cx,
7353 );
7354 this.delete(&Delete, cx);
7355 });
7356 }
7357
7358 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7359 self.transact(cx, |this, cx| {
7360 this.select_to_end_of_line(
7361 &SelectToEndOfLine {
7362 stop_at_soft_wraps: false,
7363 },
7364 cx,
7365 );
7366 this.cut(&Cut, cx);
7367 });
7368 }
7369
7370 pub fn move_to_start_of_paragraph(
7371 &mut self,
7372 _: &MoveToStartOfParagraph,
7373 cx: &mut ViewContext<Self>,
7374 ) {
7375 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7376 cx.propagate();
7377 return;
7378 }
7379
7380 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7381 s.move_with(|map, selection| {
7382 selection.collapse_to(
7383 movement::start_of_paragraph(map, selection.head(), 1),
7384 SelectionGoal::None,
7385 )
7386 });
7387 })
7388 }
7389
7390 pub fn move_to_end_of_paragraph(
7391 &mut self,
7392 _: &MoveToEndOfParagraph,
7393 cx: &mut ViewContext<Self>,
7394 ) {
7395 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7396 cx.propagate();
7397 return;
7398 }
7399
7400 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7401 s.move_with(|map, selection| {
7402 selection.collapse_to(
7403 movement::end_of_paragraph(map, selection.head(), 1),
7404 SelectionGoal::None,
7405 )
7406 });
7407 })
7408 }
7409
7410 pub fn select_to_start_of_paragraph(
7411 &mut self,
7412 _: &SelectToStartOfParagraph,
7413 cx: &mut ViewContext<Self>,
7414 ) {
7415 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7416 cx.propagate();
7417 return;
7418 }
7419
7420 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7421 s.move_heads_with(|map, head, _| {
7422 (
7423 movement::start_of_paragraph(map, head, 1),
7424 SelectionGoal::None,
7425 )
7426 });
7427 })
7428 }
7429
7430 pub fn select_to_end_of_paragraph(
7431 &mut self,
7432 _: &SelectToEndOfParagraph,
7433 cx: &mut ViewContext<Self>,
7434 ) {
7435 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7436 cx.propagate();
7437 return;
7438 }
7439
7440 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7441 s.move_heads_with(|map, head, _| {
7442 (
7443 movement::end_of_paragraph(map, head, 1),
7444 SelectionGoal::None,
7445 )
7446 });
7447 })
7448 }
7449
7450 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7451 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7452 cx.propagate();
7453 return;
7454 }
7455
7456 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7457 s.select_ranges(vec![0..0]);
7458 });
7459 }
7460
7461 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7462 let mut selection = self.selections.last::<Point>(cx);
7463 selection.set_head(Point::zero(), SelectionGoal::None);
7464
7465 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7466 s.select(vec![selection]);
7467 });
7468 }
7469
7470 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7471 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7472 cx.propagate();
7473 return;
7474 }
7475
7476 let cursor = self.buffer.read(cx).read(cx).len();
7477 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7478 s.select_ranges(vec![cursor..cursor])
7479 });
7480 }
7481
7482 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7483 self.nav_history = nav_history;
7484 }
7485
7486 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7487 self.nav_history.as_ref()
7488 }
7489
7490 fn push_to_nav_history(
7491 &mut self,
7492 cursor_anchor: Anchor,
7493 new_position: Option<Point>,
7494 cx: &mut ViewContext<Self>,
7495 ) {
7496 if let Some(nav_history) = self.nav_history.as_mut() {
7497 let buffer = self.buffer.read(cx).read(cx);
7498 let cursor_position = cursor_anchor.to_point(&buffer);
7499 let scroll_state = self.scroll_manager.anchor();
7500 let scroll_top_row = scroll_state.top_row(&buffer);
7501 drop(buffer);
7502
7503 if let Some(new_position) = new_position {
7504 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7505 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7506 return;
7507 }
7508 }
7509
7510 nav_history.push(
7511 Some(NavigationData {
7512 cursor_anchor,
7513 cursor_position,
7514 scroll_anchor: scroll_state,
7515 scroll_top_row,
7516 }),
7517 cx,
7518 );
7519 }
7520 }
7521
7522 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7523 let buffer = self.buffer.read(cx).snapshot(cx);
7524 let mut selection = self.selections.first::<usize>(cx);
7525 selection.set_head(buffer.len(), SelectionGoal::None);
7526 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7527 s.select(vec![selection]);
7528 });
7529 }
7530
7531 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7532 let end = self.buffer.read(cx).read(cx).len();
7533 self.change_selections(None, cx, |s| {
7534 s.select_ranges(vec![0..end]);
7535 });
7536 }
7537
7538 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7539 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7540 let mut selections = self.selections.all::<Point>(cx);
7541 let max_point = display_map.buffer_snapshot.max_point();
7542 for selection in &mut selections {
7543 let rows = selection.spanned_rows(true, &display_map);
7544 selection.start = Point::new(rows.start.0, 0);
7545 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7546 selection.reversed = false;
7547 }
7548 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7549 s.select(selections);
7550 });
7551 }
7552
7553 pub fn split_selection_into_lines(
7554 &mut self,
7555 _: &SplitSelectionIntoLines,
7556 cx: &mut ViewContext<Self>,
7557 ) {
7558 let mut to_unfold = Vec::new();
7559 let mut new_selection_ranges = Vec::new();
7560 {
7561 let selections = self.selections.all::<Point>(cx);
7562 let buffer = self.buffer.read(cx).read(cx);
7563 for selection in selections {
7564 for row in selection.start.row..selection.end.row {
7565 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7566 new_selection_ranges.push(cursor..cursor);
7567 }
7568 new_selection_ranges.push(selection.end..selection.end);
7569 to_unfold.push(selection.start..selection.end);
7570 }
7571 }
7572 self.unfold_ranges(to_unfold, true, true, cx);
7573 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7574 s.select_ranges(new_selection_ranges);
7575 });
7576 }
7577
7578 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7579 self.add_selection(true, cx);
7580 }
7581
7582 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7583 self.add_selection(false, cx);
7584 }
7585
7586 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7587 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7588 let mut selections = self.selections.all::<Point>(cx);
7589 let text_layout_details = self.text_layout_details(cx);
7590 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7591 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7592 let range = oldest_selection.display_range(&display_map).sorted();
7593
7594 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7595 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7596 let positions = start_x.min(end_x)..start_x.max(end_x);
7597
7598 selections.clear();
7599 let mut stack = Vec::new();
7600 for row in range.start.row().0..=range.end.row().0 {
7601 if let Some(selection) = self.selections.build_columnar_selection(
7602 &display_map,
7603 DisplayRow(row),
7604 &positions,
7605 oldest_selection.reversed,
7606 &text_layout_details,
7607 ) {
7608 stack.push(selection.id);
7609 selections.push(selection);
7610 }
7611 }
7612
7613 if above {
7614 stack.reverse();
7615 }
7616
7617 AddSelectionsState { above, stack }
7618 });
7619
7620 let last_added_selection = *state.stack.last().unwrap();
7621 let mut new_selections = Vec::new();
7622 if above == state.above {
7623 let end_row = if above {
7624 DisplayRow(0)
7625 } else {
7626 display_map.max_point().row()
7627 };
7628
7629 'outer: for selection in selections {
7630 if selection.id == last_added_selection {
7631 let range = selection.display_range(&display_map).sorted();
7632 debug_assert_eq!(range.start.row(), range.end.row());
7633 let mut row = range.start.row();
7634 let positions =
7635 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7636 px(start)..px(end)
7637 } else {
7638 let start_x =
7639 display_map.x_for_display_point(range.start, &text_layout_details);
7640 let end_x =
7641 display_map.x_for_display_point(range.end, &text_layout_details);
7642 start_x.min(end_x)..start_x.max(end_x)
7643 };
7644
7645 while row != end_row {
7646 if above {
7647 row.0 -= 1;
7648 } else {
7649 row.0 += 1;
7650 }
7651
7652 if let Some(new_selection) = self.selections.build_columnar_selection(
7653 &display_map,
7654 row,
7655 &positions,
7656 selection.reversed,
7657 &text_layout_details,
7658 ) {
7659 state.stack.push(new_selection.id);
7660 if above {
7661 new_selections.push(new_selection);
7662 new_selections.push(selection);
7663 } else {
7664 new_selections.push(selection);
7665 new_selections.push(new_selection);
7666 }
7667
7668 continue 'outer;
7669 }
7670 }
7671 }
7672
7673 new_selections.push(selection);
7674 }
7675 } else {
7676 new_selections = selections;
7677 new_selections.retain(|s| s.id != last_added_selection);
7678 state.stack.pop();
7679 }
7680
7681 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7682 s.select(new_selections);
7683 });
7684 if state.stack.len() > 1 {
7685 self.add_selections_state = Some(state);
7686 }
7687 }
7688
7689 pub fn select_next_match_internal(
7690 &mut self,
7691 display_map: &DisplaySnapshot,
7692 replace_newest: bool,
7693 autoscroll: Option<Autoscroll>,
7694 cx: &mut ViewContext<Self>,
7695 ) -> Result<()> {
7696 fn select_next_match_ranges(
7697 this: &mut Editor,
7698 range: Range<usize>,
7699 replace_newest: bool,
7700 auto_scroll: Option<Autoscroll>,
7701 cx: &mut ViewContext<Editor>,
7702 ) {
7703 this.unfold_ranges([range.clone()], false, true, cx);
7704 this.change_selections(auto_scroll, cx, |s| {
7705 if replace_newest {
7706 s.delete(s.newest_anchor().id);
7707 }
7708 s.insert_range(range.clone());
7709 });
7710 }
7711
7712 let buffer = &display_map.buffer_snapshot;
7713 let mut selections = self.selections.all::<usize>(cx);
7714 if let Some(mut select_next_state) = self.select_next_state.take() {
7715 let query = &select_next_state.query;
7716 if !select_next_state.done {
7717 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7718 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7719 let mut next_selected_range = None;
7720
7721 let bytes_after_last_selection =
7722 buffer.bytes_in_range(last_selection.end..buffer.len());
7723 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
7724 let query_matches = query
7725 .stream_find_iter(bytes_after_last_selection)
7726 .map(|result| (last_selection.end, result))
7727 .chain(
7728 query
7729 .stream_find_iter(bytes_before_first_selection)
7730 .map(|result| (0, result)),
7731 );
7732
7733 for (start_offset, query_match) in query_matches {
7734 let query_match = query_match.unwrap(); // can only fail due to I/O
7735 let offset_range =
7736 start_offset + query_match.start()..start_offset + query_match.end();
7737 let display_range = offset_range.start.to_display_point(&display_map)
7738 ..offset_range.end.to_display_point(&display_map);
7739
7740 if !select_next_state.wordwise
7741 || (!movement::is_inside_word(&display_map, display_range.start)
7742 && !movement::is_inside_word(&display_map, display_range.end))
7743 {
7744 // TODO: This is n^2, because we might check all the selections
7745 if !selections
7746 .iter()
7747 .any(|selection| selection.range().overlaps(&offset_range))
7748 {
7749 next_selected_range = Some(offset_range);
7750 break;
7751 }
7752 }
7753 }
7754
7755 if let Some(next_selected_range) = next_selected_range {
7756 select_next_match_ranges(
7757 self,
7758 next_selected_range,
7759 replace_newest,
7760 autoscroll,
7761 cx,
7762 );
7763 } else {
7764 select_next_state.done = true;
7765 }
7766 }
7767
7768 self.select_next_state = Some(select_next_state);
7769 } else {
7770 let mut only_carets = true;
7771 let mut same_text_selected = true;
7772 let mut selected_text = None;
7773
7774 let mut selections_iter = selections.iter().peekable();
7775 while let Some(selection) = selections_iter.next() {
7776 if selection.start != selection.end {
7777 only_carets = false;
7778 }
7779
7780 if same_text_selected {
7781 if selected_text.is_none() {
7782 selected_text =
7783 Some(buffer.text_for_range(selection.range()).collect::<String>());
7784 }
7785
7786 if let Some(next_selection) = selections_iter.peek() {
7787 if next_selection.range().len() == selection.range().len() {
7788 let next_selected_text = buffer
7789 .text_for_range(next_selection.range())
7790 .collect::<String>();
7791 if Some(next_selected_text) != selected_text {
7792 same_text_selected = false;
7793 selected_text = None;
7794 }
7795 } else {
7796 same_text_selected = false;
7797 selected_text = None;
7798 }
7799 }
7800 }
7801 }
7802
7803 if only_carets {
7804 for selection in &mut selections {
7805 let word_range = movement::surrounding_word(
7806 &display_map,
7807 selection.start.to_display_point(&display_map),
7808 );
7809 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
7810 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
7811 selection.goal = SelectionGoal::None;
7812 selection.reversed = false;
7813 select_next_match_ranges(
7814 self,
7815 selection.start..selection.end,
7816 replace_newest,
7817 autoscroll,
7818 cx,
7819 );
7820 }
7821
7822 if selections.len() == 1 {
7823 let selection = selections
7824 .last()
7825 .expect("ensured that there's only one selection");
7826 let query = buffer
7827 .text_for_range(selection.start..selection.end)
7828 .collect::<String>();
7829 let is_empty = query.is_empty();
7830 let select_state = SelectNextState {
7831 query: AhoCorasick::new(&[query])?,
7832 wordwise: true,
7833 done: is_empty,
7834 };
7835 self.select_next_state = Some(select_state);
7836 } else {
7837 self.select_next_state = None;
7838 }
7839 } else if let Some(selected_text) = selected_text {
7840 self.select_next_state = Some(SelectNextState {
7841 query: AhoCorasick::new(&[selected_text])?,
7842 wordwise: false,
7843 done: false,
7844 });
7845 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
7846 }
7847 }
7848 Ok(())
7849 }
7850
7851 pub fn select_all_matches(
7852 &mut self,
7853 _action: &SelectAllMatches,
7854 cx: &mut ViewContext<Self>,
7855 ) -> Result<()> {
7856 self.push_to_selection_history();
7857 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7858
7859 self.select_next_match_internal(&display_map, false, None, cx)?;
7860 let Some(select_next_state) = self.select_next_state.as_mut() else {
7861 return Ok(());
7862 };
7863 if select_next_state.done {
7864 return Ok(());
7865 }
7866
7867 let mut new_selections = self.selections.all::<usize>(cx);
7868
7869 let buffer = &display_map.buffer_snapshot;
7870 let query_matches = select_next_state
7871 .query
7872 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
7873
7874 for query_match in query_matches {
7875 let query_match = query_match.unwrap(); // can only fail due to I/O
7876 let offset_range = query_match.start()..query_match.end();
7877 let display_range = offset_range.start.to_display_point(&display_map)
7878 ..offset_range.end.to_display_point(&display_map);
7879
7880 if !select_next_state.wordwise
7881 || (!movement::is_inside_word(&display_map, display_range.start)
7882 && !movement::is_inside_word(&display_map, display_range.end))
7883 {
7884 self.selections.change_with(cx, |selections| {
7885 new_selections.push(Selection {
7886 id: selections.new_selection_id(),
7887 start: offset_range.start,
7888 end: offset_range.end,
7889 reversed: false,
7890 goal: SelectionGoal::None,
7891 });
7892 });
7893 }
7894 }
7895
7896 new_selections.sort_by_key(|selection| selection.start);
7897 let mut ix = 0;
7898 while ix + 1 < new_selections.len() {
7899 let current_selection = &new_selections[ix];
7900 let next_selection = &new_selections[ix + 1];
7901 if current_selection.range().overlaps(&next_selection.range()) {
7902 if current_selection.id < next_selection.id {
7903 new_selections.remove(ix + 1);
7904 } else {
7905 new_selections.remove(ix);
7906 }
7907 } else {
7908 ix += 1;
7909 }
7910 }
7911
7912 select_next_state.done = true;
7913 self.unfold_ranges(
7914 new_selections.iter().map(|selection| selection.range()),
7915 false,
7916 false,
7917 cx,
7918 );
7919 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
7920 selections.select(new_selections)
7921 });
7922
7923 Ok(())
7924 }
7925
7926 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
7927 self.push_to_selection_history();
7928 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7929 self.select_next_match_internal(
7930 &display_map,
7931 action.replace_newest,
7932 Some(Autoscroll::newest()),
7933 cx,
7934 )?;
7935 Ok(())
7936 }
7937
7938 pub fn select_previous(
7939 &mut self,
7940 action: &SelectPrevious,
7941 cx: &mut ViewContext<Self>,
7942 ) -> Result<()> {
7943 self.push_to_selection_history();
7944 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7945 let buffer = &display_map.buffer_snapshot;
7946 let mut selections = self.selections.all::<usize>(cx);
7947 if let Some(mut select_prev_state) = self.select_prev_state.take() {
7948 let query = &select_prev_state.query;
7949 if !select_prev_state.done {
7950 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7951 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7952 let mut next_selected_range = None;
7953 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
7954 let bytes_before_last_selection =
7955 buffer.reversed_bytes_in_range(0..last_selection.start);
7956 let bytes_after_first_selection =
7957 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
7958 let query_matches = query
7959 .stream_find_iter(bytes_before_last_selection)
7960 .map(|result| (last_selection.start, result))
7961 .chain(
7962 query
7963 .stream_find_iter(bytes_after_first_selection)
7964 .map(|result| (buffer.len(), result)),
7965 );
7966 for (end_offset, query_match) in query_matches {
7967 let query_match = query_match.unwrap(); // can only fail due to I/O
7968 let offset_range =
7969 end_offset - query_match.end()..end_offset - query_match.start();
7970 let display_range = offset_range.start.to_display_point(&display_map)
7971 ..offset_range.end.to_display_point(&display_map);
7972
7973 if !select_prev_state.wordwise
7974 || (!movement::is_inside_word(&display_map, display_range.start)
7975 && !movement::is_inside_word(&display_map, display_range.end))
7976 {
7977 next_selected_range = Some(offset_range);
7978 break;
7979 }
7980 }
7981
7982 if let Some(next_selected_range) = next_selected_range {
7983 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
7984 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
7985 if action.replace_newest {
7986 s.delete(s.newest_anchor().id);
7987 }
7988 s.insert_range(next_selected_range);
7989 });
7990 } else {
7991 select_prev_state.done = true;
7992 }
7993 }
7994
7995 self.select_prev_state = Some(select_prev_state);
7996 } else {
7997 let mut only_carets = true;
7998 let mut same_text_selected = true;
7999 let mut selected_text = None;
8000
8001 let mut selections_iter = selections.iter().peekable();
8002 while let Some(selection) = selections_iter.next() {
8003 if selection.start != selection.end {
8004 only_carets = false;
8005 }
8006
8007 if same_text_selected {
8008 if selected_text.is_none() {
8009 selected_text =
8010 Some(buffer.text_for_range(selection.range()).collect::<String>());
8011 }
8012
8013 if let Some(next_selection) = selections_iter.peek() {
8014 if next_selection.range().len() == selection.range().len() {
8015 let next_selected_text = buffer
8016 .text_for_range(next_selection.range())
8017 .collect::<String>();
8018 if Some(next_selected_text) != selected_text {
8019 same_text_selected = false;
8020 selected_text = None;
8021 }
8022 } else {
8023 same_text_selected = false;
8024 selected_text = None;
8025 }
8026 }
8027 }
8028 }
8029
8030 if only_carets {
8031 for selection in &mut selections {
8032 let word_range = movement::surrounding_word(
8033 &display_map,
8034 selection.start.to_display_point(&display_map),
8035 );
8036 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8037 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8038 selection.goal = SelectionGoal::None;
8039 selection.reversed = false;
8040 }
8041 if selections.len() == 1 {
8042 let selection = selections
8043 .last()
8044 .expect("ensured that there's only one selection");
8045 let query = buffer
8046 .text_for_range(selection.start..selection.end)
8047 .collect::<String>();
8048 let is_empty = query.is_empty();
8049 let select_state = SelectNextState {
8050 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8051 wordwise: true,
8052 done: is_empty,
8053 };
8054 self.select_prev_state = Some(select_state);
8055 } else {
8056 self.select_prev_state = None;
8057 }
8058
8059 self.unfold_ranges(
8060 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8061 false,
8062 true,
8063 cx,
8064 );
8065 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8066 s.select(selections);
8067 });
8068 } else if let Some(selected_text) = selected_text {
8069 self.select_prev_state = Some(SelectNextState {
8070 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8071 wordwise: false,
8072 done: false,
8073 });
8074 self.select_previous(action, cx)?;
8075 }
8076 }
8077 Ok(())
8078 }
8079
8080 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8081 let text_layout_details = &self.text_layout_details(cx);
8082 self.transact(cx, |this, cx| {
8083 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8084 let mut edits = Vec::new();
8085 let mut selection_edit_ranges = Vec::new();
8086 let mut last_toggled_row = None;
8087 let snapshot = this.buffer.read(cx).read(cx);
8088 let empty_str: Arc<str> = Arc::default();
8089 let mut suffixes_inserted = Vec::new();
8090
8091 fn comment_prefix_range(
8092 snapshot: &MultiBufferSnapshot,
8093 row: MultiBufferRow,
8094 comment_prefix: &str,
8095 comment_prefix_whitespace: &str,
8096 ) -> Range<Point> {
8097 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8098
8099 let mut line_bytes = snapshot
8100 .bytes_in_range(start..snapshot.max_point())
8101 .flatten()
8102 .copied();
8103
8104 // If this line currently begins with the line comment prefix, then record
8105 // the range containing the prefix.
8106 if line_bytes
8107 .by_ref()
8108 .take(comment_prefix.len())
8109 .eq(comment_prefix.bytes())
8110 {
8111 // Include any whitespace that matches the comment prefix.
8112 let matching_whitespace_len = line_bytes
8113 .zip(comment_prefix_whitespace.bytes())
8114 .take_while(|(a, b)| a == b)
8115 .count() as u32;
8116 let end = Point::new(
8117 start.row,
8118 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8119 );
8120 start..end
8121 } else {
8122 start..start
8123 }
8124 }
8125
8126 fn comment_suffix_range(
8127 snapshot: &MultiBufferSnapshot,
8128 row: MultiBufferRow,
8129 comment_suffix: &str,
8130 comment_suffix_has_leading_space: bool,
8131 ) -> Range<Point> {
8132 let end = Point::new(row.0, snapshot.line_len(row));
8133 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8134
8135 let mut line_end_bytes = snapshot
8136 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8137 .flatten()
8138 .copied();
8139
8140 let leading_space_len = if suffix_start_column > 0
8141 && line_end_bytes.next() == Some(b' ')
8142 && comment_suffix_has_leading_space
8143 {
8144 1
8145 } else {
8146 0
8147 };
8148
8149 // If this line currently begins with the line comment prefix, then record
8150 // the range containing the prefix.
8151 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8152 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8153 start..end
8154 } else {
8155 end..end
8156 }
8157 }
8158
8159 // TODO: Handle selections that cross excerpts
8160 for selection in &mut selections {
8161 let start_column = snapshot
8162 .indent_size_for_line(MultiBufferRow(selection.start.row))
8163 .len;
8164 let language = if let Some(language) =
8165 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8166 {
8167 language
8168 } else {
8169 continue;
8170 };
8171
8172 selection_edit_ranges.clear();
8173
8174 // If multiple selections contain a given row, avoid processing that
8175 // row more than once.
8176 let mut start_row = MultiBufferRow(selection.start.row);
8177 if last_toggled_row == Some(start_row) {
8178 start_row = start_row.next_row();
8179 }
8180 let end_row =
8181 if selection.end.row > selection.start.row && selection.end.column == 0 {
8182 MultiBufferRow(selection.end.row - 1)
8183 } else {
8184 MultiBufferRow(selection.end.row)
8185 };
8186 last_toggled_row = Some(end_row);
8187
8188 if start_row > end_row {
8189 continue;
8190 }
8191
8192 // If the language has line comments, toggle those.
8193 let full_comment_prefixes = language.line_comment_prefixes();
8194 if !full_comment_prefixes.is_empty() {
8195 let first_prefix = full_comment_prefixes
8196 .first()
8197 .expect("prefixes is non-empty");
8198 let prefix_trimmed_lengths = full_comment_prefixes
8199 .iter()
8200 .map(|p| p.trim_end_matches(' ').len())
8201 .collect::<SmallVec<[usize; 4]>>();
8202
8203 let mut all_selection_lines_are_comments = true;
8204
8205 for row in start_row.0..=end_row.0 {
8206 let row = MultiBufferRow(row);
8207 if start_row < end_row && snapshot.is_line_blank(row) {
8208 continue;
8209 }
8210
8211 let prefix_range = full_comment_prefixes
8212 .iter()
8213 .zip(prefix_trimmed_lengths.iter().copied())
8214 .map(|(prefix, trimmed_prefix_len)| {
8215 comment_prefix_range(
8216 snapshot.deref(),
8217 row,
8218 &prefix[..trimmed_prefix_len],
8219 &prefix[trimmed_prefix_len..],
8220 )
8221 })
8222 .max_by_key(|range| range.end.column - range.start.column)
8223 .expect("prefixes is non-empty");
8224
8225 if prefix_range.is_empty() {
8226 all_selection_lines_are_comments = false;
8227 }
8228
8229 selection_edit_ranges.push(prefix_range);
8230 }
8231
8232 if all_selection_lines_are_comments {
8233 edits.extend(
8234 selection_edit_ranges
8235 .iter()
8236 .cloned()
8237 .map(|range| (range, empty_str.clone())),
8238 );
8239 } else {
8240 let min_column = selection_edit_ranges
8241 .iter()
8242 .map(|range| range.start.column)
8243 .min()
8244 .unwrap_or(0);
8245 edits.extend(selection_edit_ranges.iter().map(|range| {
8246 let position = Point::new(range.start.row, min_column);
8247 (position..position, first_prefix.clone())
8248 }));
8249 }
8250 } else if let Some((full_comment_prefix, comment_suffix)) =
8251 language.block_comment_delimiters()
8252 {
8253 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8254 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8255 let prefix_range = comment_prefix_range(
8256 snapshot.deref(),
8257 start_row,
8258 comment_prefix,
8259 comment_prefix_whitespace,
8260 );
8261 let suffix_range = comment_suffix_range(
8262 snapshot.deref(),
8263 end_row,
8264 comment_suffix.trim_start_matches(' '),
8265 comment_suffix.starts_with(' '),
8266 );
8267
8268 if prefix_range.is_empty() || suffix_range.is_empty() {
8269 edits.push((
8270 prefix_range.start..prefix_range.start,
8271 full_comment_prefix.clone(),
8272 ));
8273 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8274 suffixes_inserted.push((end_row, comment_suffix.len()));
8275 } else {
8276 edits.push((prefix_range, empty_str.clone()));
8277 edits.push((suffix_range, empty_str.clone()));
8278 }
8279 } else {
8280 continue;
8281 }
8282 }
8283
8284 drop(snapshot);
8285 this.buffer.update(cx, |buffer, cx| {
8286 buffer.edit(edits, None, cx);
8287 });
8288
8289 // Adjust selections so that they end before any comment suffixes that
8290 // were inserted.
8291 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8292 let mut selections = this.selections.all::<Point>(cx);
8293 let snapshot = this.buffer.read(cx).read(cx);
8294 for selection in &mut selections {
8295 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8296 match row.cmp(&MultiBufferRow(selection.end.row)) {
8297 Ordering::Less => {
8298 suffixes_inserted.next();
8299 continue;
8300 }
8301 Ordering::Greater => break,
8302 Ordering::Equal => {
8303 if selection.end.column == snapshot.line_len(row) {
8304 if selection.is_empty() {
8305 selection.start.column -= suffix_len as u32;
8306 }
8307 selection.end.column -= suffix_len as u32;
8308 }
8309 break;
8310 }
8311 }
8312 }
8313 }
8314
8315 drop(snapshot);
8316 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8317
8318 let selections = this.selections.all::<Point>(cx);
8319 let selections_on_single_row = selections.windows(2).all(|selections| {
8320 selections[0].start.row == selections[1].start.row
8321 && selections[0].end.row == selections[1].end.row
8322 && selections[0].start.row == selections[0].end.row
8323 });
8324 let selections_selecting = selections
8325 .iter()
8326 .any(|selection| selection.start != selection.end);
8327 let advance_downwards = action.advance_downwards
8328 && selections_on_single_row
8329 && !selections_selecting
8330 && !matches!(this.mode, EditorMode::SingleLine { .. });
8331
8332 if advance_downwards {
8333 let snapshot = this.buffer.read(cx).snapshot(cx);
8334
8335 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8336 s.move_cursors_with(|display_snapshot, display_point, _| {
8337 let mut point = display_point.to_point(display_snapshot);
8338 point.row += 1;
8339 point = snapshot.clip_point(point, Bias::Left);
8340 let display_point = point.to_display_point(display_snapshot);
8341 let goal = SelectionGoal::HorizontalPosition(
8342 display_snapshot
8343 .x_for_display_point(display_point, &text_layout_details)
8344 .into(),
8345 );
8346 (display_point, goal)
8347 })
8348 });
8349 }
8350 });
8351 }
8352
8353 pub fn select_enclosing_symbol(
8354 &mut self,
8355 _: &SelectEnclosingSymbol,
8356 cx: &mut ViewContext<Self>,
8357 ) {
8358 let buffer = self.buffer.read(cx).snapshot(cx);
8359 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8360
8361 fn update_selection(
8362 selection: &Selection<usize>,
8363 buffer_snap: &MultiBufferSnapshot,
8364 ) -> Option<Selection<usize>> {
8365 let cursor = selection.head();
8366 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8367 for symbol in symbols.iter().rev() {
8368 let start = symbol.range.start.to_offset(&buffer_snap);
8369 let end = symbol.range.end.to_offset(&buffer_snap);
8370 let new_range = start..end;
8371 if start < selection.start || end > selection.end {
8372 return Some(Selection {
8373 id: selection.id,
8374 start: new_range.start,
8375 end: new_range.end,
8376 goal: SelectionGoal::None,
8377 reversed: selection.reversed,
8378 });
8379 }
8380 }
8381 None
8382 }
8383
8384 let mut selected_larger_symbol = false;
8385 let new_selections = old_selections
8386 .iter()
8387 .map(|selection| match update_selection(selection, &buffer) {
8388 Some(new_selection) => {
8389 if new_selection.range() != selection.range() {
8390 selected_larger_symbol = true;
8391 }
8392 new_selection
8393 }
8394 None => selection.clone(),
8395 })
8396 .collect::<Vec<_>>();
8397
8398 if selected_larger_symbol {
8399 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8400 s.select(new_selections);
8401 });
8402 }
8403 }
8404
8405 pub fn select_larger_syntax_node(
8406 &mut self,
8407 _: &SelectLargerSyntaxNode,
8408 cx: &mut ViewContext<Self>,
8409 ) {
8410 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8411 let buffer = self.buffer.read(cx).snapshot(cx);
8412 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8413
8414 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8415 let mut selected_larger_node = false;
8416 let new_selections = old_selections
8417 .iter()
8418 .map(|selection| {
8419 let old_range = selection.start..selection.end;
8420 let mut new_range = old_range.clone();
8421 while let Some(containing_range) =
8422 buffer.range_for_syntax_ancestor(new_range.clone())
8423 {
8424 new_range = containing_range;
8425 if !display_map.intersects_fold(new_range.start)
8426 && !display_map.intersects_fold(new_range.end)
8427 {
8428 break;
8429 }
8430 }
8431
8432 selected_larger_node |= new_range != old_range;
8433 Selection {
8434 id: selection.id,
8435 start: new_range.start,
8436 end: new_range.end,
8437 goal: SelectionGoal::None,
8438 reversed: selection.reversed,
8439 }
8440 })
8441 .collect::<Vec<_>>();
8442
8443 if selected_larger_node {
8444 stack.push(old_selections);
8445 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8446 s.select(new_selections);
8447 });
8448 }
8449 self.select_larger_syntax_node_stack = stack;
8450 }
8451
8452 pub fn select_smaller_syntax_node(
8453 &mut self,
8454 _: &SelectSmallerSyntaxNode,
8455 cx: &mut ViewContext<Self>,
8456 ) {
8457 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8458 if let Some(selections) = stack.pop() {
8459 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8460 s.select(selections.to_vec());
8461 });
8462 }
8463 self.select_larger_syntax_node_stack = stack;
8464 }
8465
8466 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8467 if !EditorSettings::get_global(cx).gutter.runnables {
8468 self.clear_tasks();
8469 return Task::ready(());
8470 }
8471 let project = self.project.clone();
8472 cx.spawn(|this, mut cx| async move {
8473 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8474 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8475 }) else {
8476 return;
8477 };
8478
8479 let Some(project) = project else {
8480 return;
8481 };
8482
8483 let hide_runnables = project
8484 .update(&mut cx, |project, cx| {
8485 // Do not display any test indicators in non-dev server remote projects.
8486 project.is_remote() && project.ssh_connection_string(cx).is_none()
8487 })
8488 .unwrap_or(true);
8489 if hide_runnables {
8490 return;
8491 }
8492 let new_rows =
8493 cx.background_executor()
8494 .spawn({
8495 let snapshot = display_snapshot.clone();
8496 async move {
8497 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8498 }
8499 })
8500 .await;
8501 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8502
8503 this.update(&mut cx, |this, _| {
8504 this.clear_tasks();
8505 for (key, value) in rows {
8506 this.insert_tasks(key, value);
8507 }
8508 })
8509 .ok();
8510 })
8511 }
8512 fn fetch_runnable_ranges(
8513 snapshot: &DisplaySnapshot,
8514 range: Range<Anchor>,
8515 ) -> Vec<language::RunnableRange> {
8516 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8517 }
8518
8519 fn runnable_rows(
8520 project: Model<Project>,
8521 snapshot: DisplaySnapshot,
8522 runnable_ranges: Vec<RunnableRange>,
8523 mut cx: AsyncWindowContext,
8524 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8525 runnable_ranges
8526 .into_iter()
8527 .filter_map(|mut runnable| {
8528 let tasks = cx
8529 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8530 .ok()?;
8531 if tasks.is_empty() {
8532 return None;
8533 }
8534
8535 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8536
8537 let row = snapshot
8538 .buffer_snapshot
8539 .buffer_line_for_row(MultiBufferRow(point.row))?
8540 .1
8541 .start
8542 .row;
8543
8544 let context_range =
8545 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8546 Some((
8547 (runnable.buffer_id, row),
8548 RunnableTasks {
8549 templates: tasks,
8550 offset: MultiBufferOffset(runnable.run_range.start),
8551 context_range,
8552 column: point.column,
8553 extra_variables: runnable.extra_captures,
8554 },
8555 ))
8556 })
8557 .collect()
8558 }
8559
8560 fn templates_with_tags(
8561 project: &Model<Project>,
8562 runnable: &mut Runnable,
8563 cx: &WindowContext<'_>,
8564 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8565 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8566 let (worktree_id, file) = project
8567 .buffer_for_id(runnable.buffer, cx)
8568 .and_then(|buffer| buffer.read(cx).file())
8569 .map(|file| (WorktreeId::from_usize(file.worktree_id()), file.clone()))
8570 .unzip();
8571
8572 (project.task_inventory().clone(), worktree_id, file)
8573 });
8574
8575 let inventory = inventory.read(cx);
8576 let tags = mem::take(&mut runnable.tags);
8577 let mut tags: Vec<_> = tags
8578 .into_iter()
8579 .flat_map(|tag| {
8580 let tag = tag.0.clone();
8581 inventory
8582 .list_tasks(
8583 file.clone(),
8584 Some(runnable.language.clone()),
8585 worktree_id,
8586 cx,
8587 )
8588 .into_iter()
8589 .filter(move |(_, template)| {
8590 template.tags.iter().any(|source_tag| source_tag == &tag)
8591 })
8592 })
8593 .sorted_by_key(|(kind, _)| kind.to_owned())
8594 .collect();
8595 if let Some((leading_tag_source, _)) = tags.first() {
8596 // Strongest source wins; if we have worktree tag binding, prefer that to
8597 // global and language bindings;
8598 // if we have a global binding, prefer that to language binding.
8599 let first_mismatch = tags
8600 .iter()
8601 .position(|(tag_source, _)| tag_source != leading_tag_source);
8602 if let Some(index) = first_mismatch {
8603 tags.truncate(index);
8604 }
8605 }
8606
8607 tags
8608 }
8609
8610 pub fn move_to_enclosing_bracket(
8611 &mut self,
8612 _: &MoveToEnclosingBracket,
8613 cx: &mut ViewContext<Self>,
8614 ) {
8615 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8616 s.move_offsets_with(|snapshot, selection| {
8617 let Some(enclosing_bracket_ranges) =
8618 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
8619 else {
8620 return;
8621 };
8622
8623 let mut best_length = usize::MAX;
8624 let mut best_inside = false;
8625 let mut best_in_bracket_range = false;
8626 let mut best_destination = None;
8627 for (open, close) in enclosing_bracket_ranges {
8628 let close = close.to_inclusive();
8629 let length = close.end() - open.start;
8630 let inside = selection.start >= open.end && selection.end <= *close.start();
8631 let in_bracket_range = open.to_inclusive().contains(&selection.head())
8632 || close.contains(&selection.head());
8633
8634 // If best is next to a bracket and current isn't, skip
8635 if !in_bracket_range && best_in_bracket_range {
8636 continue;
8637 }
8638
8639 // Prefer smaller lengths unless best is inside and current isn't
8640 if length > best_length && (best_inside || !inside) {
8641 continue;
8642 }
8643
8644 best_length = length;
8645 best_inside = inside;
8646 best_in_bracket_range = in_bracket_range;
8647 best_destination = Some(
8648 if close.contains(&selection.start) && close.contains(&selection.end) {
8649 if inside {
8650 open.end
8651 } else {
8652 open.start
8653 }
8654 } else {
8655 if inside {
8656 *close.start()
8657 } else {
8658 *close.end()
8659 }
8660 },
8661 );
8662 }
8663
8664 if let Some(destination) = best_destination {
8665 selection.collapse_to(destination, SelectionGoal::None);
8666 }
8667 })
8668 });
8669 }
8670
8671 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
8672 self.end_selection(cx);
8673 self.selection_history.mode = SelectionHistoryMode::Undoing;
8674 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
8675 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8676 self.select_next_state = entry.select_next_state;
8677 self.select_prev_state = entry.select_prev_state;
8678 self.add_selections_state = entry.add_selections_state;
8679 self.request_autoscroll(Autoscroll::newest(), cx);
8680 }
8681 self.selection_history.mode = SelectionHistoryMode::Normal;
8682 }
8683
8684 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
8685 self.end_selection(cx);
8686 self.selection_history.mode = SelectionHistoryMode::Redoing;
8687 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
8688 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8689 self.select_next_state = entry.select_next_state;
8690 self.select_prev_state = entry.select_prev_state;
8691 self.add_selections_state = entry.add_selections_state;
8692 self.request_autoscroll(Autoscroll::newest(), cx);
8693 }
8694 self.selection_history.mode = SelectionHistoryMode::Normal;
8695 }
8696
8697 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
8698 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
8699 }
8700
8701 pub fn expand_excerpts_down(
8702 &mut self,
8703 action: &ExpandExcerptsDown,
8704 cx: &mut ViewContext<Self>,
8705 ) {
8706 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
8707 }
8708
8709 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
8710 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
8711 }
8712
8713 pub fn expand_excerpts_for_direction(
8714 &mut self,
8715 lines: u32,
8716 direction: ExpandExcerptDirection,
8717 cx: &mut ViewContext<Self>,
8718 ) {
8719 let selections = self.selections.disjoint_anchors();
8720
8721 let lines = if lines == 0 {
8722 EditorSettings::get_global(cx).expand_excerpt_lines
8723 } else {
8724 lines
8725 };
8726
8727 self.buffer.update(cx, |buffer, cx| {
8728 buffer.expand_excerpts(
8729 selections
8730 .into_iter()
8731 .map(|selection| selection.head().excerpt_id)
8732 .dedup(),
8733 lines,
8734 direction,
8735 cx,
8736 )
8737 })
8738 }
8739
8740 pub fn expand_excerpt(
8741 &mut self,
8742 excerpt: ExcerptId,
8743 direction: ExpandExcerptDirection,
8744 cx: &mut ViewContext<Self>,
8745 ) {
8746 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
8747 self.buffer.update(cx, |buffer, cx| {
8748 buffer.expand_excerpts([excerpt], lines, direction, cx)
8749 })
8750 }
8751
8752 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
8753 self.go_to_diagnostic_impl(Direction::Next, cx)
8754 }
8755
8756 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
8757 self.go_to_diagnostic_impl(Direction::Prev, cx)
8758 }
8759
8760 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
8761 let buffer = self.buffer.read(cx).snapshot(cx);
8762 let selection = self.selections.newest::<usize>(cx);
8763
8764 // If there is an active Diagnostic Popover jump to its diagnostic instead.
8765 if direction == Direction::Next {
8766 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
8767 let (group_id, jump_to) = popover.activation_info();
8768 if self.activate_diagnostics(group_id, cx) {
8769 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8770 let mut new_selection = s.newest_anchor().clone();
8771 new_selection.collapse_to(jump_to, SelectionGoal::None);
8772 s.select_anchors(vec![new_selection.clone()]);
8773 });
8774 }
8775 return;
8776 }
8777 }
8778
8779 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
8780 active_diagnostics
8781 .primary_range
8782 .to_offset(&buffer)
8783 .to_inclusive()
8784 });
8785 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
8786 if active_primary_range.contains(&selection.head()) {
8787 *active_primary_range.start()
8788 } else {
8789 selection.head()
8790 }
8791 } else {
8792 selection.head()
8793 };
8794 let snapshot = self.snapshot(cx);
8795 loop {
8796 let diagnostics = if direction == Direction::Prev {
8797 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
8798 } else {
8799 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
8800 }
8801 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
8802 let group = diagnostics
8803 // relies on diagnostics_in_range to return diagnostics with the same starting range to
8804 // be sorted in a stable way
8805 // skip until we are at current active diagnostic, if it exists
8806 .skip_while(|entry| {
8807 (match direction {
8808 Direction::Prev => entry.range.start >= search_start,
8809 Direction::Next => entry.range.start <= search_start,
8810 }) && self
8811 .active_diagnostics
8812 .as_ref()
8813 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
8814 })
8815 .find_map(|entry| {
8816 if entry.diagnostic.is_primary
8817 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
8818 && !entry.range.is_empty()
8819 // if we match with the active diagnostic, skip it
8820 && Some(entry.diagnostic.group_id)
8821 != self.active_diagnostics.as_ref().map(|d| d.group_id)
8822 {
8823 Some((entry.range, entry.diagnostic.group_id))
8824 } else {
8825 None
8826 }
8827 });
8828
8829 if let Some((primary_range, group_id)) = group {
8830 if self.activate_diagnostics(group_id, cx) {
8831 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8832 s.select(vec![Selection {
8833 id: selection.id,
8834 start: primary_range.start,
8835 end: primary_range.start,
8836 reversed: false,
8837 goal: SelectionGoal::None,
8838 }]);
8839 });
8840 }
8841 break;
8842 } else {
8843 // Cycle around to the start of the buffer, potentially moving back to the start of
8844 // the currently active diagnostic.
8845 active_primary_range.take();
8846 if direction == Direction::Prev {
8847 if search_start == buffer.len() {
8848 break;
8849 } else {
8850 search_start = buffer.len();
8851 }
8852 } else if search_start == 0 {
8853 break;
8854 } else {
8855 search_start = 0;
8856 }
8857 }
8858 }
8859 }
8860
8861 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
8862 let snapshot = self
8863 .display_map
8864 .update(cx, |display_map, cx| display_map.snapshot(cx));
8865 let selection = self.selections.newest::<Point>(cx);
8866
8867 if !self.seek_in_direction(
8868 &snapshot,
8869 selection.head(),
8870 false,
8871 snapshot.buffer_snapshot.git_diff_hunks_in_range(
8872 MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
8873 ),
8874 cx,
8875 ) {
8876 let wrapped_point = Point::zero();
8877 self.seek_in_direction(
8878 &snapshot,
8879 wrapped_point,
8880 true,
8881 snapshot.buffer_snapshot.git_diff_hunks_in_range(
8882 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
8883 ),
8884 cx,
8885 );
8886 }
8887 }
8888
8889 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
8890 let snapshot = self
8891 .display_map
8892 .update(cx, |display_map, cx| display_map.snapshot(cx));
8893 let selection = self.selections.newest::<Point>(cx);
8894
8895 if !self.seek_in_direction(
8896 &snapshot,
8897 selection.head(),
8898 false,
8899 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
8900 MultiBufferRow(0)..MultiBufferRow(selection.head().row),
8901 ),
8902 cx,
8903 ) {
8904 let wrapped_point = snapshot.buffer_snapshot.max_point();
8905 self.seek_in_direction(
8906 &snapshot,
8907 wrapped_point,
8908 true,
8909 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
8910 MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
8911 ),
8912 cx,
8913 );
8914 }
8915 }
8916
8917 fn seek_in_direction(
8918 &mut self,
8919 snapshot: &DisplaySnapshot,
8920 initial_point: Point,
8921 is_wrapped: bool,
8922 hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
8923 cx: &mut ViewContext<Editor>,
8924 ) -> bool {
8925 let display_point = initial_point.to_display_point(snapshot);
8926 let mut hunks = hunks
8927 .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
8928 .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
8929 .dedup();
8930
8931 if let Some(hunk) = hunks.next() {
8932 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8933 let row = hunk.start_display_row();
8934 let point = DisplayPoint::new(row, 0);
8935 s.select_display_ranges([point..point]);
8936 });
8937
8938 true
8939 } else {
8940 false
8941 }
8942 }
8943
8944 pub fn go_to_definition(
8945 &mut self,
8946 _: &GoToDefinition,
8947 cx: &mut ViewContext<Self>,
8948 ) -> Task<Result<bool>> {
8949 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx)
8950 }
8951
8952 pub fn go_to_declaration(
8953 &mut self,
8954 _: &GoToDeclaration,
8955 cx: &mut ViewContext<Self>,
8956 ) -> Task<Result<bool>> {
8957 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
8958 }
8959
8960 pub fn go_to_declaration_split(
8961 &mut self,
8962 _: &GoToDeclaration,
8963 cx: &mut ViewContext<Self>,
8964 ) -> Task<Result<bool>> {
8965 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
8966 }
8967
8968 pub fn go_to_implementation(
8969 &mut self,
8970 _: &GoToImplementation,
8971 cx: &mut ViewContext<Self>,
8972 ) -> Task<Result<bool>> {
8973 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
8974 }
8975
8976 pub fn go_to_implementation_split(
8977 &mut self,
8978 _: &GoToImplementationSplit,
8979 cx: &mut ViewContext<Self>,
8980 ) -> Task<Result<bool>> {
8981 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
8982 }
8983
8984 pub fn go_to_type_definition(
8985 &mut self,
8986 _: &GoToTypeDefinition,
8987 cx: &mut ViewContext<Self>,
8988 ) -> Task<Result<bool>> {
8989 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
8990 }
8991
8992 pub fn go_to_definition_split(
8993 &mut self,
8994 _: &GoToDefinitionSplit,
8995 cx: &mut ViewContext<Self>,
8996 ) -> Task<Result<bool>> {
8997 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
8998 }
8999
9000 pub fn go_to_type_definition_split(
9001 &mut self,
9002 _: &GoToTypeDefinitionSplit,
9003 cx: &mut ViewContext<Self>,
9004 ) -> Task<Result<bool>> {
9005 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9006 }
9007
9008 fn go_to_definition_of_kind(
9009 &mut self,
9010 kind: GotoDefinitionKind,
9011 split: bool,
9012 cx: &mut ViewContext<Self>,
9013 ) -> Task<Result<bool>> {
9014 let Some(workspace) = self.workspace() else {
9015 return Task::ready(Ok(false));
9016 };
9017 let buffer = self.buffer.read(cx);
9018 let head = self.selections.newest::<usize>(cx).head();
9019 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9020 text_anchor
9021 } else {
9022 return Task::ready(Ok(false));
9023 };
9024
9025 let project = workspace.read(cx).project().clone();
9026 let definitions = project.update(cx, |project, cx| match kind {
9027 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
9028 GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
9029 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
9030 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
9031 });
9032
9033 cx.spawn(|editor, mut cx| async move {
9034 let definitions = definitions.await?;
9035 let navigated = editor
9036 .update(&mut cx, |editor, cx| {
9037 editor.navigate_to_hover_links(
9038 Some(kind),
9039 definitions
9040 .into_iter()
9041 .filter(|location| {
9042 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9043 })
9044 .map(HoverLink::Text)
9045 .collect::<Vec<_>>(),
9046 split,
9047 cx,
9048 )
9049 })?
9050 .await?;
9051 anyhow::Ok(navigated)
9052 })
9053 }
9054
9055 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9056 let position = self.selections.newest_anchor().head();
9057 let Some((buffer, buffer_position)) =
9058 self.buffer.read(cx).text_anchor_for_position(position, cx)
9059 else {
9060 return;
9061 };
9062
9063 cx.spawn(|editor, mut cx| async move {
9064 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9065 editor.update(&mut cx, |_, cx| {
9066 cx.open_url(&url);
9067 })
9068 } else {
9069 Ok(())
9070 }
9071 })
9072 .detach();
9073 }
9074
9075 pub(crate) fn navigate_to_hover_links(
9076 &mut self,
9077 kind: Option<GotoDefinitionKind>,
9078 mut definitions: Vec<HoverLink>,
9079 split: bool,
9080 cx: &mut ViewContext<Editor>,
9081 ) -> Task<Result<bool>> {
9082 // If there is one definition, just open it directly
9083 if definitions.len() == 1 {
9084 let definition = definitions.pop().unwrap();
9085 let target_task = match definition {
9086 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9087 HoverLink::InlayHint(lsp_location, server_id) => {
9088 self.compute_target_location(lsp_location, server_id, cx)
9089 }
9090 HoverLink::Url(url) => {
9091 cx.open_url(&url);
9092 Task::ready(Ok(None))
9093 }
9094 };
9095 cx.spawn(|editor, mut cx| async move {
9096 let target = target_task.await.context("target resolution task")?;
9097 if let Some(target) = target {
9098 editor.update(&mut cx, |editor, cx| {
9099 let Some(workspace) = editor.workspace() else {
9100 return false;
9101 };
9102 let pane = workspace.read(cx).active_pane().clone();
9103
9104 let range = target.range.to_offset(target.buffer.read(cx));
9105 let range = editor.range_for_match(&range);
9106
9107 /// If select range has more than one line, we
9108 /// just point the cursor to range.start.
9109 fn check_multiline_range(
9110 buffer: &Buffer,
9111 range: Range<usize>,
9112 ) -> Range<usize> {
9113 if buffer.offset_to_point(range.start).row
9114 == buffer.offset_to_point(range.end).row
9115 {
9116 range
9117 } else {
9118 range.start..range.start
9119 }
9120 }
9121
9122 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9123 let buffer = target.buffer.read(cx);
9124 let range = check_multiline_range(buffer, range);
9125 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
9126 s.select_ranges([range]);
9127 });
9128 } else {
9129 cx.window_context().defer(move |cx| {
9130 let target_editor: View<Self> =
9131 workspace.update(cx, |workspace, cx| {
9132 let pane = if split {
9133 workspace.adjacent_pane(cx)
9134 } else {
9135 workspace.active_pane().clone()
9136 };
9137
9138 workspace.open_project_item(
9139 pane,
9140 target.buffer.clone(),
9141 true,
9142 true,
9143 cx,
9144 )
9145 });
9146 target_editor.update(cx, |target_editor, cx| {
9147 // When selecting a definition in a different buffer, disable the nav history
9148 // to avoid creating a history entry at the previous cursor location.
9149 pane.update(cx, |pane, _| pane.disable_history());
9150 let buffer = target.buffer.read(cx);
9151 let range = check_multiline_range(buffer, range);
9152 target_editor.change_selections(
9153 Some(Autoscroll::focused()),
9154 cx,
9155 |s| {
9156 s.select_ranges([range]);
9157 },
9158 );
9159 pane.update(cx, |pane, _| pane.enable_history());
9160 });
9161 });
9162 }
9163 true
9164 })
9165 } else {
9166 Ok(false)
9167 }
9168 })
9169 } else if !definitions.is_empty() {
9170 let replica_id = self.replica_id(cx);
9171 cx.spawn(|editor, mut cx| async move {
9172 let (title, location_tasks, workspace) = editor
9173 .update(&mut cx, |editor, cx| {
9174 let tab_kind = match kind {
9175 Some(GotoDefinitionKind::Implementation) => "Implementations",
9176 _ => "Definitions",
9177 };
9178 let title = definitions
9179 .iter()
9180 .find_map(|definition| match definition {
9181 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9182 let buffer = origin.buffer.read(cx);
9183 format!(
9184 "{} for {}",
9185 tab_kind,
9186 buffer
9187 .text_for_range(origin.range.clone())
9188 .collect::<String>()
9189 )
9190 }),
9191 HoverLink::InlayHint(_, _) => None,
9192 HoverLink::Url(_) => None,
9193 })
9194 .unwrap_or(tab_kind.to_string());
9195 let location_tasks = definitions
9196 .into_iter()
9197 .map(|definition| match definition {
9198 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9199 HoverLink::InlayHint(lsp_location, server_id) => {
9200 editor.compute_target_location(lsp_location, server_id, cx)
9201 }
9202 HoverLink::Url(_) => Task::ready(Ok(None)),
9203 })
9204 .collect::<Vec<_>>();
9205 (title, location_tasks, editor.workspace().clone())
9206 })
9207 .context("location tasks preparation")?;
9208
9209 let locations = futures::future::join_all(location_tasks)
9210 .await
9211 .into_iter()
9212 .filter_map(|location| location.transpose())
9213 .collect::<Result<_>>()
9214 .context("location tasks")?;
9215
9216 let Some(workspace) = workspace else {
9217 return Ok(false);
9218 };
9219 let opened = workspace
9220 .update(&mut cx, |workspace, cx| {
9221 Self::open_locations_in_multibuffer(
9222 workspace, locations, replica_id, title, split, cx,
9223 )
9224 })
9225 .ok();
9226
9227 anyhow::Ok(opened.is_some())
9228 })
9229 } else {
9230 Task::ready(Ok(false))
9231 }
9232 }
9233
9234 fn compute_target_location(
9235 &self,
9236 lsp_location: lsp::Location,
9237 server_id: LanguageServerId,
9238 cx: &mut ViewContext<Editor>,
9239 ) -> Task<anyhow::Result<Option<Location>>> {
9240 let Some(project) = self.project.clone() else {
9241 return Task::Ready(Some(Ok(None)));
9242 };
9243
9244 cx.spawn(move |editor, mut cx| async move {
9245 let location_task = editor.update(&mut cx, |editor, cx| {
9246 project.update(cx, |project, cx| {
9247 let language_server_name =
9248 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9249 project
9250 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9251 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9252 });
9253 language_server_name.map(|language_server_name| {
9254 project.open_local_buffer_via_lsp(
9255 lsp_location.uri.clone(),
9256 server_id,
9257 language_server_name,
9258 cx,
9259 )
9260 })
9261 })
9262 })?;
9263 let location = match location_task {
9264 Some(task) => Some({
9265 let target_buffer_handle = task.await.context("open local buffer")?;
9266 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9267 let target_start = target_buffer
9268 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9269 let target_end = target_buffer
9270 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9271 target_buffer.anchor_after(target_start)
9272 ..target_buffer.anchor_before(target_end)
9273 })?;
9274 Location {
9275 buffer: target_buffer_handle,
9276 range,
9277 }
9278 }),
9279 None => None,
9280 };
9281 Ok(location)
9282 })
9283 }
9284
9285 pub fn find_all_references(
9286 &mut self,
9287 _: &FindAllReferences,
9288 cx: &mut ViewContext<Self>,
9289 ) -> Option<Task<Result<()>>> {
9290 let multi_buffer = self.buffer.read(cx);
9291 let selection = self.selections.newest::<usize>(cx);
9292 let head = selection.head();
9293
9294 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9295 let head_anchor = multi_buffer_snapshot.anchor_at(
9296 head,
9297 if head < selection.tail() {
9298 Bias::Right
9299 } else {
9300 Bias::Left
9301 },
9302 );
9303
9304 match self
9305 .find_all_references_task_sources
9306 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9307 {
9308 Ok(_) => {
9309 log::info!(
9310 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9311 );
9312 return None;
9313 }
9314 Err(i) => {
9315 self.find_all_references_task_sources.insert(i, head_anchor);
9316 }
9317 }
9318
9319 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9320 let replica_id = self.replica_id(cx);
9321 let workspace = self.workspace()?;
9322 let project = workspace.read(cx).project().clone();
9323 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9324 Some(cx.spawn(|editor, mut cx| async move {
9325 let _cleanup = defer({
9326 let mut cx = cx.clone();
9327 move || {
9328 let _ = editor.update(&mut cx, |editor, _| {
9329 if let Ok(i) =
9330 editor
9331 .find_all_references_task_sources
9332 .binary_search_by(|anchor| {
9333 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9334 })
9335 {
9336 editor.find_all_references_task_sources.remove(i);
9337 }
9338 });
9339 }
9340 });
9341
9342 let locations = references.await?;
9343 if locations.is_empty() {
9344 return anyhow::Ok(());
9345 }
9346
9347 workspace.update(&mut cx, |workspace, cx| {
9348 let title = locations
9349 .first()
9350 .as_ref()
9351 .map(|location| {
9352 let buffer = location.buffer.read(cx);
9353 format!(
9354 "References to `{}`",
9355 buffer
9356 .text_for_range(location.range.clone())
9357 .collect::<String>()
9358 )
9359 })
9360 .unwrap();
9361 Self::open_locations_in_multibuffer(
9362 workspace, locations, replica_id, title, false, cx,
9363 );
9364 })
9365 }))
9366 }
9367
9368 /// Opens a multibuffer with the given project locations in it
9369 pub fn open_locations_in_multibuffer(
9370 workspace: &mut Workspace,
9371 mut locations: Vec<Location>,
9372 replica_id: ReplicaId,
9373 title: String,
9374 split: bool,
9375 cx: &mut ViewContext<Workspace>,
9376 ) {
9377 // If there are multiple definitions, open them in a multibuffer
9378 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9379 let mut locations = locations.into_iter().peekable();
9380 let mut ranges_to_highlight = Vec::new();
9381 let capability = workspace.project().read(cx).capability();
9382
9383 let excerpt_buffer = cx.new_model(|cx| {
9384 let mut multibuffer = MultiBuffer::new(replica_id, capability);
9385 while let Some(location) = locations.next() {
9386 let buffer = location.buffer.read(cx);
9387 let mut ranges_for_buffer = Vec::new();
9388 let range = location.range.to_offset(buffer);
9389 ranges_for_buffer.push(range.clone());
9390
9391 while let Some(next_location) = locations.peek() {
9392 if next_location.buffer == location.buffer {
9393 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9394 locations.next();
9395 } else {
9396 break;
9397 }
9398 }
9399
9400 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9401 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9402 location.buffer.clone(),
9403 ranges_for_buffer,
9404 DEFAULT_MULTIBUFFER_CONTEXT,
9405 cx,
9406 ))
9407 }
9408
9409 multibuffer.with_title(title)
9410 });
9411
9412 let editor = cx.new_view(|cx| {
9413 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9414 });
9415 editor.update(cx, |editor, cx| {
9416 if let Some(first_range) = ranges_to_highlight.first() {
9417 editor.change_selections(None, cx, |selections| {
9418 selections.clear_disjoint();
9419 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9420 });
9421 }
9422 editor.highlight_background::<Self>(
9423 &ranges_to_highlight,
9424 |theme| theme.editor_highlighted_line_background,
9425 cx,
9426 );
9427 });
9428
9429 let item = Box::new(editor);
9430 let item_id = item.item_id();
9431
9432 if split {
9433 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9434 } else {
9435 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9436 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9437 pane.close_current_preview_item(cx)
9438 } else {
9439 None
9440 }
9441 });
9442 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9443 }
9444 workspace.active_pane().update(cx, |pane, cx| {
9445 pane.set_preview_item_id(Some(item_id), cx);
9446 });
9447 }
9448
9449 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9450 use language::ToOffset as _;
9451
9452 let project = self.project.clone()?;
9453 let selection = self.selections.newest_anchor().clone();
9454 let (cursor_buffer, cursor_buffer_position) = self
9455 .buffer
9456 .read(cx)
9457 .text_anchor_for_position(selection.head(), cx)?;
9458 let (tail_buffer, cursor_buffer_position_end) = self
9459 .buffer
9460 .read(cx)
9461 .text_anchor_for_position(selection.tail(), cx)?;
9462 if tail_buffer != cursor_buffer {
9463 return None;
9464 }
9465
9466 let snapshot = cursor_buffer.read(cx).snapshot();
9467 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9468 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9469 let prepare_rename = project.update(cx, |project, cx| {
9470 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
9471 });
9472 drop(snapshot);
9473
9474 Some(cx.spawn(|this, mut cx| async move {
9475 let rename_range = if let Some(range) = prepare_rename.await? {
9476 Some(range)
9477 } else {
9478 this.update(&mut cx, |this, cx| {
9479 let buffer = this.buffer.read(cx).snapshot(cx);
9480 let mut buffer_highlights = this
9481 .document_highlights_for_position(selection.head(), &buffer)
9482 .filter(|highlight| {
9483 highlight.start.excerpt_id == selection.head().excerpt_id
9484 && highlight.end.excerpt_id == selection.head().excerpt_id
9485 });
9486 buffer_highlights
9487 .next()
9488 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9489 })?
9490 };
9491 if let Some(rename_range) = rename_range {
9492 this.update(&mut cx, |this, cx| {
9493 let snapshot = cursor_buffer.read(cx).snapshot();
9494 let rename_buffer_range = rename_range.to_offset(&snapshot);
9495 let cursor_offset_in_rename_range =
9496 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9497 let cursor_offset_in_rename_range_end =
9498 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9499
9500 this.take_rename(false, cx);
9501 let buffer = this.buffer.read(cx).read(cx);
9502 let cursor_offset = selection.head().to_offset(&buffer);
9503 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9504 let rename_end = rename_start + rename_buffer_range.len();
9505 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9506 let mut old_highlight_id = None;
9507 let old_name: Arc<str> = buffer
9508 .chunks(rename_start..rename_end, true)
9509 .map(|chunk| {
9510 if old_highlight_id.is_none() {
9511 old_highlight_id = chunk.syntax_highlight_id;
9512 }
9513 chunk.text
9514 })
9515 .collect::<String>()
9516 .into();
9517
9518 drop(buffer);
9519
9520 // Position the selection in the rename editor so that it matches the current selection.
9521 this.show_local_selections = false;
9522 let rename_editor = cx.new_view(|cx| {
9523 let mut editor = Editor::single_line(cx);
9524 editor.buffer.update(cx, |buffer, cx| {
9525 buffer.edit([(0..0, old_name.clone())], None, cx)
9526 });
9527 let rename_selection_range = match cursor_offset_in_rename_range
9528 .cmp(&cursor_offset_in_rename_range_end)
9529 {
9530 Ordering::Equal => {
9531 editor.select_all(&SelectAll, cx);
9532 return editor;
9533 }
9534 Ordering::Less => {
9535 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9536 }
9537 Ordering::Greater => {
9538 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9539 }
9540 };
9541 if rename_selection_range.end > old_name.len() {
9542 editor.select_all(&SelectAll, cx);
9543 } else {
9544 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9545 s.select_ranges([rename_selection_range]);
9546 });
9547 }
9548 editor
9549 });
9550 cx.subscribe(&rename_editor, |_, _, e, cx| match e {
9551 EditorEvent::Focused => cx.emit(EditorEvent::FocusedIn),
9552 _ => {}
9553 })
9554 .detach();
9555
9556 let write_highlights =
9557 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
9558 let read_highlights =
9559 this.clear_background_highlights::<DocumentHighlightRead>(cx);
9560 let ranges = write_highlights
9561 .iter()
9562 .flat_map(|(_, ranges)| ranges.iter())
9563 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
9564 .cloned()
9565 .collect();
9566
9567 this.highlight_text::<Rename>(
9568 ranges,
9569 HighlightStyle {
9570 fade_out: Some(0.6),
9571 ..Default::default()
9572 },
9573 cx,
9574 );
9575 let rename_focus_handle = rename_editor.focus_handle(cx);
9576 cx.focus(&rename_focus_handle);
9577 let block_id = this.insert_blocks(
9578 [BlockProperties {
9579 style: BlockStyle::Flex,
9580 position: range.start,
9581 height: 1,
9582 render: Box::new({
9583 let rename_editor = rename_editor.clone();
9584 move |cx: &mut BlockContext| {
9585 let mut text_style = cx.editor_style.text.clone();
9586 if let Some(highlight_style) = old_highlight_id
9587 .and_then(|h| h.style(&cx.editor_style.syntax))
9588 {
9589 text_style = text_style.highlight(highlight_style);
9590 }
9591 div()
9592 .pl(cx.anchor_x)
9593 .child(EditorElement::new(
9594 &rename_editor,
9595 EditorStyle {
9596 background: cx.theme().system().transparent,
9597 local_player: cx.editor_style.local_player,
9598 text: text_style,
9599 scrollbar_width: cx.editor_style.scrollbar_width,
9600 syntax: cx.editor_style.syntax.clone(),
9601 status: cx.editor_style.status.clone(),
9602 inlay_hints_style: HighlightStyle {
9603 color: Some(cx.theme().status().hint),
9604 font_weight: Some(FontWeight::BOLD),
9605 ..HighlightStyle::default()
9606 },
9607 suggestions_style: HighlightStyle {
9608 color: Some(cx.theme().status().predictive),
9609 ..HighlightStyle::default()
9610 },
9611 },
9612 ))
9613 .into_any_element()
9614 }
9615 }),
9616 disposition: BlockDisposition::Below,
9617 }],
9618 Some(Autoscroll::fit()),
9619 cx,
9620 )[0];
9621 this.pending_rename = Some(RenameState {
9622 range,
9623 old_name,
9624 editor: rename_editor,
9625 block_id,
9626 });
9627 })?;
9628 }
9629
9630 Ok(())
9631 }))
9632 }
9633
9634 pub fn confirm_rename(
9635 &mut self,
9636 _: &ConfirmRename,
9637 cx: &mut ViewContext<Self>,
9638 ) -> Option<Task<Result<()>>> {
9639 let rename = self.take_rename(false, cx)?;
9640 let workspace = self.workspace()?;
9641 let (start_buffer, start) = self
9642 .buffer
9643 .read(cx)
9644 .text_anchor_for_position(rename.range.start, cx)?;
9645 let (end_buffer, end) = self
9646 .buffer
9647 .read(cx)
9648 .text_anchor_for_position(rename.range.end, cx)?;
9649 if start_buffer != end_buffer {
9650 return None;
9651 }
9652
9653 let buffer = start_buffer;
9654 let range = start..end;
9655 let old_name = rename.old_name;
9656 let new_name = rename.editor.read(cx).text(cx);
9657
9658 let rename = workspace
9659 .read(cx)
9660 .project()
9661 .clone()
9662 .update(cx, |project, cx| {
9663 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
9664 });
9665 let workspace = workspace.downgrade();
9666
9667 Some(cx.spawn(|editor, mut cx| async move {
9668 let project_transaction = rename.await?;
9669 Self::open_project_transaction(
9670 &editor,
9671 workspace,
9672 project_transaction,
9673 format!("Rename: {} → {}", old_name, new_name),
9674 cx.clone(),
9675 )
9676 .await?;
9677
9678 editor.update(&mut cx, |editor, cx| {
9679 editor.refresh_document_highlights(cx);
9680 })?;
9681 Ok(())
9682 }))
9683 }
9684
9685 fn take_rename(
9686 &mut self,
9687 moving_cursor: bool,
9688 cx: &mut ViewContext<Self>,
9689 ) -> Option<RenameState> {
9690 let rename = self.pending_rename.take()?;
9691 if rename.editor.focus_handle(cx).is_focused(cx) {
9692 cx.focus(&self.focus_handle);
9693 }
9694
9695 self.remove_blocks(
9696 [rename.block_id].into_iter().collect(),
9697 Some(Autoscroll::fit()),
9698 cx,
9699 );
9700 self.clear_highlights::<Rename>(cx);
9701 self.show_local_selections = true;
9702
9703 if moving_cursor {
9704 let rename_editor = rename.editor.read(cx);
9705 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
9706
9707 // Update the selection to match the position of the selection inside
9708 // the rename editor.
9709 let snapshot = self.buffer.read(cx).read(cx);
9710 let rename_range = rename.range.to_offset(&snapshot);
9711 let cursor_in_editor = snapshot
9712 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
9713 .min(rename_range.end);
9714 drop(snapshot);
9715
9716 self.change_selections(None, cx, |s| {
9717 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
9718 });
9719 } else {
9720 self.refresh_document_highlights(cx);
9721 }
9722
9723 Some(rename)
9724 }
9725
9726 pub fn pending_rename(&self) -> Option<&RenameState> {
9727 self.pending_rename.as_ref()
9728 }
9729
9730 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9731 let project = match &self.project {
9732 Some(project) => project.clone(),
9733 None => return None,
9734 };
9735
9736 Some(self.perform_format(project, FormatTrigger::Manual, cx))
9737 }
9738
9739 fn perform_format(
9740 &mut self,
9741 project: Model<Project>,
9742 trigger: FormatTrigger,
9743 cx: &mut ViewContext<Self>,
9744 ) -> Task<Result<()>> {
9745 let buffer = self.buffer().clone();
9746 let mut buffers = buffer.read(cx).all_buffers();
9747 if trigger == FormatTrigger::Save {
9748 buffers.retain(|buffer| buffer.read(cx).is_dirty());
9749 }
9750
9751 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
9752 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
9753
9754 cx.spawn(|_, mut cx| async move {
9755 let transaction = futures::select_biased! {
9756 () = timeout => {
9757 log::warn!("timed out waiting for formatting");
9758 None
9759 }
9760 transaction = format.log_err().fuse() => transaction,
9761 };
9762
9763 buffer
9764 .update(&mut cx, |buffer, cx| {
9765 if let Some(transaction) = transaction {
9766 if !buffer.is_singleton() {
9767 buffer.push_transaction(&transaction.0, cx);
9768 }
9769 }
9770
9771 cx.notify();
9772 })
9773 .ok();
9774
9775 Ok(())
9776 })
9777 }
9778
9779 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
9780 if let Some(project) = self.project.clone() {
9781 self.buffer.update(cx, |multi_buffer, cx| {
9782 project.update(cx, |project, cx| {
9783 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
9784 });
9785 })
9786 }
9787 }
9788
9789 fn cancel_language_server_work(
9790 &mut self,
9791 _: &CancelLanguageServerWork,
9792 cx: &mut ViewContext<Self>,
9793 ) {
9794 if let Some(project) = self.project.clone() {
9795 self.buffer.update(cx, |multi_buffer, cx| {
9796 project.update(cx, |project, cx| {
9797 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
9798 });
9799 })
9800 }
9801 }
9802
9803 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
9804 cx.show_character_palette();
9805 }
9806
9807 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
9808 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
9809 let buffer = self.buffer.read(cx).snapshot(cx);
9810 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
9811 let is_valid = buffer
9812 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
9813 .any(|entry| {
9814 entry.diagnostic.is_primary
9815 && !entry.range.is_empty()
9816 && entry.range.start == primary_range_start
9817 && entry.diagnostic.message == active_diagnostics.primary_message
9818 });
9819
9820 if is_valid != active_diagnostics.is_valid {
9821 active_diagnostics.is_valid = is_valid;
9822 let mut new_styles = HashMap::default();
9823 for (block_id, diagnostic) in &active_diagnostics.blocks {
9824 new_styles.insert(
9825 *block_id,
9826 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
9827 );
9828 }
9829 self.display_map.update(cx, |display_map, _cx| {
9830 display_map.replace_blocks(new_styles)
9831 });
9832 }
9833 }
9834 }
9835
9836 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
9837 self.dismiss_diagnostics(cx);
9838 let snapshot = self.snapshot(cx);
9839 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
9840 let buffer = self.buffer.read(cx).snapshot(cx);
9841
9842 let mut primary_range = None;
9843 let mut primary_message = None;
9844 let mut group_end = Point::zero();
9845 let diagnostic_group = buffer
9846 .diagnostic_group::<MultiBufferPoint>(group_id)
9847 .filter_map(|entry| {
9848 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
9849 && (entry.range.start.row == entry.range.end.row
9850 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
9851 {
9852 return None;
9853 }
9854 if entry.range.end > group_end {
9855 group_end = entry.range.end;
9856 }
9857 if entry.diagnostic.is_primary {
9858 primary_range = Some(entry.range.clone());
9859 primary_message = Some(entry.diagnostic.message.clone());
9860 }
9861 Some(entry)
9862 })
9863 .collect::<Vec<_>>();
9864 let primary_range = primary_range?;
9865 let primary_message = primary_message?;
9866 let primary_range =
9867 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
9868
9869 let blocks = display_map
9870 .insert_blocks(
9871 diagnostic_group.iter().map(|entry| {
9872 let diagnostic = entry.diagnostic.clone();
9873 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
9874 BlockProperties {
9875 style: BlockStyle::Fixed,
9876 position: buffer.anchor_after(entry.range.start),
9877 height: message_height,
9878 render: diagnostic_block_renderer(diagnostic, None, true, true),
9879 disposition: BlockDisposition::Below,
9880 }
9881 }),
9882 cx,
9883 )
9884 .into_iter()
9885 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
9886 .collect();
9887
9888 Some(ActiveDiagnosticGroup {
9889 primary_range,
9890 primary_message,
9891 group_id,
9892 blocks,
9893 is_valid: true,
9894 })
9895 });
9896 self.active_diagnostics.is_some()
9897 }
9898
9899 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
9900 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
9901 self.display_map.update(cx, |display_map, cx| {
9902 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
9903 });
9904 cx.notify();
9905 }
9906 }
9907
9908 pub fn set_selections_from_remote(
9909 &mut self,
9910 selections: Vec<Selection<Anchor>>,
9911 pending_selection: Option<Selection<Anchor>>,
9912 cx: &mut ViewContext<Self>,
9913 ) {
9914 let old_cursor_position = self.selections.newest_anchor().head();
9915 self.selections.change_with(cx, |s| {
9916 s.select_anchors(selections);
9917 if let Some(pending_selection) = pending_selection {
9918 s.set_pending(pending_selection, SelectMode::Character);
9919 } else {
9920 s.clear_pending();
9921 }
9922 });
9923 self.selections_did_change(false, &old_cursor_position, true, cx);
9924 }
9925
9926 fn push_to_selection_history(&mut self) {
9927 self.selection_history.push(SelectionHistoryEntry {
9928 selections: self.selections.disjoint_anchors(),
9929 select_next_state: self.select_next_state.clone(),
9930 select_prev_state: self.select_prev_state.clone(),
9931 add_selections_state: self.add_selections_state.clone(),
9932 });
9933 }
9934
9935 pub fn transact(
9936 &mut self,
9937 cx: &mut ViewContext<Self>,
9938 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
9939 ) -> Option<TransactionId> {
9940 self.start_transaction_at(Instant::now(), cx);
9941 update(self, cx);
9942 self.end_transaction_at(Instant::now(), cx)
9943 }
9944
9945 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
9946 self.end_selection(cx);
9947 if let Some(tx_id) = self
9948 .buffer
9949 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
9950 {
9951 self.selection_history
9952 .insert_transaction(tx_id, self.selections.disjoint_anchors());
9953 cx.emit(EditorEvent::TransactionBegun {
9954 transaction_id: tx_id,
9955 })
9956 }
9957 }
9958
9959 fn end_transaction_at(
9960 &mut self,
9961 now: Instant,
9962 cx: &mut ViewContext<Self>,
9963 ) -> Option<TransactionId> {
9964 if let Some(transaction_id) = self
9965 .buffer
9966 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
9967 {
9968 if let Some((_, end_selections)) =
9969 self.selection_history.transaction_mut(transaction_id)
9970 {
9971 *end_selections = Some(self.selections.disjoint_anchors());
9972 } else {
9973 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
9974 }
9975
9976 cx.emit(EditorEvent::Edited { transaction_id });
9977 Some(transaction_id)
9978 } else {
9979 None
9980 }
9981 }
9982
9983 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
9984 let mut fold_ranges = Vec::new();
9985
9986 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
9987
9988 let selections = self.selections.all_adjusted(cx);
9989 for selection in selections {
9990 let range = selection.range().sorted();
9991 let buffer_start_row = range.start.row;
9992
9993 for row in (0..=range.end.row).rev() {
9994 if let Some((foldable_range, fold_text)) =
9995 display_map.foldable_range(MultiBufferRow(row))
9996 {
9997 if foldable_range.end.row >= buffer_start_row {
9998 fold_ranges.push((foldable_range, fold_text));
9999 if row <= range.start.row {
10000 break;
10001 }
10002 }
10003 }
10004 }
10005 }
10006
10007 self.fold_ranges(fold_ranges, true, cx);
10008 }
10009
10010 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10011 let buffer_row = fold_at.buffer_row;
10012 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10013
10014 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10015 let autoscroll = self
10016 .selections
10017 .all::<Point>(cx)
10018 .iter()
10019 .any(|selection| fold_range.overlaps(&selection.range()));
10020
10021 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10022 }
10023 }
10024
10025 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10026 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10027 let buffer = &display_map.buffer_snapshot;
10028 let selections = self.selections.all::<Point>(cx);
10029 let ranges = selections
10030 .iter()
10031 .map(|s| {
10032 let range = s.display_range(&display_map).sorted();
10033 let mut start = range.start.to_point(&display_map);
10034 let mut end = range.end.to_point(&display_map);
10035 start.column = 0;
10036 end.column = buffer.line_len(MultiBufferRow(end.row));
10037 start..end
10038 })
10039 .collect::<Vec<_>>();
10040
10041 self.unfold_ranges(ranges, true, true, cx);
10042 }
10043
10044 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10045 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10046
10047 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10048 ..Point::new(
10049 unfold_at.buffer_row.0,
10050 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10051 );
10052
10053 let autoscroll = self
10054 .selections
10055 .all::<Point>(cx)
10056 .iter()
10057 .any(|selection| selection.range().overlaps(&intersection_range));
10058
10059 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10060 }
10061
10062 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10063 let selections = self.selections.all::<Point>(cx);
10064 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10065 let line_mode = self.selections.line_mode;
10066 let ranges = selections.into_iter().map(|s| {
10067 if line_mode {
10068 let start = Point::new(s.start.row, 0);
10069 let end = Point::new(
10070 s.end.row,
10071 display_map
10072 .buffer_snapshot
10073 .line_len(MultiBufferRow(s.end.row)),
10074 );
10075 (start..end, display_map.fold_placeholder.clone())
10076 } else {
10077 (s.start..s.end, display_map.fold_placeholder.clone())
10078 }
10079 });
10080 self.fold_ranges(ranges, true, cx);
10081 }
10082
10083 pub fn fold_ranges<T: ToOffset + Clone>(
10084 &mut self,
10085 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10086 auto_scroll: bool,
10087 cx: &mut ViewContext<Self>,
10088 ) {
10089 let mut fold_ranges = Vec::new();
10090 let mut buffers_affected = HashMap::default();
10091 let multi_buffer = self.buffer().read(cx);
10092 for (fold_range, fold_text) in ranges {
10093 if let Some((_, buffer, _)) =
10094 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10095 {
10096 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10097 };
10098 fold_ranges.push((fold_range, fold_text));
10099 }
10100
10101 let mut ranges = fold_ranges.into_iter().peekable();
10102 if ranges.peek().is_some() {
10103 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10104
10105 if auto_scroll {
10106 self.request_autoscroll(Autoscroll::fit(), cx);
10107 }
10108
10109 for buffer in buffers_affected.into_values() {
10110 self.sync_expanded_diff_hunks(buffer, cx);
10111 }
10112
10113 cx.notify();
10114
10115 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10116 // Clear diagnostics block when folding a range that contains it.
10117 let snapshot = self.snapshot(cx);
10118 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10119 drop(snapshot);
10120 self.active_diagnostics = Some(active_diagnostics);
10121 self.dismiss_diagnostics(cx);
10122 } else {
10123 self.active_diagnostics = Some(active_diagnostics);
10124 }
10125 }
10126
10127 self.scrollbar_marker_state.dirty = true;
10128 }
10129 }
10130
10131 pub fn unfold_ranges<T: ToOffset + Clone>(
10132 &mut self,
10133 ranges: impl IntoIterator<Item = Range<T>>,
10134 inclusive: bool,
10135 auto_scroll: bool,
10136 cx: &mut ViewContext<Self>,
10137 ) {
10138 let mut unfold_ranges = Vec::new();
10139 let mut buffers_affected = HashMap::default();
10140 let multi_buffer = self.buffer().read(cx);
10141 for range in ranges {
10142 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10143 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10144 };
10145 unfold_ranges.push(range);
10146 }
10147
10148 let mut ranges = unfold_ranges.into_iter().peekable();
10149 if ranges.peek().is_some() {
10150 self.display_map
10151 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10152 if auto_scroll {
10153 self.request_autoscroll(Autoscroll::fit(), cx);
10154 }
10155
10156 for buffer in buffers_affected.into_values() {
10157 self.sync_expanded_diff_hunks(buffer, cx);
10158 }
10159
10160 cx.notify();
10161 self.scrollbar_marker_state.dirty = true;
10162 self.active_indent_guides_state.dirty = true;
10163 }
10164 }
10165
10166 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10167 if hovered != self.gutter_hovered {
10168 self.gutter_hovered = hovered;
10169 cx.notify();
10170 }
10171 }
10172
10173 pub fn insert_blocks(
10174 &mut self,
10175 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10176 autoscroll: Option<Autoscroll>,
10177 cx: &mut ViewContext<Self>,
10178 ) -> Vec<CustomBlockId> {
10179 let blocks = self
10180 .display_map
10181 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10182 if let Some(autoscroll) = autoscroll {
10183 self.request_autoscroll(autoscroll, cx);
10184 }
10185 blocks
10186 }
10187
10188 pub fn resize_blocks(
10189 &mut self,
10190 heights: HashMap<CustomBlockId, u32>,
10191 autoscroll: Option<Autoscroll>,
10192 cx: &mut ViewContext<Self>,
10193 ) {
10194 self.display_map
10195 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10196 if let Some(autoscroll) = autoscroll {
10197 self.request_autoscroll(autoscroll, cx);
10198 }
10199 }
10200
10201 pub fn replace_blocks(
10202 &mut self,
10203 renderers: HashMap<CustomBlockId, RenderBlock>,
10204 autoscroll: Option<Autoscroll>,
10205 cx: &mut ViewContext<Self>,
10206 ) {
10207 self.display_map
10208 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10209 if let Some(autoscroll) = autoscroll {
10210 self.request_autoscroll(autoscroll, cx);
10211 } else {
10212 cx.notify();
10213 }
10214 }
10215
10216 pub fn remove_blocks(
10217 &mut self,
10218 block_ids: HashSet<CustomBlockId>,
10219 autoscroll: Option<Autoscroll>,
10220 cx: &mut ViewContext<Self>,
10221 ) {
10222 self.display_map.update(cx, |display_map, cx| {
10223 display_map.remove_blocks(block_ids, cx)
10224 });
10225 if let Some(autoscroll) = autoscroll {
10226 self.request_autoscroll(autoscroll, cx);
10227 }
10228 }
10229
10230 pub fn row_for_block(
10231 &self,
10232 block_id: CustomBlockId,
10233 cx: &mut ViewContext<Self>,
10234 ) -> Option<DisplayRow> {
10235 self.display_map
10236 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10237 }
10238
10239 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10240 self.focused_block = Some(focused_block);
10241 }
10242
10243 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10244 self.focused_block.take()
10245 }
10246
10247 pub fn insert_creases(
10248 &mut self,
10249 creases: impl IntoIterator<Item = Crease>,
10250 cx: &mut ViewContext<Self>,
10251 ) -> Vec<CreaseId> {
10252 self.display_map
10253 .update(cx, |map, cx| map.insert_creases(creases, cx))
10254 }
10255
10256 pub fn remove_creases(
10257 &mut self,
10258 ids: impl IntoIterator<Item = CreaseId>,
10259 cx: &mut ViewContext<Self>,
10260 ) {
10261 self.display_map
10262 .update(cx, |map, cx| map.remove_creases(ids, cx));
10263 }
10264
10265 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10266 self.display_map
10267 .update(cx, |map, cx| map.snapshot(cx))
10268 .longest_row()
10269 }
10270
10271 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10272 self.display_map
10273 .update(cx, |map, cx| map.snapshot(cx))
10274 .max_point()
10275 }
10276
10277 pub fn text(&self, cx: &AppContext) -> String {
10278 self.buffer.read(cx).read(cx).text()
10279 }
10280
10281 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10282 let text = self.text(cx);
10283 let text = text.trim();
10284
10285 if text.is_empty() {
10286 return None;
10287 }
10288
10289 Some(text.to_string())
10290 }
10291
10292 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10293 self.transact(cx, |this, cx| {
10294 this.buffer
10295 .read(cx)
10296 .as_singleton()
10297 .expect("you can only call set_text on editors for singleton buffers")
10298 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10299 });
10300 }
10301
10302 pub fn display_text(&self, cx: &mut AppContext) -> String {
10303 self.display_map
10304 .update(cx, |map, cx| map.snapshot(cx))
10305 .text()
10306 }
10307
10308 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10309 let mut wrap_guides = smallvec::smallvec![];
10310
10311 if self.show_wrap_guides == Some(false) {
10312 return wrap_guides;
10313 }
10314
10315 let settings = self.buffer.read(cx).settings_at(0, cx);
10316 if settings.show_wrap_guides {
10317 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10318 wrap_guides.push((soft_wrap as usize, true));
10319 }
10320 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10321 }
10322
10323 wrap_guides
10324 }
10325
10326 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10327 let settings = self.buffer.read(cx).settings_at(0, cx);
10328 let mode = self
10329 .soft_wrap_mode_override
10330 .unwrap_or_else(|| settings.soft_wrap);
10331 match mode {
10332 language_settings::SoftWrap::None => SoftWrap::None,
10333 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10334 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10335 language_settings::SoftWrap::PreferredLineLength => {
10336 SoftWrap::Column(settings.preferred_line_length)
10337 }
10338 }
10339 }
10340
10341 pub fn set_soft_wrap_mode(
10342 &mut self,
10343 mode: language_settings::SoftWrap,
10344 cx: &mut ViewContext<Self>,
10345 ) {
10346 self.soft_wrap_mode_override = Some(mode);
10347 cx.notify();
10348 }
10349
10350 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10351 let rem_size = cx.rem_size();
10352 self.display_map.update(cx, |map, cx| {
10353 map.set_font(
10354 style.text.font(),
10355 style.text.font_size.to_pixels(rem_size),
10356 cx,
10357 )
10358 });
10359 self.style = Some(style);
10360 }
10361
10362 pub fn style(&self) -> Option<&EditorStyle> {
10363 self.style.as_ref()
10364 }
10365
10366 // Called by the element. This method is not designed to be called outside of the editor
10367 // element's layout code because it does not notify when rewrapping is computed synchronously.
10368 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10369 self.display_map
10370 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10371 }
10372
10373 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10374 if self.soft_wrap_mode_override.is_some() {
10375 self.soft_wrap_mode_override.take();
10376 } else {
10377 let soft_wrap = match self.soft_wrap_mode(cx) {
10378 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10379 SoftWrap::EditorWidth | SoftWrap::Column(_) => {
10380 language_settings::SoftWrap::PreferLine
10381 }
10382 };
10383 self.soft_wrap_mode_override = Some(soft_wrap);
10384 }
10385 cx.notify();
10386 }
10387
10388 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10389 let Some(workspace) = self.workspace() else {
10390 return;
10391 };
10392 let fs = workspace.read(cx).app_state().fs.clone();
10393 let current_show = TabBarSettings::get_global(cx).show;
10394 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10395 setting.show = Some(!current_show);
10396 });
10397 }
10398
10399 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10400 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10401 self.buffer
10402 .read(cx)
10403 .settings_at(0, cx)
10404 .indent_guides
10405 .enabled
10406 });
10407 self.show_indent_guides = Some(!currently_enabled);
10408 cx.notify();
10409 }
10410
10411 fn should_show_indent_guides(&self) -> Option<bool> {
10412 self.show_indent_guides
10413 }
10414
10415 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10416 let mut editor_settings = EditorSettings::get_global(cx).clone();
10417 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10418 EditorSettings::override_global(editor_settings, cx);
10419 }
10420
10421 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10422 self.show_gutter = show_gutter;
10423 cx.notify();
10424 }
10425
10426 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10427 self.show_line_numbers = Some(show_line_numbers);
10428 cx.notify();
10429 }
10430
10431 pub fn set_show_git_diff_gutter(
10432 &mut self,
10433 show_git_diff_gutter: bool,
10434 cx: &mut ViewContext<Self>,
10435 ) {
10436 self.show_git_diff_gutter = Some(show_git_diff_gutter);
10437 cx.notify();
10438 }
10439
10440 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10441 self.show_code_actions = Some(show_code_actions);
10442 cx.notify();
10443 }
10444
10445 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10446 self.show_runnables = Some(show_runnables);
10447 cx.notify();
10448 }
10449
10450 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
10451 if self.display_map.read(cx).masked != masked {
10452 self.display_map.update(cx, |map, _| map.masked = masked);
10453 }
10454 cx.notify()
10455 }
10456
10457 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10458 self.show_wrap_guides = Some(show_wrap_guides);
10459 cx.notify();
10460 }
10461
10462 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10463 self.show_indent_guides = Some(show_indent_guides);
10464 cx.notify();
10465 }
10466
10467 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10468 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10469 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10470 if let Some(dir) = file.abs_path(cx).parent() {
10471 return Some(dir.to_owned());
10472 }
10473 }
10474
10475 if let Some(project_path) = buffer.read(cx).project_path(cx) {
10476 return Some(project_path.path.to_path_buf());
10477 }
10478 }
10479
10480 None
10481 }
10482
10483 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10484 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10485 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10486 cx.reveal_path(&file.abs_path(cx));
10487 }
10488 }
10489 }
10490
10491 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10492 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10493 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10494 if let Some(path) = file.abs_path(cx).to_str() {
10495 cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10496 }
10497 }
10498 }
10499 }
10500
10501 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10502 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10503 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10504 if let Some(path) = file.path().to_str() {
10505 cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10506 }
10507 }
10508 }
10509 }
10510
10511 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10512 self.show_git_blame_gutter = !self.show_git_blame_gutter;
10513
10514 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10515 self.start_git_blame(true, cx);
10516 }
10517
10518 cx.notify();
10519 }
10520
10521 pub fn toggle_git_blame_inline(
10522 &mut self,
10523 _: &ToggleGitBlameInline,
10524 cx: &mut ViewContext<Self>,
10525 ) {
10526 self.toggle_git_blame_inline_internal(true, cx);
10527 cx.notify();
10528 }
10529
10530 pub fn git_blame_inline_enabled(&self) -> bool {
10531 self.git_blame_inline_enabled
10532 }
10533
10534 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10535 self.show_selection_menu = self
10536 .show_selection_menu
10537 .map(|show_selections_menu| !show_selections_menu)
10538 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10539
10540 cx.notify();
10541 }
10542
10543 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10544 self.show_selection_menu
10545 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10546 }
10547
10548 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10549 if let Some(project) = self.project.as_ref() {
10550 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10551 return;
10552 };
10553
10554 if buffer.read(cx).file().is_none() {
10555 return;
10556 }
10557
10558 let focused = self.focus_handle(cx).contains_focused(cx);
10559
10560 let project = project.clone();
10561 let blame =
10562 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10563 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10564 self.blame = Some(blame);
10565 }
10566 }
10567
10568 fn toggle_git_blame_inline_internal(
10569 &mut self,
10570 user_triggered: bool,
10571 cx: &mut ViewContext<Self>,
10572 ) {
10573 if self.git_blame_inline_enabled {
10574 self.git_blame_inline_enabled = false;
10575 self.show_git_blame_inline = false;
10576 self.show_git_blame_inline_delay_task.take();
10577 } else {
10578 self.git_blame_inline_enabled = true;
10579 self.start_git_blame_inline(user_triggered, cx);
10580 }
10581
10582 cx.notify();
10583 }
10584
10585 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10586 self.start_git_blame(user_triggered, cx);
10587
10588 if ProjectSettings::get_global(cx)
10589 .git
10590 .inline_blame_delay()
10591 .is_some()
10592 {
10593 self.start_inline_blame_timer(cx);
10594 } else {
10595 self.show_git_blame_inline = true
10596 }
10597 }
10598
10599 pub fn blame(&self) -> Option<&Model<GitBlame>> {
10600 self.blame.as_ref()
10601 }
10602
10603 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10604 self.show_git_blame_gutter && self.has_blame_entries(cx)
10605 }
10606
10607 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10608 self.show_git_blame_inline
10609 && self.focus_handle.is_focused(cx)
10610 && !self.newest_selection_head_on_empty_line(cx)
10611 && self.has_blame_entries(cx)
10612 }
10613
10614 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10615 self.blame()
10616 .map_or(false, |blame| blame.read(cx).has_generated_entries())
10617 }
10618
10619 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10620 let cursor_anchor = self.selections.newest_anchor().head();
10621
10622 let snapshot = self.buffer.read(cx).snapshot(cx);
10623 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10624
10625 snapshot.line_len(buffer_row) == 0
10626 }
10627
10628 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10629 let (path, selection, repo) = maybe!({
10630 let project_handle = self.project.as_ref()?.clone();
10631 let project = project_handle.read(cx);
10632
10633 let selection = self.selections.newest::<Point>(cx);
10634 let selection_range = selection.range();
10635
10636 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10637 (buffer, selection_range.start.row..selection_range.end.row)
10638 } else {
10639 let buffer_ranges = self
10640 .buffer()
10641 .read(cx)
10642 .range_to_buffer_ranges(selection_range, cx);
10643
10644 let (buffer, range, _) = if selection.reversed {
10645 buffer_ranges.first()
10646 } else {
10647 buffer_ranges.last()
10648 }?;
10649
10650 let snapshot = buffer.read(cx).snapshot();
10651 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10652 ..text::ToPoint::to_point(&range.end, &snapshot).row;
10653 (buffer.clone(), selection)
10654 };
10655
10656 let path = buffer
10657 .read(cx)
10658 .file()?
10659 .as_local()?
10660 .path()
10661 .to_str()?
10662 .to_string();
10663 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10664 Some((path, selection, repo))
10665 })
10666 .ok_or_else(|| anyhow!("unable to open git repository"))?;
10667
10668 const REMOTE_NAME: &str = "origin";
10669 let origin_url = repo
10670 .remote_url(REMOTE_NAME)
10671 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10672 let sha = repo
10673 .head_sha()
10674 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10675
10676 let (provider, remote) =
10677 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10678 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10679
10680 Ok(provider.build_permalink(
10681 remote,
10682 BuildPermalinkParams {
10683 sha: &sha,
10684 path: &path,
10685 selection: Some(selection),
10686 },
10687 ))
10688 }
10689
10690 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10691 let permalink = self.get_permalink_to_line(cx);
10692
10693 match permalink {
10694 Ok(permalink) => {
10695 cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
10696 }
10697 Err(err) => {
10698 let message = format!("Failed to copy permalink: {err}");
10699
10700 Err::<(), anyhow::Error>(err).log_err();
10701
10702 if let Some(workspace) = self.workspace() {
10703 workspace.update(cx, |workspace, cx| {
10704 struct CopyPermalinkToLine;
10705
10706 workspace.show_toast(
10707 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10708 cx,
10709 )
10710 })
10711 }
10712 }
10713 }
10714 }
10715
10716 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10717 let permalink = self.get_permalink_to_line(cx);
10718
10719 match permalink {
10720 Ok(permalink) => {
10721 cx.open_url(permalink.as_ref());
10722 }
10723 Err(err) => {
10724 let message = format!("Failed to open permalink: {err}");
10725
10726 Err::<(), anyhow::Error>(err).log_err();
10727
10728 if let Some(workspace) = self.workspace() {
10729 workspace.update(cx, |workspace, cx| {
10730 struct OpenPermalinkToLine;
10731
10732 workspace.show_toast(
10733 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
10734 cx,
10735 )
10736 })
10737 }
10738 }
10739 }
10740 }
10741
10742 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
10743 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
10744 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
10745 pub fn highlight_rows<T: 'static>(
10746 &mut self,
10747 rows: RangeInclusive<Anchor>,
10748 color: Option<Hsla>,
10749 should_autoscroll: bool,
10750 cx: &mut ViewContext<Self>,
10751 ) {
10752 let snapshot = self.buffer().read(cx).snapshot(cx);
10753 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
10754 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
10755 highlight
10756 .range
10757 .start()
10758 .cmp(&rows.start(), &snapshot)
10759 .then(highlight.range.end().cmp(&rows.end(), &snapshot))
10760 });
10761 match (color, existing_highlight_index) {
10762 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
10763 ix,
10764 RowHighlight {
10765 index: post_inc(&mut self.highlight_order),
10766 range: rows,
10767 should_autoscroll,
10768 color,
10769 },
10770 ),
10771 (None, Ok(i)) => {
10772 row_highlights.remove(i);
10773 }
10774 }
10775 }
10776
10777 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
10778 pub fn clear_row_highlights<T: 'static>(&mut self) {
10779 self.highlighted_rows.remove(&TypeId::of::<T>());
10780 }
10781
10782 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
10783 pub fn highlighted_rows<T: 'static>(
10784 &self,
10785 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
10786 Some(
10787 self.highlighted_rows
10788 .get(&TypeId::of::<T>())?
10789 .iter()
10790 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
10791 )
10792 }
10793
10794 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
10795 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
10796 /// Allows to ignore certain kinds of highlights.
10797 pub fn highlighted_display_rows(
10798 &mut self,
10799 cx: &mut WindowContext,
10800 ) -> BTreeMap<DisplayRow, Hsla> {
10801 let snapshot = self.snapshot(cx);
10802 let mut used_highlight_orders = HashMap::default();
10803 self.highlighted_rows
10804 .iter()
10805 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
10806 .fold(
10807 BTreeMap::<DisplayRow, Hsla>::new(),
10808 |mut unique_rows, highlight| {
10809 let start_row = highlight.range.start().to_display_point(&snapshot).row();
10810 let end_row = highlight.range.end().to_display_point(&snapshot).row();
10811 for row in start_row.0..=end_row.0 {
10812 let used_index =
10813 used_highlight_orders.entry(row).or_insert(highlight.index);
10814 if highlight.index >= *used_index {
10815 *used_index = highlight.index;
10816 match highlight.color {
10817 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
10818 None => unique_rows.remove(&DisplayRow(row)),
10819 };
10820 }
10821 }
10822 unique_rows
10823 },
10824 )
10825 }
10826
10827 pub fn highlighted_display_row_for_autoscroll(
10828 &self,
10829 snapshot: &DisplaySnapshot,
10830 ) -> Option<DisplayRow> {
10831 self.highlighted_rows
10832 .values()
10833 .flat_map(|highlighted_rows| highlighted_rows.iter())
10834 .filter_map(|highlight| {
10835 if highlight.color.is_none() || !highlight.should_autoscroll {
10836 return None;
10837 }
10838 Some(highlight.range.start().to_display_point(&snapshot).row())
10839 })
10840 .min()
10841 }
10842
10843 pub fn set_search_within_ranges(
10844 &mut self,
10845 ranges: &[Range<Anchor>],
10846 cx: &mut ViewContext<Self>,
10847 ) {
10848 self.highlight_background::<SearchWithinRange>(
10849 ranges,
10850 |colors| colors.editor_document_highlight_read_background,
10851 cx,
10852 )
10853 }
10854
10855 pub fn set_breadcrumb_header(&mut self, new_header: String) {
10856 self.breadcrumb_header = Some(new_header);
10857 }
10858
10859 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
10860 self.clear_background_highlights::<SearchWithinRange>(cx);
10861 }
10862
10863 pub fn highlight_background<T: 'static>(
10864 &mut self,
10865 ranges: &[Range<Anchor>],
10866 color_fetcher: fn(&ThemeColors) -> Hsla,
10867 cx: &mut ViewContext<Self>,
10868 ) {
10869 self.background_highlights
10870 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10871 self.scrollbar_marker_state.dirty = true;
10872 cx.notify();
10873 }
10874
10875 pub fn clear_background_highlights<T: 'static>(
10876 &mut self,
10877 cx: &mut ViewContext<Self>,
10878 ) -> Option<BackgroundHighlight> {
10879 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
10880 if !text_highlights.1.is_empty() {
10881 self.scrollbar_marker_state.dirty = true;
10882 cx.notify();
10883 }
10884 Some(text_highlights)
10885 }
10886
10887 pub fn highlight_gutter<T: 'static>(
10888 &mut self,
10889 ranges: &[Range<Anchor>],
10890 color_fetcher: fn(&AppContext) -> Hsla,
10891 cx: &mut ViewContext<Self>,
10892 ) {
10893 self.gutter_highlights
10894 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10895 cx.notify();
10896 }
10897
10898 pub fn clear_gutter_highlights<T: 'static>(
10899 &mut self,
10900 cx: &mut ViewContext<Self>,
10901 ) -> Option<GutterHighlight> {
10902 cx.notify();
10903 self.gutter_highlights.remove(&TypeId::of::<T>())
10904 }
10905
10906 #[cfg(feature = "test-support")]
10907 pub fn all_text_background_highlights(
10908 &mut self,
10909 cx: &mut ViewContext<Self>,
10910 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10911 let snapshot = self.snapshot(cx);
10912 let buffer = &snapshot.buffer_snapshot;
10913 let start = buffer.anchor_before(0);
10914 let end = buffer.anchor_after(buffer.len());
10915 let theme = cx.theme().colors();
10916 self.background_highlights_in_range(start..end, &snapshot, theme)
10917 }
10918
10919 #[cfg(feature = "test-support")]
10920 pub fn search_background_highlights(
10921 &mut self,
10922 cx: &mut ViewContext<Self>,
10923 ) -> Vec<Range<Point>> {
10924 let snapshot = self.buffer().read(cx).snapshot(cx);
10925
10926 let highlights = self
10927 .background_highlights
10928 .get(&TypeId::of::<items::BufferSearchHighlights>());
10929
10930 if let Some((_color, ranges)) = highlights {
10931 ranges
10932 .iter()
10933 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
10934 .collect_vec()
10935 } else {
10936 vec![]
10937 }
10938 }
10939
10940 fn document_highlights_for_position<'a>(
10941 &'a self,
10942 position: Anchor,
10943 buffer: &'a MultiBufferSnapshot,
10944 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
10945 let read_highlights = self
10946 .background_highlights
10947 .get(&TypeId::of::<DocumentHighlightRead>())
10948 .map(|h| &h.1);
10949 let write_highlights = self
10950 .background_highlights
10951 .get(&TypeId::of::<DocumentHighlightWrite>())
10952 .map(|h| &h.1);
10953 let left_position = position.bias_left(buffer);
10954 let right_position = position.bias_right(buffer);
10955 read_highlights
10956 .into_iter()
10957 .chain(write_highlights)
10958 .flat_map(move |ranges| {
10959 let start_ix = match ranges.binary_search_by(|probe| {
10960 let cmp = probe.end.cmp(&left_position, buffer);
10961 if cmp.is_ge() {
10962 Ordering::Greater
10963 } else {
10964 Ordering::Less
10965 }
10966 }) {
10967 Ok(i) | Err(i) => i,
10968 };
10969
10970 ranges[start_ix..]
10971 .iter()
10972 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
10973 })
10974 }
10975
10976 pub fn has_background_highlights<T: 'static>(&self) -> bool {
10977 self.background_highlights
10978 .get(&TypeId::of::<T>())
10979 .map_or(false, |(_, highlights)| !highlights.is_empty())
10980 }
10981
10982 pub fn background_highlights_in_range(
10983 &self,
10984 search_range: Range<Anchor>,
10985 display_snapshot: &DisplaySnapshot,
10986 theme: &ThemeColors,
10987 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10988 let mut results = Vec::new();
10989 for (color_fetcher, ranges) in self.background_highlights.values() {
10990 let color = color_fetcher(theme);
10991 let start_ix = match ranges.binary_search_by(|probe| {
10992 let cmp = probe
10993 .end
10994 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10995 if cmp.is_gt() {
10996 Ordering::Greater
10997 } else {
10998 Ordering::Less
10999 }
11000 }) {
11001 Ok(i) | Err(i) => i,
11002 };
11003 for range in &ranges[start_ix..] {
11004 if range
11005 .start
11006 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11007 .is_ge()
11008 {
11009 break;
11010 }
11011
11012 let start = range.start.to_display_point(&display_snapshot);
11013 let end = range.end.to_display_point(&display_snapshot);
11014 results.push((start..end, color))
11015 }
11016 }
11017 results
11018 }
11019
11020 pub fn background_highlight_row_ranges<T: 'static>(
11021 &self,
11022 search_range: Range<Anchor>,
11023 display_snapshot: &DisplaySnapshot,
11024 count: usize,
11025 ) -> Vec<RangeInclusive<DisplayPoint>> {
11026 let mut results = Vec::new();
11027 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11028 return vec![];
11029 };
11030
11031 let start_ix = match ranges.binary_search_by(|probe| {
11032 let cmp = probe
11033 .end
11034 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11035 if cmp.is_gt() {
11036 Ordering::Greater
11037 } else {
11038 Ordering::Less
11039 }
11040 }) {
11041 Ok(i) | Err(i) => i,
11042 };
11043 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11044 if let (Some(start_display), Some(end_display)) = (start, end) {
11045 results.push(
11046 start_display.to_display_point(display_snapshot)
11047 ..=end_display.to_display_point(display_snapshot),
11048 );
11049 }
11050 };
11051 let mut start_row: Option<Point> = None;
11052 let mut end_row: Option<Point> = None;
11053 if ranges.len() > count {
11054 return Vec::new();
11055 }
11056 for range in &ranges[start_ix..] {
11057 if range
11058 .start
11059 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11060 .is_ge()
11061 {
11062 break;
11063 }
11064 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11065 if let Some(current_row) = &end_row {
11066 if end.row == current_row.row {
11067 continue;
11068 }
11069 }
11070 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11071 if start_row.is_none() {
11072 assert_eq!(end_row, None);
11073 start_row = Some(start);
11074 end_row = Some(end);
11075 continue;
11076 }
11077 if let Some(current_end) = end_row.as_mut() {
11078 if start.row > current_end.row + 1 {
11079 push_region(start_row, end_row);
11080 start_row = Some(start);
11081 end_row = Some(end);
11082 } else {
11083 // Merge two hunks.
11084 *current_end = end;
11085 }
11086 } else {
11087 unreachable!();
11088 }
11089 }
11090 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11091 push_region(start_row, end_row);
11092 results
11093 }
11094
11095 pub fn gutter_highlights_in_range(
11096 &self,
11097 search_range: Range<Anchor>,
11098 display_snapshot: &DisplaySnapshot,
11099 cx: &AppContext,
11100 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11101 let mut results = Vec::new();
11102 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11103 let color = color_fetcher(cx);
11104 let start_ix = match ranges.binary_search_by(|probe| {
11105 let cmp = probe
11106 .end
11107 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11108 if cmp.is_gt() {
11109 Ordering::Greater
11110 } else {
11111 Ordering::Less
11112 }
11113 }) {
11114 Ok(i) | Err(i) => i,
11115 };
11116 for range in &ranges[start_ix..] {
11117 if range
11118 .start
11119 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11120 .is_ge()
11121 {
11122 break;
11123 }
11124
11125 let start = range.start.to_display_point(&display_snapshot);
11126 let end = range.end.to_display_point(&display_snapshot);
11127 results.push((start..end, color))
11128 }
11129 }
11130 results
11131 }
11132
11133 /// Get the text ranges corresponding to the redaction query
11134 pub fn redacted_ranges(
11135 &self,
11136 search_range: Range<Anchor>,
11137 display_snapshot: &DisplaySnapshot,
11138 cx: &WindowContext,
11139 ) -> Vec<Range<DisplayPoint>> {
11140 display_snapshot
11141 .buffer_snapshot
11142 .redacted_ranges(search_range, |file| {
11143 if let Some(file) = file {
11144 file.is_private()
11145 && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
11146 } else {
11147 false
11148 }
11149 })
11150 .map(|range| {
11151 range.start.to_display_point(display_snapshot)
11152 ..range.end.to_display_point(display_snapshot)
11153 })
11154 .collect()
11155 }
11156
11157 pub fn highlight_text<T: 'static>(
11158 &mut self,
11159 ranges: Vec<Range<Anchor>>,
11160 style: HighlightStyle,
11161 cx: &mut ViewContext<Self>,
11162 ) {
11163 self.display_map.update(cx, |map, _| {
11164 map.highlight_text(TypeId::of::<T>(), ranges, style)
11165 });
11166 cx.notify();
11167 }
11168
11169 pub(crate) fn highlight_inlays<T: 'static>(
11170 &mut self,
11171 highlights: Vec<InlayHighlight>,
11172 style: HighlightStyle,
11173 cx: &mut ViewContext<Self>,
11174 ) {
11175 self.display_map.update(cx, |map, _| {
11176 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11177 });
11178 cx.notify();
11179 }
11180
11181 pub fn text_highlights<'a, T: 'static>(
11182 &'a self,
11183 cx: &'a AppContext,
11184 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11185 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11186 }
11187
11188 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11189 let cleared = self
11190 .display_map
11191 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11192 if cleared {
11193 cx.notify();
11194 }
11195 }
11196
11197 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11198 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11199 && self.focus_handle.is_focused(cx)
11200 }
11201
11202 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11203 self.show_cursor_when_unfocused = is_enabled;
11204 cx.notify();
11205 }
11206
11207 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11208 cx.notify();
11209 }
11210
11211 fn on_buffer_event(
11212 &mut self,
11213 multibuffer: Model<MultiBuffer>,
11214 event: &multi_buffer::Event,
11215 cx: &mut ViewContext<Self>,
11216 ) {
11217 match event {
11218 multi_buffer::Event::Edited {
11219 singleton_buffer_edited,
11220 } => {
11221 self.scrollbar_marker_state.dirty = true;
11222 self.active_indent_guides_state.dirty = true;
11223 self.refresh_active_diagnostics(cx);
11224 self.refresh_code_actions(cx);
11225 if self.has_active_inline_completion(cx) {
11226 self.update_visible_inline_completion(cx);
11227 }
11228 cx.emit(EditorEvent::BufferEdited);
11229 cx.emit(SearchEvent::MatchesInvalidated);
11230 if *singleton_buffer_edited {
11231 if let Some(project) = &self.project {
11232 let project = project.read(cx);
11233 #[allow(clippy::mutable_key_type)]
11234 let languages_affected = multibuffer
11235 .read(cx)
11236 .all_buffers()
11237 .into_iter()
11238 .filter_map(|buffer| {
11239 let buffer = buffer.read(cx);
11240 let language = buffer.language()?;
11241 if project.is_local()
11242 && project.language_servers_for_buffer(buffer, cx).count() == 0
11243 {
11244 None
11245 } else {
11246 Some(language)
11247 }
11248 })
11249 .cloned()
11250 .collect::<HashSet<_>>();
11251 if !languages_affected.is_empty() {
11252 self.refresh_inlay_hints(
11253 InlayHintRefreshReason::BufferEdited(languages_affected),
11254 cx,
11255 );
11256 }
11257 }
11258 }
11259
11260 let Some(project) = &self.project else { return };
11261 let telemetry = project.read(cx).client().telemetry().clone();
11262 refresh_linked_ranges(self, cx);
11263 telemetry.log_edit_event("editor");
11264 }
11265 multi_buffer::Event::ExcerptsAdded {
11266 buffer,
11267 predecessor,
11268 excerpts,
11269 } => {
11270 self.tasks_update_task = Some(self.refresh_runnables(cx));
11271 cx.emit(EditorEvent::ExcerptsAdded {
11272 buffer: buffer.clone(),
11273 predecessor: *predecessor,
11274 excerpts: excerpts.clone(),
11275 });
11276 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11277 }
11278 multi_buffer::Event::ExcerptsRemoved { ids } => {
11279 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11280 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11281 }
11282 multi_buffer::Event::ExcerptsEdited { ids } => {
11283 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11284 }
11285 multi_buffer::Event::ExcerptsExpanded { ids } => {
11286 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11287 }
11288 multi_buffer::Event::Reparsed(buffer_id) => {
11289 self.tasks_update_task = Some(self.refresh_runnables(cx));
11290
11291 cx.emit(EditorEvent::Reparsed(*buffer_id));
11292 }
11293 multi_buffer::Event::LanguageChanged(buffer_id) => {
11294 linked_editing_ranges::refresh_linked_ranges(self, cx);
11295 cx.emit(EditorEvent::Reparsed(*buffer_id));
11296 cx.notify();
11297 }
11298 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11299 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11300 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11301 cx.emit(EditorEvent::TitleChanged)
11302 }
11303 multi_buffer::Event::DiffBaseChanged => {
11304 self.scrollbar_marker_state.dirty = true;
11305 cx.emit(EditorEvent::DiffBaseChanged);
11306 cx.notify();
11307 }
11308 multi_buffer::Event::DiffUpdated { buffer } => {
11309 self.sync_expanded_diff_hunks(buffer.clone(), cx);
11310 cx.notify();
11311 }
11312 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11313 multi_buffer::Event::DiagnosticsUpdated => {
11314 self.refresh_active_diagnostics(cx);
11315 self.scrollbar_marker_state.dirty = true;
11316 cx.notify();
11317 }
11318 _ => {}
11319 };
11320 }
11321
11322 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11323 cx.notify();
11324 }
11325
11326 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11327 self.tasks_update_task = Some(self.refresh_runnables(cx));
11328 self.refresh_inline_completion(true, cx);
11329 self.refresh_inlay_hints(
11330 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11331 self.selections.newest_anchor().head(),
11332 &self.buffer.read(cx).snapshot(cx),
11333 cx,
11334 )),
11335 cx,
11336 );
11337 let editor_settings = EditorSettings::get_global(cx);
11338 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11339 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11340
11341 let project_settings = ProjectSettings::get_global(cx);
11342 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11343
11344 if self.mode == EditorMode::Full {
11345 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11346 if self.git_blame_inline_enabled != inline_blame_enabled {
11347 self.toggle_git_blame_inline_internal(false, cx);
11348 }
11349 }
11350
11351 cx.notify();
11352 }
11353
11354 pub fn set_searchable(&mut self, searchable: bool) {
11355 self.searchable = searchable;
11356 }
11357
11358 pub fn searchable(&self) -> bool {
11359 self.searchable
11360 }
11361
11362 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11363 self.open_excerpts_common(true, cx)
11364 }
11365
11366 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11367 self.open_excerpts_common(false, cx)
11368 }
11369
11370 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11371 let buffer = self.buffer.read(cx);
11372 if buffer.is_singleton() {
11373 cx.propagate();
11374 return;
11375 }
11376
11377 let Some(workspace) = self.workspace() else {
11378 cx.propagate();
11379 return;
11380 };
11381
11382 let mut new_selections_by_buffer = HashMap::default();
11383 for selection in self.selections.all::<usize>(cx) {
11384 for (buffer, mut range, _) in
11385 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11386 {
11387 if selection.reversed {
11388 mem::swap(&mut range.start, &mut range.end);
11389 }
11390 new_selections_by_buffer
11391 .entry(buffer)
11392 .or_insert(Vec::new())
11393 .push(range)
11394 }
11395 }
11396
11397 // We defer the pane interaction because we ourselves are a workspace item
11398 // and activating a new item causes the pane to call a method on us reentrantly,
11399 // which panics if we're on the stack.
11400 cx.window_context().defer(move |cx| {
11401 workspace.update(cx, |workspace, cx| {
11402 let pane = if split {
11403 workspace.adjacent_pane(cx)
11404 } else {
11405 workspace.active_pane().clone()
11406 };
11407
11408 for (buffer, ranges) in new_selections_by_buffer {
11409 let editor =
11410 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
11411 editor.update(cx, |editor, cx| {
11412 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11413 s.select_ranges(ranges);
11414 });
11415 });
11416 }
11417 })
11418 });
11419 }
11420
11421 fn jump(
11422 &mut self,
11423 path: ProjectPath,
11424 position: Point,
11425 anchor: language::Anchor,
11426 offset_from_top: u32,
11427 cx: &mut ViewContext<Self>,
11428 ) {
11429 let workspace = self.workspace();
11430 cx.spawn(|_, mut cx| async move {
11431 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11432 let editor = workspace.update(&mut cx, |workspace, cx| {
11433 // Reset the preview item id before opening the new item
11434 workspace.active_pane().update(cx, |pane, cx| {
11435 pane.set_preview_item_id(None, cx);
11436 });
11437 workspace.open_path_preview(path, None, true, true, cx)
11438 })?;
11439 let editor = editor
11440 .await?
11441 .downcast::<Editor>()
11442 .ok_or_else(|| anyhow!("opened item was not an editor"))?
11443 .downgrade();
11444 editor.update(&mut cx, |editor, cx| {
11445 let buffer = editor
11446 .buffer()
11447 .read(cx)
11448 .as_singleton()
11449 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11450 let buffer = buffer.read(cx);
11451 let cursor = if buffer.can_resolve(&anchor) {
11452 language::ToPoint::to_point(&anchor, buffer)
11453 } else {
11454 buffer.clip_point(position, Bias::Left)
11455 };
11456
11457 let nav_history = editor.nav_history.take();
11458 editor.change_selections(
11459 Some(Autoscroll::top_relative(offset_from_top as usize)),
11460 cx,
11461 |s| {
11462 s.select_ranges([cursor..cursor]);
11463 },
11464 );
11465 editor.nav_history = nav_history;
11466
11467 anyhow::Ok(())
11468 })??;
11469
11470 anyhow::Ok(())
11471 })
11472 .detach_and_log_err(cx);
11473 }
11474
11475 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11476 let snapshot = self.buffer.read(cx).read(cx);
11477 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11478 Some(
11479 ranges
11480 .iter()
11481 .map(move |range| {
11482 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11483 })
11484 .collect(),
11485 )
11486 }
11487
11488 fn selection_replacement_ranges(
11489 &self,
11490 range: Range<OffsetUtf16>,
11491 cx: &AppContext,
11492 ) -> Vec<Range<OffsetUtf16>> {
11493 let selections = self.selections.all::<OffsetUtf16>(cx);
11494 let newest_selection = selections
11495 .iter()
11496 .max_by_key(|selection| selection.id)
11497 .unwrap();
11498 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11499 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11500 let snapshot = self.buffer.read(cx).read(cx);
11501 selections
11502 .into_iter()
11503 .map(|mut selection| {
11504 selection.start.0 =
11505 (selection.start.0 as isize).saturating_add(start_delta) as usize;
11506 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11507 snapshot.clip_offset_utf16(selection.start, Bias::Left)
11508 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11509 })
11510 .collect()
11511 }
11512
11513 fn report_editor_event(
11514 &self,
11515 operation: &'static str,
11516 file_extension: Option<String>,
11517 cx: &AppContext,
11518 ) {
11519 if cfg!(any(test, feature = "test-support")) {
11520 return;
11521 }
11522
11523 let Some(project) = &self.project else { return };
11524
11525 // If None, we are in a file without an extension
11526 let file = self
11527 .buffer
11528 .read(cx)
11529 .as_singleton()
11530 .and_then(|b| b.read(cx).file());
11531 let file_extension = file_extension.or(file
11532 .as_ref()
11533 .and_then(|file| Path::new(file.file_name(cx)).extension())
11534 .and_then(|e| e.to_str())
11535 .map(|a| a.to_string()));
11536
11537 let vim_mode = cx
11538 .global::<SettingsStore>()
11539 .raw_user_settings()
11540 .get("vim_mode")
11541 == Some(&serde_json::Value::Bool(true));
11542
11543 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11544 == language::language_settings::InlineCompletionProvider::Copilot;
11545 let copilot_enabled_for_language = self
11546 .buffer
11547 .read(cx)
11548 .settings_at(0, cx)
11549 .show_inline_completions;
11550
11551 let telemetry = project.read(cx).client().telemetry().clone();
11552 telemetry.report_editor_event(
11553 file_extension,
11554 vim_mode,
11555 operation,
11556 copilot_enabled,
11557 copilot_enabled_for_language,
11558 )
11559 }
11560
11561 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11562 /// with each line being an array of {text, highlight} objects.
11563 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11564 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11565 return;
11566 };
11567
11568 #[derive(Serialize)]
11569 struct Chunk<'a> {
11570 text: String,
11571 highlight: Option<&'a str>,
11572 }
11573
11574 let snapshot = buffer.read(cx).snapshot();
11575 let range = self
11576 .selected_text_range(cx)
11577 .and_then(|selected_range| {
11578 if selected_range.is_empty() {
11579 None
11580 } else {
11581 Some(selected_range)
11582 }
11583 })
11584 .unwrap_or_else(|| 0..snapshot.len());
11585
11586 let chunks = snapshot.chunks(range, true);
11587 let mut lines = Vec::new();
11588 let mut line: VecDeque<Chunk> = VecDeque::new();
11589
11590 let Some(style) = self.style.as_ref() else {
11591 return;
11592 };
11593
11594 for chunk in chunks {
11595 let highlight = chunk
11596 .syntax_highlight_id
11597 .and_then(|id| id.name(&style.syntax));
11598 let mut chunk_lines = chunk.text.split('\n').peekable();
11599 while let Some(text) = chunk_lines.next() {
11600 let mut merged_with_last_token = false;
11601 if let Some(last_token) = line.back_mut() {
11602 if last_token.highlight == highlight {
11603 last_token.text.push_str(text);
11604 merged_with_last_token = true;
11605 }
11606 }
11607
11608 if !merged_with_last_token {
11609 line.push_back(Chunk {
11610 text: text.into(),
11611 highlight,
11612 });
11613 }
11614
11615 if chunk_lines.peek().is_some() {
11616 if line.len() > 1 && line.front().unwrap().text.is_empty() {
11617 line.pop_front();
11618 }
11619 if line.len() > 1 && line.back().unwrap().text.is_empty() {
11620 line.pop_back();
11621 }
11622
11623 lines.push(mem::take(&mut line));
11624 }
11625 }
11626 }
11627
11628 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11629 return;
11630 };
11631 cx.write_to_clipboard(ClipboardItem::new(lines));
11632 }
11633
11634 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11635 &self.inlay_hint_cache
11636 }
11637
11638 pub fn replay_insert_event(
11639 &mut self,
11640 text: &str,
11641 relative_utf16_range: Option<Range<isize>>,
11642 cx: &mut ViewContext<Self>,
11643 ) {
11644 if !self.input_enabled {
11645 cx.emit(EditorEvent::InputIgnored { text: text.into() });
11646 return;
11647 }
11648 if let Some(relative_utf16_range) = relative_utf16_range {
11649 let selections = self.selections.all::<OffsetUtf16>(cx);
11650 self.change_selections(None, cx, |s| {
11651 let new_ranges = selections.into_iter().map(|range| {
11652 let start = OffsetUtf16(
11653 range
11654 .head()
11655 .0
11656 .saturating_add_signed(relative_utf16_range.start),
11657 );
11658 let end = OffsetUtf16(
11659 range
11660 .head()
11661 .0
11662 .saturating_add_signed(relative_utf16_range.end),
11663 );
11664 start..end
11665 });
11666 s.select_ranges(new_ranges);
11667 });
11668 }
11669
11670 self.handle_input(text, cx);
11671 }
11672
11673 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11674 let Some(project) = self.project.as_ref() else {
11675 return false;
11676 };
11677 let project = project.read(cx);
11678
11679 let mut supports = false;
11680 self.buffer().read(cx).for_each_buffer(|buffer| {
11681 if !supports {
11682 supports = project
11683 .language_servers_for_buffer(buffer.read(cx), cx)
11684 .any(
11685 |(_, server)| match server.capabilities().inlay_hint_provider {
11686 Some(lsp::OneOf::Left(enabled)) => enabled,
11687 Some(lsp::OneOf::Right(_)) => true,
11688 None => false,
11689 },
11690 )
11691 }
11692 });
11693 supports
11694 }
11695
11696 pub fn focus(&self, cx: &mut WindowContext) {
11697 cx.focus(&self.focus_handle)
11698 }
11699
11700 pub fn is_focused(&self, cx: &WindowContext) -> bool {
11701 self.focus_handle.is_focused(cx)
11702 }
11703
11704 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11705 cx.emit(EditorEvent::Focused);
11706
11707 if let Some(descendant) = self
11708 .last_focused_descendant
11709 .take()
11710 .and_then(|descendant| descendant.upgrade())
11711 {
11712 cx.focus(&descendant);
11713 } else {
11714 if let Some(blame) = self.blame.as_ref() {
11715 blame.update(cx, GitBlame::focus)
11716 }
11717
11718 self.blink_manager.update(cx, BlinkManager::enable);
11719 self.show_cursor_names(cx);
11720 self.buffer.update(cx, |buffer, cx| {
11721 buffer.finalize_last_transaction(cx);
11722 if self.leader_peer_id.is_none() {
11723 buffer.set_active_selections(
11724 &self.selections.disjoint_anchors(),
11725 self.selections.line_mode,
11726 self.cursor_shape,
11727 cx,
11728 );
11729 }
11730 });
11731 }
11732 }
11733
11734 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
11735 cx.emit(EditorEvent::FocusedIn)
11736 }
11737
11738 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
11739 if event.blurred != self.focus_handle {
11740 self.last_focused_descendant = Some(event.blurred);
11741 }
11742 }
11743
11744 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
11745 self.blink_manager.update(cx, BlinkManager::disable);
11746 self.buffer
11747 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
11748
11749 if let Some(blame) = self.blame.as_ref() {
11750 blame.update(cx, GitBlame::blur)
11751 }
11752 if !self.hover_state.focused(cx) {
11753 hide_hover(self, cx);
11754 }
11755
11756 self.hide_context_menu(cx);
11757 cx.emit(EditorEvent::Blurred);
11758 cx.notify();
11759 }
11760
11761 pub fn register_action<A: Action>(
11762 &mut self,
11763 listener: impl Fn(&A, &mut WindowContext) + 'static,
11764 ) -> Subscription {
11765 let id = self.next_editor_action_id.post_inc();
11766 let listener = Arc::new(listener);
11767 self.editor_actions.borrow_mut().insert(
11768 id,
11769 Box::new(move |cx| {
11770 let _view = cx.view().clone();
11771 let cx = cx.window_context();
11772 let listener = listener.clone();
11773 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
11774 let action = action.downcast_ref().unwrap();
11775 if phase == DispatchPhase::Bubble {
11776 listener(action, cx)
11777 }
11778 })
11779 }),
11780 );
11781
11782 let editor_actions = self.editor_actions.clone();
11783 Subscription::new(move || {
11784 editor_actions.borrow_mut().remove(&id);
11785 })
11786 }
11787
11788 pub fn file_header_size(&self) -> u32 {
11789 self.file_header_size
11790 }
11791
11792 pub fn revert(
11793 &mut self,
11794 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
11795 cx: &mut ViewContext<Self>,
11796 ) {
11797 self.buffer().update(cx, |multi_buffer, cx| {
11798 for (buffer_id, changes) in revert_changes {
11799 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
11800 buffer.update(cx, |buffer, cx| {
11801 buffer.edit(
11802 changes.into_iter().map(|(range, text)| {
11803 (range, text.to_string().map(Arc::<str>::from))
11804 }),
11805 None,
11806 cx,
11807 );
11808 });
11809 }
11810 }
11811 });
11812 self.change_selections(None, cx, |selections| selections.refresh());
11813 }
11814
11815 pub fn to_pixel_point(
11816 &mut self,
11817 source: multi_buffer::Anchor,
11818 editor_snapshot: &EditorSnapshot,
11819 cx: &mut ViewContext<Self>,
11820 ) -> Option<gpui::Point<Pixels>> {
11821 let source_point = source.to_display_point(editor_snapshot);
11822 self.display_to_pixel_point(source_point, editor_snapshot, cx)
11823 }
11824
11825 pub fn display_to_pixel_point(
11826 &mut self,
11827 source: DisplayPoint,
11828 editor_snapshot: &EditorSnapshot,
11829 cx: &mut ViewContext<Self>,
11830 ) -> Option<gpui::Point<Pixels>> {
11831 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
11832 let text_layout_details = self.text_layout_details(cx);
11833 let scroll_top = text_layout_details
11834 .scroll_anchor
11835 .scroll_position(editor_snapshot)
11836 .y;
11837
11838 if source.row().as_f32() < scroll_top.floor() {
11839 return None;
11840 }
11841 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
11842 let source_y = line_height * (source.row().as_f32() - scroll_top);
11843 Some(gpui::Point::new(source_x, source_y))
11844 }
11845
11846 fn gutter_bounds(&self) -> Option<Bounds<Pixels>> {
11847 let bounds = self.last_bounds?;
11848 Some(element::gutter_bounds(bounds, self.gutter_dimensions))
11849 }
11850}
11851
11852fn hunks_for_selections(
11853 multi_buffer_snapshot: &MultiBufferSnapshot,
11854 selections: &[Selection<Anchor>],
11855) -> Vec<DiffHunk<MultiBufferRow>> {
11856 let buffer_rows_for_selections = selections.iter().map(|selection| {
11857 let head = selection.head();
11858 let tail = selection.tail();
11859 let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
11860 let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
11861 if start > end {
11862 end..start
11863 } else {
11864 start..end
11865 }
11866 });
11867
11868 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
11869}
11870
11871pub fn hunks_for_rows(
11872 rows: impl Iterator<Item = Range<MultiBufferRow>>,
11873 multi_buffer_snapshot: &MultiBufferSnapshot,
11874) -> Vec<DiffHunk<MultiBufferRow>> {
11875 let mut hunks = Vec::new();
11876 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
11877 HashMap::default();
11878 for selected_multi_buffer_rows in rows {
11879 let query_rows =
11880 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
11881 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
11882 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
11883 // when the caret is just above or just below the deleted hunk.
11884 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
11885 let related_to_selection = if allow_adjacent {
11886 hunk.associated_range.overlaps(&query_rows)
11887 || hunk.associated_range.start == query_rows.end
11888 || hunk.associated_range.end == query_rows.start
11889 } else {
11890 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
11891 // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
11892 hunk.associated_range.overlaps(&selected_multi_buffer_rows)
11893 || selected_multi_buffer_rows.end == hunk.associated_range.start
11894 };
11895 if related_to_selection {
11896 if !processed_buffer_rows
11897 .entry(hunk.buffer_id)
11898 .or_default()
11899 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
11900 {
11901 continue;
11902 }
11903 hunks.push(hunk);
11904 }
11905 }
11906 }
11907
11908 hunks
11909}
11910
11911pub trait CollaborationHub {
11912 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
11913 fn user_participant_indices<'a>(
11914 &self,
11915 cx: &'a AppContext,
11916 ) -> &'a HashMap<u64, ParticipantIndex>;
11917 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
11918}
11919
11920impl CollaborationHub for Model<Project> {
11921 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
11922 self.read(cx).collaborators()
11923 }
11924
11925 fn user_participant_indices<'a>(
11926 &self,
11927 cx: &'a AppContext,
11928 ) -> &'a HashMap<u64, ParticipantIndex> {
11929 self.read(cx).user_store().read(cx).participant_indices()
11930 }
11931
11932 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
11933 let this = self.read(cx);
11934 let user_ids = this.collaborators().values().map(|c| c.user_id);
11935 this.user_store().read_with(cx, |user_store, cx| {
11936 user_store.participant_names(user_ids, cx)
11937 })
11938 }
11939}
11940
11941pub trait CompletionProvider {
11942 fn completions(
11943 &self,
11944 buffer: &Model<Buffer>,
11945 buffer_position: text::Anchor,
11946 trigger: CompletionContext,
11947 cx: &mut ViewContext<Editor>,
11948 ) -> Task<Result<Vec<Completion>>>;
11949
11950 fn resolve_completions(
11951 &self,
11952 buffer: Model<Buffer>,
11953 completion_indices: Vec<usize>,
11954 completions: Arc<RwLock<Box<[Completion]>>>,
11955 cx: &mut ViewContext<Editor>,
11956 ) -> Task<Result<bool>>;
11957
11958 fn apply_additional_edits_for_completion(
11959 &self,
11960 buffer: Model<Buffer>,
11961 completion: Completion,
11962 push_to_history: bool,
11963 cx: &mut ViewContext<Editor>,
11964 ) -> Task<Result<Option<language::Transaction>>>;
11965
11966 fn is_completion_trigger(
11967 &self,
11968 buffer: &Model<Buffer>,
11969 position: language::Anchor,
11970 text: &str,
11971 trigger_in_words: bool,
11972 cx: &mut ViewContext<Editor>,
11973 ) -> bool;
11974}
11975
11976fn snippet_completions(
11977 project: &Project,
11978 buffer: &Model<Buffer>,
11979 buffer_position: text::Anchor,
11980 cx: &mut AppContext,
11981) -> Vec<Completion> {
11982 let language = buffer.read(cx).language_at(buffer_position);
11983 let language_name = language.as_ref().map(|language| language.lsp_id());
11984 let snippet_store = project.snippets().read(cx);
11985 let snippets = snippet_store.snippets_for(language_name, cx);
11986
11987 if snippets.is_empty() {
11988 return vec![];
11989 }
11990 let snapshot = buffer.read(cx).text_snapshot();
11991 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
11992
11993 let mut lines = chunks.lines();
11994 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
11995 return vec![];
11996 };
11997
11998 let scope = language.map(|language| language.default_scope());
11999 let mut last_word = line_at
12000 .chars()
12001 .rev()
12002 .take_while(|c| char_kind(&scope, *c) == CharKind::Word)
12003 .collect::<String>();
12004 last_word = last_word.chars().rev().collect();
12005 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12006 let to_lsp = |point: &text::Anchor| {
12007 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12008 point_to_lsp(end)
12009 };
12010 let lsp_end = to_lsp(&buffer_position);
12011 snippets
12012 .into_iter()
12013 .filter_map(|snippet| {
12014 let matching_prefix = snippet
12015 .prefix
12016 .iter()
12017 .find(|prefix| prefix.starts_with(&last_word))?;
12018 let start = as_offset - last_word.len();
12019 let start = snapshot.anchor_before(start);
12020 let range = start..buffer_position;
12021 let lsp_start = to_lsp(&start);
12022 let lsp_range = lsp::Range {
12023 start: lsp_start,
12024 end: lsp_end,
12025 };
12026 Some(Completion {
12027 old_range: range,
12028 new_text: snippet.body.clone(),
12029 label: CodeLabel {
12030 text: matching_prefix.clone(),
12031 runs: vec![],
12032 filter_range: 0..matching_prefix.len(),
12033 },
12034 server_id: LanguageServerId(usize::MAX),
12035 documentation: snippet
12036 .description
12037 .clone()
12038 .map(|description| Documentation::SingleLine(description)),
12039 lsp_completion: lsp::CompletionItem {
12040 label: snippet.prefix.first().unwrap().clone(),
12041 kind: Some(CompletionItemKind::SNIPPET),
12042 label_details: snippet.description.as_ref().map(|description| {
12043 lsp::CompletionItemLabelDetails {
12044 detail: Some(description.clone()),
12045 description: None,
12046 }
12047 }),
12048 insert_text_format: Some(InsertTextFormat::SNIPPET),
12049 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12050 lsp::InsertReplaceEdit {
12051 new_text: snippet.body.clone(),
12052 insert: lsp_range,
12053 replace: lsp_range,
12054 },
12055 )),
12056 filter_text: Some(snippet.body.clone()),
12057 sort_text: Some(char::MAX.to_string()),
12058 ..Default::default()
12059 },
12060 confirm: None,
12061 show_new_completions_on_confirm: false,
12062 })
12063 })
12064 .collect()
12065}
12066
12067impl CompletionProvider for Model<Project> {
12068 fn completions(
12069 &self,
12070 buffer: &Model<Buffer>,
12071 buffer_position: text::Anchor,
12072 options: CompletionContext,
12073 cx: &mut ViewContext<Editor>,
12074 ) -> Task<Result<Vec<Completion>>> {
12075 self.update(cx, |project, cx| {
12076 let snippets = snippet_completions(project, buffer, buffer_position, cx);
12077 let project_completions = project.completions(&buffer, buffer_position, options, cx);
12078 cx.background_executor().spawn(async move {
12079 let mut completions = project_completions.await?;
12080 //let snippets = snippets.into_iter().;
12081 completions.extend(snippets);
12082 Ok(completions)
12083 })
12084 })
12085 }
12086
12087 fn resolve_completions(
12088 &self,
12089 buffer: Model<Buffer>,
12090 completion_indices: Vec<usize>,
12091 completions: Arc<RwLock<Box<[Completion]>>>,
12092 cx: &mut ViewContext<Editor>,
12093 ) -> Task<Result<bool>> {
12094 self.update(cx, |project, cx| {
12095 project.resolve_completions(buffer, completion_indices, completions, cx)
12096 })
12097 }
12098
12099 fn apply_additional_edits_for_completion(
12100 &self,
12101 buffer: Model<Buffer>,
12102 completion: Completion,
12103 push_to_history: bool,
12104 cx: &mut ViewContext<Editor>,
12105 ) -> Task<Result<Option<language::Transaction>>> {
12106 self.update(cx, |project, cx| {
12107 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12108 })
12109 }
12110
12111 fn is_completion_trigger(
12112 &self,
12113 buffer: &Model<Buffer>,
12114 position: language::Anchor,
12115 text: &str,
12116 trigger_in_words: bool,
12117 cx: &mut ViewContext<Editor>,
12118 ) -> bool {
12119 if !EditorSettings::get_global(cx).show_completions_on_input {
12120 return false;
12121 }
12122
12123 let mut chars = text.chars();
12124 let char = if let Some(char) = chars.next() {
12125 char
12126 } else {
12127 return false;
12128 };
12129 if chars.next().is_some() {
12130 return false;
12131 }
12132
12133 let buffer = buffer.read(cx);
12134 let scope = buffer.snapshot().language_scope_at(position);
12135 if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
12136 return true;
12137 }
12138
12139 buffer
12140 .completion_triggers()
12141 .iter()
12142 .any(|string| string == text)
12143 }
12144}
12145
12146fn inlay_hint_settings(
12147 location: Anchor,
12148 snapshot: &MultiBufferSnapshot,
12149 cx: &mut ViewContext<'_, Editor>,
12150) -> InlayHintSettings {
12151 let file = snapshot.file_at(location);
12152 let language = snapshot.language_at(location);
12153 let settings = all_language_settings(file, cx);
12154 settings
12155 .language(language.map(|l| l.name()).as_deref())
12156 .inlay_hints
12157}
12158
12159fn consume_contiguous_rows(
12160 contiguous_row_selections: &mut Vec<Selection<Point>>,
12161 selection: &Selection<Point>,
12162 display_map: &DisplaySnapshot,
12163 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12164) -> (MultiBufferRow, MultiBufferRow) {
12165 contiguous_row_selections.push(selection.clone());
12166 let start_row = MultiBufferRow(selection.start.row);
12167 let mut end_row = ending_row(selection, display_map);
12168
12169 while let Some(next_selection) = selections.peek() {
12170 if next_selection.start.row <= end_row.0 {
12171 end_row = ending_row(next_selection, display_map);
12172 contiguous_row_selections.push(selections.next().unwrap().clone());
12173 } else {
12174 break;
12175 }
12176 }
12177 (start_row, end_row)
12178}
12179
12180fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12181 if next_selection.end.column > 0 || next_selection.is_empty() {
12182 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12183 } else {
12184 MultiBufferRow(next_selection.end.row)
12185 }
12186}
12187
12188impl EditorSnapshot {
12189 pub fn remote_selections_in_range<'a>(
12190 &'a self,
12191 range: &'a Range<Anchor>,
12192 collaboration_hub: &dyn CollaborationHub,
12193 cx: &'a AppContext,
12194 ) -> impl 'a + Iterator<Item = RemoteSelection> {
12195 let participant_names = collaboration_hub.user_names(cx);
12196 let participant_indices = collaboration_hub.user_participant_indices(cx);
12197 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12198 let collaborators_by_replica_id = collaborators_by_peer_id
12199 .iter()
12200 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12201 .collect::<HashMap<_, _>>();
12202 self.buffer_snapshot
12203 .selections_in_range(range, false)
12204 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12205 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12206 let participant_index = participant_indices.get(&collaborator.user_id).copied();
12207 let user_name = participant_names.get(&collaborator.user_id).cloned();
12208 Some(RemoteSelection {
12209 replica_id,
12210 selection,
12211 cursor_shape,
12212 line_mode,
12213 participant_index,
12214 peer_id: collaborator.peer_id,
12215 user_name,
12216 })
12217 })
12218 }
12219
12220 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12221 self.display_snapshot.buffer_snapshot.language_at(position)
12222 }
12223
12224 pub fn is_focused(&self) -> bool {
12225 self.is_focused
12226 }
12227
12228 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12229 self.placeholder_text.as_ref()
12230 }
12231
12232 pub fn scroll_position(&self) -> gpui::Point<f32> {
12233 self.scroll_anchor.scroll_position(&self.display_snapshot)
12234 }
12235
12236 fn gutter_dimensions(
12237 &self,
12238 font_id: FontId,
12239 font_size: Pixels,
12240 em_width: Pixels,
12241 max_line_number_width: Pixels,
12242 cx: &AppContext,
12243 ) -> GutterDimensions {
12244 if !self.show_gutter {
12245 return GutterDimensions::default();
12246 }
12247 let descent = cx.text_system().descent(font_id, font_size);
12248
12249 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12250 matches!(
12251 ProjectSettings::get_global(cx).git.git_gutter,
12252 Some(GitGutterSetting::TrackedFiles)
12253 )
12254 });
12255 let gutter_settings = EditorSettings::get_global(cx).gutter;
12256 let show_line_numbers = self
12257 .show_line_numbers
12258 .unwrap_or(gutter_settings.line_numbers);
12259 let line_gutter_width = if show_line_numbers {
12260 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12261 let min_width_for_number_on_gutter = em_width * 4.0;
12262 max_line_number_width.max(min_width_for_number_on_gutter)
12263 } else {
12264 0.0.into()
12265 };
12266
12267 let show_code_actions = self
12268 .show_code_actions
12269 .unwrap_or(gutter_settings.code_actions);
12270
12271 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12272
12273 let git_blame_entries_width = self
12274 .render_git_blame_gutter
12275 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12276
12277 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12278 left_padding += if show_code_actions || show_runnables {
12279 em_width * 3.0
12280 } else if show_git_gutter && show_line_numbers {
12281 em_width * 2.0
12282 } else if show_git_gutter || show_line_numbers {
12283 em_width
12284 } else {
12285 px(0.)
12286 };
12287
12288 let right_padding = if gutter_settings.folds && show_line_numbers {
12289 em_width * 4.0
12290 } else if gutter_settings.folds {
12291 em_width * 3.0
12292 } else if show_line_numbers {
12293 em_width
12294 } else {
12295 px(0.)
12296 };
12297
12298 GutterDimensions {
12299 left_padding,
12300 right_padding,
12301 width: line_gutter_width + left_padding + right_padding,
12302 margin: -descent,
12303 git_blame_entries_width,
12304 }
12305 }
12306
12307 pub fn render_fold_toggle(
12308 &self,
12309 buffer_row: MultiBufferRow,
12310 row_contains_cursor: bool,
12311 editor: View<Editor>,
12312 cx: &mut WindowContext,
12313 ) -> Option<AnyElement> {
12314 let folded = self.is_line_folded(buffer_row);
12315
12316 if let Some(crease) = self
12317 .crease_snapshot
12318 .query_row(buffer_row, &self.buffer_snapshot)
12319 {
12320 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12321 if folded {
12322 editor.update(cx, |editor, cx| {
12323 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12324 });
12325 } else {
12326 editor.update(cx, |editor, cx| {
12327 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12328 });
12329 }
12330 });
12331
12332 Some((crease.render_toggle)(
12333 buffer_row,
12334 folded,
12335 toggle_callback,
12336 cx,
12337 ))
12338 } else if folded
12339 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12340 {
12341 Some(
12342 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12343 .selected(folded)
12344 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12345 if folded {
12346 this.unfold_at(&UnfoldAt { buffer_row }, cx);
12347 } else {
12348 this.fold_at(&FoldAt { buffer_row }, cx);
12349 }
12350 }))
12351 .into_any_element(),
12352 )
12353 } else {
12354 None
12355 }
12356 }
12357
12358 pub fn render_crease_trailer(
12359 &self,
12360 buffer_row: MultiBufferRow,
12361 cx: &mut WindowContext,
12362 ) -> Option<AnyElement> {
12363 let folded = self.is_line_folded(buffer_row);
12364 let crease = self
12365 .crease_snapshot
12366 .query_row(buffer_row, &self.buffer_snapshot)?;
12367 Some((crease.render_trailer)(buffer_row, folded, cx))
12368 }
12369}
12370
12371impl Deref for EditorSnapshot {
12372 type Target = DisplaySnapshot;
12373
12374 fn deref(&self) -> &Self::Target {
12375 &self.display_snapshot
12376 }
12377}
12378
12379#[derive(Clone, Debug, PartialEq, Eq)]
12380pub enum EditorEvent {
12381 InputIgnored {
12382 text: Arc<str>,
12383 },
12384 InputHandled {
12385 utf16_range_to_replace: Option<Range<isize>>,
12386 text: Arc<str>,
12387 },
12388 ExcerptsAdded {
12389 buffer: Model<Buffer>,
12390 predecessor: ExcerptId,
12391 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12392 },
12393 ExcerptsRemoved {
12394 ids: Vec<ExcerptId>,
12395 },
12396 ExcerptsEdited {
12397 ids: Vec<ExcerptId>,
12398 },
12399 ExcerptsExpanded {
12400 ids: Vec<ExcerptId>,
12401 },
12402 BufferEdited,
12403 Edited {
12404 transaction_id: clock::Lamport,
12405 },
12406 Reparsed(BufferId),
12407 Focused,
12408 FocusedIn,
12409 Blurred,
12410 DirtyChanged,
12411 Saved,
12412 TitleChanged,
12413 DiffBaseChanged,
12414 SelectionsChanged {
12415 local: bool,
12416 },
12417 ScrollPositionChanged {
12418 local: bool,
12419 autoscroll: bool,
12420 },
12421 Closed,
12422 TransactionUndone {
12423 transaction_id: clock::Lamport,
12424 },
12425 TransactionBegun {
12426 transaction_id: clock::Lamport,
12427 },
12428}
12429
12430impl EventEmitter<EditorEvent> for Editor {}
12431
12432impl FocusableView for Editor {
12433 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12434 self.focus_handle.clone()
12435 }
12436}
12437
12438impl Render for Editor {
12439 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12440 let settings = ThemeSettings::get_global(cx);
12441
12442 let text_style = match self.mode {
12443 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12444 color: cx.theme().colors().editor_foreground,
12445 font_family: settings.ui_font.family.clone(),
12446 font_features: settings.ui_font.features.clone(),
12447 font_fallbacks: settings.ui_font.fallbacks.clone(),
12448 font_size: rems(0.875).into(),
12449 font_weight: settings.ui_font.weight,
12450 line_height: relative(settings.buffer_line_height.value()),
12451 ..Default::default()
12452 },
12453 EditorMode::Full => TextStyle {
12454 color: cx.theme().colors().editor_foreground,
12455 font_family: settings.buffer_font.family.clone(),
12456 font_features: settings.buffer_font.features.clone(),
12457 font_fallbacks: settings.buffer_font.fallbacks.clone(),
12458 font_size: settings.buffer_font_size(cx).into(),
12459 font_weight: settings.buffer_font.weight,
12460 line_height: relative(settings.buffer_line_height.value()),
12461 ..Default::default()
12462 },
12463 };
12464
12465 let background = match self.mode {
12466 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12467 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12468 EditorMode::Full => cx.theme().colors().editor_background,
12469 };
12470
12471 EditorElement::new(
12472 cx.view(),
12473 EditorStyle {
12474 background,
12475 local_player: cx.theme().players().local(),
12476 text: text_style,
12477 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12478 syntax: cx.theme().syntax().clone(),
12479 status: cx.theme().status().clone(),
12480 inlay_hints_style: HighlightStyle {
12481 color: Some(cx.theme().status().hint),
12482 ..HighlightStyle::default()
12483 },
12484 suggestions_style: HighlightStyle {
12485 color: Some(cx.theme().status().predictive),
12486 ..HighlightStyle::default()
12487 },
12488 },
12489 )
12490 }
12491}
12492
12493impl ViewInputHandler for Editor {
12494 fn text_for_range(
12495 &mut self,
12496 range_utf16: Range<usize>,
12497 cx: &mut ViewContext<Self>,
12498 ) -> Option<String> {
12499 Some(
12500 self.buffer
12501 .read(cx)
12502 .read(cx)
12503 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12504 .collect(),
12505 )
12506 }
12507
12508 fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12509 // Prevent the IME menu from appearing when holding down an alphabetic key
12510 // while input is disabled.
12511 if !self.input_enabled {
12512 return None;
12513 }
12514
12515 let range = self.selections.newest::<OffsetUtf16>(cx).range();
12516 Some(range.start.0..range.end.0)
12517 }
12518
12519 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12520 let snapshot = self.buffer.read(cx).read(cx);
12521 let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
12522 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12523 }
12524
12525 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12526 self.clear_highlights::<InputComposition>(cx);
12527 self.ime_transaction.take();
12528 }
12529
12530 fn replace_text_in_range(
12531 &mut self,
12532 range_utf16: Option<Range<usize>>,
12533 text: &str,
12534 cx: &mut ViewContext<Self>,
12535 ) {
12536 if !self.input_enabled {
12537 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12538 return;
12539 }
12540
12541 self.transact(cx, |this, cx| {
12542 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12543 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12544 Some(this.selection_replacement_ranges(range_utf16, cx))
12545 } else {
12546 this.marked_text_ranges(cx)
12547 };
12548
12549 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12550 let newest_selection_id = this.selections.newest_anchor().id;
12551 this.selections
12552 .all::<OffsetUtf16>(cx)
12553 .iter()
12554 .zip(ranges_to_replace.iter())
12555 .find_map(|(selection, range)| {
12556 if selection.id == newest_selection_id {
12557 Some(
12558 (range.start.0 as isize - selection.head().0 as isize)
12559 ..(range.end.0 as isize - selection.head().0 as isize),
12560 )
12561 } else {
12562 None
12563 }
12564 })
12565 });
12566
12567 cx.emit(EditorEvent::InputHandled {
12568 utf16_range_to_replace: range_to_replace,
12569 text: text.into(),
12570 });
12571
12572 if let Some(new_selected_ranges) = new_selected_ranges {
12573 this.change_selections(None, cx, |selections| {
12574 selections.select_ranges(new_selected_ranges)
12575 });
12576 this.backspace(&Default::default(), cx);
12577 }
12578
12579 this.handle_input(text, cx);
12580 });
12581
12582 if let Some(transaction) = self.ime_transaction {
12583 self.buffer.update(cx, |buffer, cx| {
12584 buffer.group_until_transaction(transaction, cx);
12585 });
12586 }
12587
12588 self.unmark_text(cx);
12589 }
12590
12591 fn replace_and_mark_text_in_range(
12592 &mut self,
12593 range_utf16: Option<Range<usize>>,
12594 text: &str,
12595 new_selected_range_utf16: Option<Range<usize>>,
12596 cx: &mut ViewContext<Self>,
12597 ) {
12598 if !self.input_enabled {
12599 return;
12600 }
12601
12602 let transaction = self.transact(cx, |this, cx| {
12603 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12604 let snapshot = this.buffer.read(cx).read(cx);
12605 if let Some(relative_range_utf16) = range_utf16.as_ref() {
12606 for marked_range in &mut marked_ranges {
12607 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12608 marked_range.start.0 += relative_range_utf16.start;
12609 marked_range.start =
12610 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12611 marked_range.end =
12612 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12613 }
12614 }
12615 Some(marked_ranges)
12616 } else if let Some(range_utf16) = range_utf16 {
12617 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12618 Some(this.selection_replacement_ranges(range_utf16, cx))
12619 } else {
12620 None
12621 };
12622
12623 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12624 let newest_selection_id = this.selections.newest_anchor().id;
12625 this.selections
12626 .all::<OffsetUtf16>(cx)
12627 .iter()
12628 .zip(ranges_to_replace.iter())
12629 .find_map(|(selection, range)| {
12630 if selection.id == newest_selection_id {
12631 Some(
12632 (range.start.0 as isize - selection.head().0 as isize)
12633 ..(range.end.0 as isize - selection.head().0 as isize),
12634 )
12635 } else {
12636 None
12637 }
12638 })
12639 });
12640
12641 cx.emit(EditorEvent::InputHandled {
12642 utf16_range_to_replace: range_to_replace,
12643 text: text.into(),
12644 });
12645
12646 if let Some(ranges) = ranges_to_replace {
12647 this.change_selections(None, cx, |s| s.select_ranges(ranges));
12648 }
12649
12650 let marked_ranges = {
12651 let snapshot = this.buffer.read(cx).read(cx);
12652 this.selections
12653 .disjoint_anchors()
12654 .iter()
12655 .map(|selection| {
12656 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12657 })
12658 .collect::<Vec<_>>()
12659 };
12660
12661 if text.is_empty() {
12662 this.unmark_text(cx);
12663 } else {
12664 this.highlight_text::<InputComposition>(
12665 marked_ranges.clone(),
12666 HighlightStyle {
12667 underline: Some(UnderlineStyle {
12668 thickness: px(1.),
12669 color: None,
12670 wavy: false,
12671 }),
12672 ..Default::default()
12673 },
12674 cx,
12675 );
12676 }
12677
12678 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12679 let use_autoclose = this.use_autoclose;
12680 let use_auto_surround = this.use_auto_surround;
12681 this.set_use_autoclose(false);
12682 this.set_use_auto_surround(false);
12683 this.handle_input(text, cx);
12684 this.set_use_autoclose(use_autoclose);
12685 this.set_use_auto_surround(use_auto_surround);
12686
12687 if let Some(new_selected_range) = new_selected_range_utf16 {
12688 let snapshot = this.buffer.read(cx).read(cx);
12689 let new_selected_ranges = marked_ranges
12690 .into_iter()
12691 .map(|marked_range| {
12692 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
12693 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
12694 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
12695 snapshot.clip_offset_utf16(new_start, Bias::Left)
12696 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
12697 })
12698 .collect::<Vec<_>>();
12699
12700 drop(snapshot);
12701 this.change_selections(None, cx, |selections| {
12702 selections.select_ranges(new_selected_ranges)
12703 });
12704 }
12705 });
12706
12707 self.ime_transaction = self.ime_transaction.or(transaction);
12708 if let Some(transaction) = self.ime_transaction {
12709 self.buffer.update(cx, |buffer, cx| {
12710 buffer.group_until_transaction(transaction, cx);
12711 });
12712 }
12713
12714 if self.text_highlights::<InputComposition>(cx).is_none() {
12715 self.ime_transaction.take();
12716 }
12717 }
12718
12719 fn bounds_for_range(
12720 &mut self,
12721 range_utf16: Range<usize>,
12722 element_bounds: gpui::Bounds<Pixels>,
12723 cx: &mut ViewContext<Self>,
12724 ) -> Option<gpui::Bounds<Pixels>> {
12725 let text_layout_details = self.text_layout_details(cx);
12726 let style = &text_layout_details.editor_style;
12727 let font_id = cx.text_system().resolve_font(&style.text.font());
12728 let font_size = style.text.font_size.to_pixels(cx.rem_size());
12729 let line_height = style.text.line_height_in_pixels(cx.rem_size());
12730
12731 let em_width = cx
12732 .text_system()
12733 .typographic_bounds(font_id, font_size, 'm')
12734 .unwrap()
12735 .size
12736 .width;
12737
12738 let snapshot = self.snapshot(cx);
12739 let scroll_position = snapshot.scroll_position();
12740 let scroll_left = scroll_position.x * em_width;
12741
12742 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
12743 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
12744 + self.gutter_dimensions.width;
12745 let y = line_height * (start.row().as_f32() - scroll_position.y);
12746
12747 Some(Bounds {
12748 origin: element_bounds.origin + point(x, y),
12749 size: size(em_width, line_height),
12750 })
12751 }
12752}
12753
12754trait SelectionExt {
12755 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
12756 fn spanned_rows(
12757 &self,
12758 include_end_if_at_line_start: bool,
12759 map: &DisplaySnapshot,
12760 ) -> Range<MultiBufferRow>;
12761}
12762
12763impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
12764 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
12765 let start = self
12766 .start
12767 .to_point(&map.buffer_snapshot)
12768 .to_display_point(map);
12769 let end = self
12770 .end
12771 .to_point(&map.buffer_snapshot)
12772 .to_display_point(map);
12773 if self.reversed {
12774 end..start
12775 } else {
12776 start..end
12777 }
12778 }
12779
12780 fn spanned_rows(
12781 &self,
12782 include_end_if_at_line_start: bool,
12783 map: &DisplaySnapshot,
12784 ) -> Range<MultiBufferRow> {
12785 let start = self.start.to_point(&map.buffer_snapshot);
12786 let mut end = self.end.to_point(&map.buffer_snapshot);
12787 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
12788 end.row -= 1;
12789 }
12790
12791 let buffer_start = map.prev_line_boundary(start).0;
12792 let buffer_end = map.next_line_boundary(end).0;
12793 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
12794 }
12795}
12796
12797impl<T: InvalidationRegion> InvalidationStack<T> {
12798 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
12799 where
12800 S: Clone + ToOffset,
12801 {
12802 while let Some(region) = self.last() {
12803 let all_selections_inside_invalidation_ranges =
12804 if selections.len() == region.ranges().len() {
12805 selections
12806 .iter()
12807 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
12808 .all(|(selection, invalidation_range)| {
12809 let head = selection.head().to_offset(buffer);
12810 invalidation_range.start <= head && invalidation_range.end >= head
12811 })
12812 } else {
12813 false
12814 };
12815
12816 if all_selections_inside_invalidation_ranges {
12817 break;
12818 } else {
12819 self.pop();
12820 }
12821 }
12822 }
12823}
12824
12825impl<T> Default for InvalidationStack<T> {
12826 fn default() -> Self {
12827 Self(Default::default())
12828 }
12829}
12830
12831impl<T> Deref for InvalidationStack<T> {
12832 type Target = Vec<T>;
12833
12834 fn deref(&self) -> &Self::Target {
12835 &self.0
12836 }
12837}
12838
12839impl<T> DerefMut for InvalidationStack<T> {
12840 fn deref_mut(&mut self) -> &mut Self::Target {
12841 &mut self.0
12842 }
12843}
12844
12845impl InvalidationRegion for SnippetState {
12846 fn ranges(&self) -> &[Range<Anchor>] {
12847 &self.ranges[self.active_index]
12848 }
12849}
12850
12851pub fn diagnostic_block_renderer(
12852 diagnostic: Diagnostic,
12853 max_message_rows: Option<u8>,
12854 allow_closing: bool,
12855 _is_valid: bool,
12856) -> RenderBlock {
12857 let (text_without_backticks, code_ranges) =
12858 highlight_diagnostic_message(&diagnostic, max_message_rows);
12859
12860 Box::new(move |cx: &mut BlockContext| {
12861 let group_id: SharedString = cx.block_id.to_string().into();
12862
12863 let mut text_style = cx.text_style().clone();
12864 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
12865 let theme_settings = ThemeSettings::get_global(cx);
12866 text_style.font_family = theme_settings.buffer_font.family.clone();
12867 text_style.font_style = theme_settings.buffer_font.style;
12868 text_style.font_features = theme_settings.buffer_font.features.clone();
12869 text_style.font_weight = theme_settings.buffer_font.weight;
12870
12871 let multi_line_diagnostic = diagnostic.message.contains('\n');
12872
12873 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
12874 if multi_line_diagnostic {
12875 v_flex()
12876 } else {
12877 h_flex()
12878 }
12879 .when(allow_closing, |div| {
12880 div.children(diagnostic.is_primary.then(|| {
12881 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
12882 .icon_color(Color::Muted)
12883 .size(ButtonSize::Compact)
12884 .style(ButtonStyle::Transparent)
12885 .visible_on_hover(group_id.clone())
12886 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
12887 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
12888 }))
12889 })
12890 .child(
12891 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
12892 .icon_color(Color::Muted)
12893 .size(ButtonSize::Compact)
12894 .style(ButtonStyle::Transparent)
12895 .visible_on_hover(group_id.clone())
12896 .on_click({
12897 let message = diagnostic.message.clone();
12898 move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
12899 })
12900 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
12901 )
12902 };
12903
12904 let icon_size = buttons(&diagnostic, cx.block_id)
12905 .into_any_element()
12906 .layout_as_root(AvailableSpace::min_size(), cx);
12907
12908 h_flex()
12909 .id(cx.block_id)
12910 .group(group_id.clone())
12911 .relative()
12912 .size_full()
12913 .pl(cx.gutter_dimensions.width)
12914 .w(cx.max_width + cx.gutter_dimensions.width)
12915 .child(
12916 div()
12917 .flex()
12918 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
12919 .flex_shrink(),
12920 )
12921 .child(buttons(&diagnostic, cx.block_id))
12922 .child(div().flex().flex_shrink_0().child(
12923 StyledText::new(text_without_backticks.clone()).with_highlights(
12924 &text_style,
12925 code_ranges.iter().map(|range| {
12926 (
12927 range.clone(),
12928 HighlightStyle {
12929 font_weight: Some(FontWeight::BOLD),
12930 ..Default::default()
12931 },
12932 )
12933 }),
12934 ),
12935 ))
12936 .into_any_element()
12937 })
12938}
12939
12940pub fn highlight_diagnostic_message(
12941 diagnostic: &Diagnostic,
12942 mut max_message_rows: Option<u8>,
12943) -> (SharedString, Vec<Range<usize>>) {
12944 let mut text_without_backticks = String::new();
12945 let mut code_ranges = Vec::new();
12946
12947 if let Some(source) = &diagnostic.source {
12948 text_without_backticks.push_str(&source);
12949 code_ranges.push(0..source.len());
12950 text_without_backticks.push_str(": ");
12951 }
12952
12953 let mut prev_offset = 0;
12954 let mut in_code_block = false;
12955 let has_row_limit = max_message_rows.is_some();
12956 let mut newline_indices = diagnostic
12957 .message
12958 .match_indices('\n')
12959 .filter(|_| has_row_limit)
12960 .map(|(ix, _)| ix)
12961 .fuse()
12962 .peekable();
12963
12964 for (quote_ix, _) in diagnostic
12965 .message
12966 .match_indices('`')
12967 .chain([(diagnostic.message.len(), "")])
12968 {
12969 let mut first_newline_ix = None;
12970 let mut last_newline_ix = None;
12971 while let Some(newline_ix) = newline_indices.peek() {
12972 if *newline_ix < quote_ix {
12973 if first_newline_ix.is_none() {
12974 first_newline_ix = Some(*newline_ix);
12975 }
12976 last_newline_ix = Some(*newline_ix);
12977
12978 if let Some(rows_left) = &mut max_message_rows {
12979 if *rows_left == 0 {
12980 break;
12981 } else {
12982 *rows_left -= 1;
12983 }
12984 }
12985 let _ = newline_indices.next();
12986 } else {
12987 break;
12988 }
12989 }
12990 let prev_len = text_without_backticks.len();
12991 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
12992 text_without_backticks.push_str(new_text);
12993 if in_code_block {
12994 code_ranges.push(prev_len..text_without_backticks.len());
12995 }
12996 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
12997 in_code_block = !in_code_block;
12998 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
12999 text_without_backticks.push_str("...");
13000 break;
13001 }
13002 }
13003
13004 (text_without_backticks.into(), code_ranges)
13005}
13006
13007fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13008 match severity {
13009 DiagnosticSeverity::ERROR => colors.error,
13010 DiagnosticSeverity::WARNING => colors.warning,
13011 DiagnosticSeverity::INFORMATION => colors.info,
13012 DiagnosticSeverity::HINT => colors.info,
13013 _ => colors.ignored,
13014 }
13015}
13016
13017pub fn styled_runs_for_code_label<'a>(
13018 label: &'a CodeLabel,
13019 syntax_theme: &'a theme::SyntaxTheme,
13020) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13021 let fade_out = HighlightStyle {
13022 fade_out: Some(0.35),
13023 ..Default::default()
13024 };
13025
13026 let mut prev_end = label.filter_range.end;
13027 label
13028 .runs
13029 .iter()
13030 .enumerate()
13031 .flat_map(move |(ix, (range, highlight_id))| {
13032 let style = if let Some(style) = highlight_id.style(syntax_theme) {
13033 style
13034 } else {
13035 return Default::default();
13036 };
13037 let mut muted_style = style;
13038 muted_style.highlight(fade_out);
13039
13040 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13041 if range.start >= label.filter_range.end {
13042 if range.start > prev_end {
13043 runs.push((prev_end..range.start, fade_out));
13044 }
13045 runs.push((range.clone(), muted_style));
13046 } else if range.end <= label.filter_range.end {
13047 runs.push((range.clone(), style));
13048 } else {
13049 runs.push((range.start..label.filter_range.end, style));
13050 runs.push((label.filter_range.end..range.end, muted_style));
13051 }
13052 prev_end = cmp::max(prev_end, range.end);
13053
13054 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13055 runs.push((prev_end..label.text.len(), fade_out));
13056 }
13057
13058 runs
13059 })
13060}
13061
13062pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13063 let mut prev_index = 0;
13064 let mut prev_codepoint: Option<char> = None;
13065 text.char_indices()
13066 .chain([(text.len(), '\0')])
13067 .filter_map(move |(index, codepoint)| {
13068 let prev_codepoint = prev_codepoint.replace(codepoint)?;
13069 let is_boundary = index == text.len()
13070 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13071 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13072 if is_boundary {
13073 let chunk = &text[prev_index..index];
13074 prev_index = index;
13075 Some(chunk)
13076 } else {
13077 None
13078 }
13079 })
13080}
13081
13082pub trait RangeToAnchorExt: Sized {
13083 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13084
13085 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13086 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13087 anchor_range.start.to_display_point(&snapshot)..anchor_range.end.to_display_point(&snapshot)
13088 }
13089}
13090
13091impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13092 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13093 let start_offset = self.start.to_offset(snapshot);
13094 let end_offset = self.end.to_offset(snapshot);
13095 if start_offset == end_offset {
13096 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13097 } else {
13098 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13099 }
13100 }
13101}
13102
13103pub trait RowExt {
13104 fn as_f32(&self) -> f32;
13105
13106 fn next_row(&self) -> Self;
13107
13108 fn previous_row(&self) -> Self;
13109
13110 fn minus(&self, other: Self) -> u32;
13111}
13112
13113impl RowExt for DisplayRow {
13114 fn as_f32(&self) -> f32 {
13115 self.0 as f32
13116 }
13117
13118 fn next_row(&self) -> Self {
13119 Self(self.0 + 1)
13120 }
13121
13122 fn previous_row(&self) -> Self {
13123 Self(self.0.saturating_sub(1))
13124 }
13125
13126 fn minus(&self, other: Self) -> u32 {
13127 self.0 - other.0
13128 }
13129}
13130
13131impl RowExt for MultiBufferRow {
13132 fn as_f32(&self) -> f32 {
13133 self.0 as f32
13134 }
13135
13136 fn next_row(&self) -> Self {
13137 Self(self.0 + 1)
13138 }
13139
13140 fn previous_row(&self) -> Self {
13141 Self(self.0.saturating_sub(1))
13142 }
13143
13144 fn minus(&self, other: Self) -> u32 {
13145 self.0 - other.0
13146 }
13147}
13148
13149trait RowRangeExt {
13150 type Row;
13151
13152 fn len(&self) -> usize;
13153
13154 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13155}
13156
13157impl RowRangeExt for Range<MultiBufferRow> {
13158 type Row = MultiBufferRow;
13159
13160 fn len(&self) -> usize {
13161 (self.end.0 - self.start.0) as usize
13162 }
13163
13164 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13165 (self.start.0..self.end.0).map(MultiBufferRow)
13166 }
13167}
13168
13169impl RowRangeExt for Range<DisplayRow> {
13170 type Row = DisplayRow;
13171
13172 fn len(&self) -> usize {
13173 (self.end.0 - self.start.0) as usize
13174 }
13175
13176 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13177 (self.start.0..self.end.0).map(DisplayRow)
13178 }
13179}
13180
13181fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13182 if hunk.diff_base_byte_range.is_empty() {
13183 DiffHunkStatus::Added
13184 } else if hunk.associated_range.is_empty() {
13185 DiffHunkStatus::Removed
13186 } else {
13187 DiffHunkStatus::Modified
13188 }
13189}