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 clangd_ext;
19mod debounced_delay;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod hunk_diff;
29mod indent_guides;
30mod inlay_hint_cache;
31mod inline_completion_provider;
32pub mod items;
33mod linked_editing_ranges;
34mod lsp_ext;
35mod mouse_context_menu;
36pub mod movement;
37mod persistence;
38mod rust_analyzer_ext;
39pub mod scroll;
40mod selections_collection;
41pub mod tasks;
42
43#[cfg(test)]
44mod editor_tests;
45mod signature_help;
46#[cfg(any(test, feature = "test-support"))]
47pub mod test;
48
49use ::git::diff::{DiffHunk, DiffHunkStatus};
50use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
51pub(crate) use actions::*;
52use aho_corasick::AhoCorasick;
53use anyhow::{anyhow, Context as _, Result};
54use blink_manager::BlinkManager;
55use client::{Collaborator, ParticipantIndex};
56use clock::ReplicaId;
57use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
58use convert_case::{Case, Casing};
59use debounced_delay::DebouncedDelay;
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine};
63pub use editor_settings_controls::*;
64use element::LineWithInvisibles;
65pub use element::{
66 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
67};
68use futures::FutureExt;
69use fuzzy::{StringMatch, StringMatchCandidate};
70use git::blame::GitBlame;
71use git::diff_hunk_to_display;
72use gpui::{
73 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
74 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
75 ClipboardItem, Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle,
76 FocusOutEvent, FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText,
77 KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
78 SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
79 UTF16Selection, UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler,
80 VisualContext, WeakFocusHandle, WeakView, WindowContext,
81};
82use highlight_matching_bracket::refresh_matching_bracket_highlights;
83use hover_popover::{hide_hover, HoverState};
84use hunk_diff::ExpandedHunks;
85pub(crate) use hunk_diff::HoveredHunk;
86use indent_guides::ActiveIndentGuidesState;
87use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
88pub use inline_completion_provider::*;
89pub use items::MAX_TAB_TITLE_LEN;
90use itertools::Itertools;
91use language::{
92 language_settings::{self, all_language_settings, InlayHintSettings},
93 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
94 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
95 Point, Selection, SelectionGoal, TransactionId,
96};
97use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
98use linked_editing_ranges::refresh_linked_ranges;
99use task::{ResolvedTask, TaskTemplate, TaskVariables};
100
101use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
102pub use lsp::CompletionContext;
103use lsp::{
104 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
105 LanguageServerId,
106};
107use mouse_context_menu::MouseContextMenu;
108use movement::TextLayoutDetails;
109pub use multi_buffer::{
110 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
111 ToPoint,
112};
113use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
114use ordered_float::OrderedFloat;
115use parking_lot::{Mutex, RwLock};
116use project::project_settings::{GitGutterSetting, ProjectSettings};
117use project::{
118 CodeAction, Completion, CompletionIntent, FormatTrigger, Item, Location, Project, ProjectPath,
119 ProjectTransaction, TaskSourceKind, WorktreeId,
120};
121use rand::prelude::*;
122use rpc::{proto::*, ErrorExt};
123use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
124use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
125use serde::{Deserialize, Serialize};
126use settings::{update_settings_file, Settings, SettingsStore};
127use smallvec::SmallVec;
128use snippet::Snippet;
129use std::{
130 any::TypeId,
131 borrow::Cow,
132 cell::RefCell,
133 cmp::{self, Ordering, Reverse},
134 mem,
135 num::NonZeroU32,
136 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
137 path::{Path, PathBuf},
138 rc::Rc,
139 sync::Arc,
140 time::{Duration, Instant},
141};
142pub use sum_tree::Bias;
143use sum_tree::TreeMap;
144use text::{BufferId, OffsetUtf16, Rope};
145use theme::{
146 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
147 ThemeColors, ThemeSettings,
148};
149use ui::{
150 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
151 ListItem, Popover, Tooltip,
152};
153use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
154use workspace::item::{ItemHandle, PreviewTabsSettings};
155use workspace::notifications::{DetachAndPromptErr, NotificationId};
156use workspace::{
157 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
158};
159use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
160
161use crate::hover_links::find_url;
162use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
163
164pub const FILE_HEADER_HEIGHT: u32 = 1;
165pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
166pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
167pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
168const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
169const MAX_LINE_LEN: usize = 1024;
170const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
171const MAX_SELECTION_HISTORY_LEN: usize = 1024;
172pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
173#[doc(hidden)]
174pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
175#[doc(hidden)]
176pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
177
178pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
179pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
180
181pub fn render_parsed_markdown(
182 element_id: impl Into<ElementId>,
183 parsed: &language::ParsedMarkdown,
184 editor_style: &EditorStyle,
185 workspace: Option<WeakView<Workspace>>,
186 cx: &mut WindowContext,
187) -> InteractiveText {
188 let code_span_background_color = cx
189 .theme()
190 .colors()
191 .editor_document_highlight_read_background;
192
193 let highlights = gpui::combine_highlights(
194 parsed.highlights.iter().filter_map(|(range, highlight)| {
195 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
196 Some((range.clone(), highlight))
197 }),
198 parsed
199 .regions
200 .iter()
201 .zip(&parsed.region_ranges)
202 .filter_map(|(region, range)| {
203 if region.code {
204 Some((
205 range.clone(),
206 HighlightStyle {
207 background_color: Some(code_span_background_color),
208 ..Default::default()
209 },
210 ))
211 } else {
212 None
213 }
214 }),
215 );
216
217 let mut links = Vec::new();
218 let mut link_ranges = Vec::new();
219 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
220 if let Some(link) = region.link.clone() {
221 links.push(link);
222 link_ranges.push(range.clone());
223 }
224 }
225
226 InteractiveText::new(
227 element_id,
228 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
229 )
230 .on_click(link_ranges, move |clicked_range_ix, cx| {
231 match &links[clicked_range_ix] {
232 markdown::Link::Web { url } => cx.open_url(url),
233 markdown::Link::Path { path } => {
234 if let Some(workspace) = &workspace {
235 _ = workspace.update(cx, |workspace, cx| {
236 workspace.open_abs_path(path.clone(), false, cx).detach();
237 });
238 }
239 }
240 }
241 })
242}
243
244#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
245pub(crate) enum InlayId {
246 Suggestion(usize),
247 Hint(usize),
248}
249
250impl InlayId {
251 fn id(&self) -> usize {
252 match self {
253 Self::Suggestion(id) => *id,
254 Self::Hint(id) => *id,
255 }
256 }
257}
258
259enum DiffRowHighlight {}
260enum DocumentHighlightRead {}
261enum DocumentHighlightWrite {}
262enum InputComposition {}
263
264#[derive(Copy, Clone, PartialEq, Eq)]
265pub enum Direction {
266 Prev,
267 Next,
268}
269
270#[derive(Debug, Copy, Clone, PartialEq, Eq)]
271pub enum Navigated {
272 Yes,
273 No,
274}
275
276impl Navigated {
277 pub fn from_bool(yes: bool) -> Navigated {
278 if yes {
279 Navigated::Yes
280 } else {
281 Navigated::No
282 }
283 }
284}
285
286pub fn init_settings(cx: &mut AppContext) {
287 EditorSettings::register(cx);
288}
289
290pub fn init(cx: &mut AppContext) {
291 init_settings(cx);
292
293 workspace::register_project_item::<Editor>(cx);
294 workspace::FollowableViewRegistry::register::<Editor>(cx);
295 workspace::register_serializable_item::<Editor>(cx);
296
297 cx.observe_new_views(
298 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
299 workspace.register_action(Editor::new_file);
300 workspace.register_action(Editor::new_file_vertical);
301 workspace.register_action(Editor::new_file_horizontal);
302 },
303 )
304 .detach();
305
306 cx.on_action(move |_: &workspace::NewFile, cx| {
307 let app_state = workspace::AppState::global(cx);
308 if let Some(app_state) = app_state.upgrade() {
309 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
310 Editor::new_file(workspace, &Default::default(), cx)
311 })
312 .detach();
313 }
314 });
315 cx.on_action(move |_: &workspace::NewWindow, cx| {
316 let app_state = workspace::AppState::global(cx);
317 if let Some(app_state) = app_state.upgrade() {
318 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
319 Editor::new_file(workspace, &Default::default(), cx)
320 })
321 .detach();
322 }
323 });
324}
325
326pub struct SearchWithinRange;
327
328trait InvalidationRegion {
329 fn ranges(&self) -> &[Range<Anchor>];
330}
331
332#[derive(Clone, Debug, PartialEq)]
333pub enum SelectPhase {
334 Begin {
335 position: DisplayPoint,
336 add: bool,
337 click_count: usize,
338 },
339 BeginColumnar {
340 position: DisplayPoint,
341 reset: bool,
342 goal_column: u32,
343 },
344 Extend {
345 position: DisplayPoint,
346 click_count: usize,
347 },
348 Update {
349 position: DisplayPoint,
350 goal_column: u32,
351 scroll_delta: gpui::Point<f32>,
352 },
353 End,
354}
355
356#[derive(Clone, Debug)]
357pub enum SelectMode {
358 Character,
359 Word(Range<Anchor>),
360 Line(Range<Anchor>),
361 All,
362}
363
364#[derive(Copy, Clone, PartialEq, Eq, Debug)]
365pub enum EditorMode {
366 SingleLine { auto_width: bool },
367 AutoHeight { max_lines: usize },
368 Full,
369}
370
371#[derive(Clone, Debug)]
372pub enum SoftWrap {
373 None,
374 PreferLine,
375 EditorWidth,
376 Column(u32),
377 Bounded(u32),
378}
379
380#[derive(Clone)]
381pub struct EditorStyle {
382 pub background: Hsla,
383 pub local_player: PlayerColor,
384 pub text: TextStyle,
385 pub scrollbar_width: Pixels,
386 pub syntax: Arc<SyntaxTheme>,
387 pub status: StatusColors,
388 pub inlay_hints_style: HighlightStyle,
389 pub suggestions_style: HighlightStyle,
390 pub unnecessary_code_fade: f32,
391}
392
393impl Default for EditorStyle {
394 fn default() -> Self {
395 Self {
396 background: Hsla::default(),
397 local_player: PlayerColor::default(),
398 text: TextStyle::default(),
399 scrollbar_width: Pixels::default(),
400 syntax: Default::default(),
401 // HACK: Status colors don't have a real default.
402 // We should look into removing the status colors from the editor
403 // style and retrieve them directly from the theme.
404 status: StatusColors::dark(),
405 inlay_hints_style: HighlightStyle::default(),
406 suggestions_style: HighlightStyle::default(),
407 unnecessary_code_fade: Default::default(),
408 }
409 }
410}
411
412type CompletionId = usize;
413
414#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
415struct EditorActionId(usize);
416
417impl EditorActionId {
418 pub fn post_inc(&mut self) -> Self {
419 let answer = self.0;
420
421 *self = Self(answer + 1);
422
423 Self(answer)
424 }
425}
426
427// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
428// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
429
430type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
431type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
432
433#[derive(Default)]
434struct ScrollbarMarkerState {
435 scrollbar_size: Size<Pixels>,
436 dirty: bool,
437 markers: Arc<[PaintQuad]>,
438 pending_refresh: Option<Task<Result<()>>>,
439}
440
441impl ScrollbarMarkerState {
442 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
443 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
444 }
445}
446
447#[derive(Clone, Debug)]
448struct RunnableTasks {
449 templates: Vec<(TaskSourceKind, TaskTemplate)>,
450 offset: MultiBufferOffset,
451 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
452 column: u32,
453 // Values of all named captures, including those starting with '_'
454 extra_variables: HashMap<String, String>,
455 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
456 context_range: Range<BufferOffset>,
457}
458
459#[derive(Clone)]
460struct ResolvedTasks {
461 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
462 position: Anchor,
463}
464#[derive(Copy, Clone, Debug)]
465struct MultiBufferOffset(usize);
466#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
467struct BufferOffset(usize);
468
469// Addons allow storing per-editor state in other crates (e.g. Vim)
470pub trait Addon: 'static {
471 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
472
473 fn to_any(&self) -> &dyn std::any::Any;
474}
475
476/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
477///
478/// See the [module level documentation](self) for more information.
479pub struct Editor {
480 focus_handle: FocusHandle,
481 last_focused_descendant: Option<WeakFocusHandle>,
482 /// The text buffer being edited
483 buffer: Model<MultiBuffer>,
484 /// Map of how text in the buffer should be displayed.
485 /// Handles soft wraps, folds, fake inlay text insertions, etc.
486 pub display_map: Model<DisplayMap>,
487 pub selections: SelectionsCollection,
488 pub scroll_manager: ScrollManager,
489 /// When inline assist editors are linked, they all render cursors because
490 /// typing enters text into each of them, even the ones that aren't focused.
491 pub(crate) show_cursor_when_unfocused: bool,
492 columnar_selection_tail: Option<Anchor>,
493 add_selections_state: Option<AddSelectionsState>,
494 select_next_state: Option<SelectNextState>,
495 select_prev_state: Option<SelectNextState>,
496 selection_history: SelectionHistory,
497 autoclose_regions: Vec<AutocloseRegion>,
498 snippet_stack: InvalidationStack<SnippetState>,
499 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
500 ime_transaction: Option<TransactionId>,
501 active_diagnostics: Option<ActiveDiagnosticGroup>,
502 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
503 project: Option<Model<Project>>,
504 completion_provider: Option<Box<dyn CompletionProvider>>,
505 collaboration_hub: Option<Box<dyn CollaborationHub>>,
506 blink_manager: Model<BlinkManager>,
507 show_cursor_names: bool,
508 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
509 pub show_local_selections: bool,
510 mode: EditorMode,
511 show_breadcrumbs: bool,
512 show_gutter: bool,
513 show_line_numbers: Option<bool>,
514 use_relative_line_numbers: Option<bool>,
515 show_git_diff_gutter: Option<bool>,
516 show_code_actions: Option<bool>,
517 show_runnables: Option<bool>,
518 show_wrap_guides: Option<bool>,
519 show_indent_guides: Option<bool>,
520 placeholder_text: Option<Arc<str>>,
521 highlight_order: usize,
522 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
523 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
524 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
525 scrollbar_marker_state: ScrollbarMarkerState,
526 active_indent_guides_state: ActiveIndentGuidesState,
527 nav_history: Option<ItemNavHistory>,
528 context_menu: RwLock<Option<ContextMenu>>,
529 mouse_context_menu: Option<MouseContextMenu>,
530 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
531 signature_help_state: SignatureHelpState,
532 auto_signature_help: Option<bool>,
533 find_all_references_task_sources: Vec<Anchor>,
534 next_completion_id: CompletionId,
535 completion_documentation_pre_resolve_debounce: DebouncedDelay,
536 available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
537 code_actions_task: Option<Task<()>>,
538 document_highlights_task: Option<Task<()>>,
539 linked_editing_range_task: Option<Task<Option<()>>>,
540 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
541 pending_rename: Option<RenameState>,
542 searchable: bool,
543 cursor_shape: CursorShape,
544 current_line_highlight: Option<CurrentLineHighlight>,
545 collapse_matches: bool,
546 autoindent_mode: Option<AutoindentMode>,
547 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
548 input_enabled: bool,
549 use_modal_editing: bool,
550 read_only: bool,
551 leader_peer_id: Option<PeerId>,
552 remote_id: Option<ViewId>,
553 hover_state: HoverState,
554 gutter_hovered: bool,
555 hovered_link_state: Option<HoveredLinkState>,
556 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
557 active_inline_completion: Option<(Inlay, Option<Range<Anchor>>)>,
558 // enable_inline_completions is a switch that Vim can use to disable
559 // inline completions based on its mode.
560 enable_inline_completions: bool,
561 show_inline_completions_override: Option<bool>,
562 inlay_hint_cache: InlayHintCache,
563 expanded_hunks: ExpandedHunks,
564 next_inlay_id: usize,
565 _subscriptions: Vec<Subscription>,
566 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
567 gutter_dimensions: GutterDimensions,
568 style: Option<EditorStyle>,
569 next_editor_action_id: EditorActionId,
570 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
571 use_autoclose: bool,
572 use_auto_surround: bool,
573 auto_replace_emoji_shortcode: bool,
574 show_git_blame_gutter: bool,
575 show_git_blame_inline: bool,
576 show_git_blame_inline_delay_task: Option<Task<()>>,
577 git_blame_inline_enabled: bool,
578 serialize_dirty_buffers: bool,
579 show_selection_menu: Option<bool>,
580 blame: Option<Model<GitBlame>>,
581 blame_subscription: Option<Subscription>,
582 custom_context_menu: Option<
583 Box<
584 dyn 'static
585 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
586 >,
587 >,
588 last_bounds: Option<Bounds<Pixels>>,
589 expect_bounds_change: Option<Bounds<Pixels>>,
590 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
591 tasks_update_task: Option<Task<()>>,
592 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
593 file_header_size: u32,
594 breadcrumb_header: Option<String>,
595 focused_block: Option<FocusedBlock>,
596 next_scroll_position: NextScrollCursorCenterTopBottom,
597 addons: HashMap<TypeId, Box<dyn Addon>>,
598 _scroll_cursor_center_top_bottom_task: Task<()>,
599}
600
601#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
602enum NextScrollCursorCenterTopBottom {
603 #[default]
604 Center,
605 Top,
606 Bottom,
607}
608
609impl NextScrollCursorCenterTopBottom {
610 fn next(&self) -> Self {
611 match self {
612 Self::Center => Self::Top,
613 Self::Top => Self::Bottom,
614 Self::Bottom => Self::Center,
615 }
616 }
617}
618
619#[derive(Clone)]
620pub struct EditorSnapshot {
621 pub mode: EditorMode,
622 show_gutter: bool,
623 show_line_numbers: Option<bool>,
624 show_git_diff_gutter: Option<bool>,
625 show_code_actions: Option<bool>,
626 show_runnables: Option<bool>,
627 render_git_blame_gutter: bool,
628 pub display_snapshot: DisplaySnapshot,
629 pub placeholder_text: Option<Arc<str>>,
630 is_focused: bool,
631 scroll_anchor: ScrollAnchor,
632 ongoing_scroll: OngoingScroll,
633 current_line_highlight: CurrentLineHighlight,
634 gutter_hovered: bool,
635}
636
637const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
638
639#[derive(Default, Debug, Clone, Copy)]
640pub struct GutterDimensions {
641 pub left_padding: Pixels,
642 pub right_padding: Pixels,
643 pub width: Pixels,
644 pub margin: Pixels,
645 pub git_blame_entries_width: Option<Pixels>,
646}
647
648impl GutterDimensions {
649 /// The full width of the space taken up by the gutter.
650 pub fn full_width(&self) -> Pixels {
651 self.margin + self.width
652 }
653
654 /// The width of the space reserved for the fold indicators,
655 /// use alongside 'justify_end' and `gutter_width` to
656 /// right align content with the line numbers
657 pub fn fold_area_width(&self) -> Pixels {
658 self.margin + self.right_padding
659 }
660}
661
662#[derive(Debug)]
663pub struct RemoteSelection {
664 pub replica_id: ReplicaId,
665 pub selection: Selection<Anchor>,
666 pub cursor_shape: CursorShape,
667 pub peer_id: PeerId,
668 pub line_mode: bool,
669 pub participant_index: Option<ParticipantIndex>,
670 pub user_name: Option<SharedString>,
671}
672
673#[derive(Clone, Debug)]
674struct SelectionHistoryEntry {
675 selections: Arc<[Selection<Anchor>]>,
676 select_next_state: Option<SelectNextState>,
677 select_prev_state: Option<SelectNextState>,
678 add_selections_state: Option<AddSelectionsState>,
679}
680
681enum SelectionHistoryMode {
682 Normal,
683 Undoing,
684 Redoing,
685}
686
687#[derive(Clone, PartialEq, Eq, Hash)]
688struct HoveredCursor {
689 replica_id: u16,
690 selection_id: usize,
691}
692
693impl Default for SelectionHistoryMode {
694 fn default() -> Self {
695 Self::Normal
696 }
697}
698
699#[derive(Default)]
700struct SelectionHistory {
701 #[allow(clippy::type_complexity)]
702 selections_by_transaction:
703 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
704 mode: SelectionHistoryMode,
705 undo_stack: VecDeque<SelectionHistoryEntry>,
706 redo_stack: VecDeque<SelectionHistoryEntry>,
707}
708
709impl SelectionHistory {
710 fn insert_transaction(
711 &mut self,
712 transaction_id: TransactionId,
713 selections: Arc<[Selection<Anchor>]>,
714 ) {
715 self.selections_by_transaction
716 .insert(transaction_id, (selections, None));
717 }
718
719 #[allow(clippy::type_complexity)]
720 fn transaction(
721 &self,
722 transaction_id: TransactionId,
723 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
724 self.selections_by_transaction.get(&transaction_id)
725 }
726
727 #[allow(clippy::type_complexity)]
728 fn transaction_mut(
729 &mut self,
730 transaction_id: TransactionId,
731 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
732 self.selections_by_transaction.get_mut(&transaction_id)
733 }
734
735 fn push(&mut self, entry: SelectionHistoryEntry) {
736 if !entry.selections.is_empty() {
737 match self.mode {
738 SelectionHistoryMode::Normal => {
739 self.push_undo(entry);
740 self.redo_stack.clear();
741 }
742 SelectionHistoryMode::Undoing => self.push_redo(entry),
743 SelectionHistoryMode::Redoing => self.push_undo(entry),
744 }
745 }
746 }
747
748 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
749 if self
750 .undo_stack
751 .back()
752 .map_or(true, |e| e.selections != entry.selections)
753 {
754 self.undo_stack.push_back(entry);
755 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
756 self.undo_stack.pop_front();
757 }
758 }
759 }
760
761 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
762 if self
763 .redo_stack
764 .back()
765 .map_or(true, |e| e.selections != entry.selections)
766 {
767 self.redo_stack.push_back(entry);
768 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
769 self.redo_stack.pop_front();
770 }
771 }
772 }
773}
774
775struct RowHighlight {
776 index: usize,
777 range: RangeInclusive<Anchor>,
778 color: Option<Hsla>,
779 should_autoscroll: bool,
780}
781
782#[derive(Clone, Debug)]
783struct AddSelectionsState {
784 above: bool,
785 stack: Vec<usize>,
786}
787
788#[derive(Clone)]
789struct SelectNextState {
790 query: AhoCorasick,
791 wordwise: bool,
792 done: bool,
793}
794
795impl std::fmt::Debug for SelectNextState {
796 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
797 f.debug_struct(std::any::type_name::<Self>())
798 .field("wordwise", &self.wordwise)
799 .field("done", &self.done)
800 .finish()
801 }
802}
803
804#[derive(Debug)]
805struct AutocloseRegion {
806 selection_id: usize,
807 range: Range<Anchor>,
808 pair: BracketPair,
809}
810
811#[derive(Debug)]
812struct SnippetState {
813 ranges: Vec<Vec<Range<Anchor>>>,
814 active_index: usize,
815}
816
817#[doc(hidden)]
818pub struct RenameState {
819 pub range: Range<Anchor>,
820 pub old_name: Arc<str>,
821 pub editor: View<Editor>,
822 block_id: CustomBlockId,
823}
824
825struct InvalidationStack<T>(Vec<T>);
826
827struct RegisteredInlineCompletionProvider {
828 provider: Arc<dyn InlineCompletionProviderHandle>,
829 _subscription: Subscription,
830}
831
832enum ContextMenu {
833 Completions(CompletionsMenu),
834 CodeActions(CodeActionsMenu),
835}
836
837impl ContextMenu {
838 fn select_first(
839 &mut self,
840 project: Option<&Model<Project>>,
841 cx: &mut ViewContext<Editor>,
842 ) -> bool {
843 if self.visible() {
844 match self {
845 ContextMenu::Completions(menu) => menu.select_first(project, cx),
846 ContextMenu::CodeActions(menu) => menu.select_first(cx),
847 }
848 true
849 } else {
850 false
851 }
852 }
853
854 fn select_prev(
855 &mut self,
856 project: Option<&Model<Project>>,
857 cx: &mut ViewContext<Editor>,
858 ) -> bool {
859 if self.visible() {
860 match self {
861 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
862 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
863 }
864 true
865 } else {
866 false
867 }
868 }
869
870 fn select_next(
871 &mut self,
872 project: Option<&Model<Project>>,
873 cx: &mut ViewContext<Editor>,
874 ) -> bool {
875 if self.visible() {
876 match self {
877 ContextMenu::Completions(menu) => menu.select_next(project, cx),
878 ContextMenu::CodeActions(menu) => menu.select_next(cx),
879 }
880 true
881 } else {
882 false
883 }
884 }
885
886 fn select_last(
887 &mut self,
888 project: Option<&Model<Project>>,
889 cx: &mut ViewContext<Editor>,
890 ) -> bool {
891 if self.visible() {
892 match self {
893 ContextMenu::Completions(menu) => menu.select_last(project, cx),
894 ContextMenu::CodeActions(menu) => menu.select_last(cx),
895 }
896 true
897 } else {
898 false
899 }
900 }
901
902 fn visible(&self) -> bool {
903 match self {
904 ContextMenu::Completions(menu) => menu.visible(),
905 ContextMenu::CodeActions(menu) => menu.visible(),
906 }
907 }
908
909 fn render(
910 &self,
911 cursor_position: DisplayPoint,
912 style: &EditorStyle,
913 max_height: Pixels,
914 workspace: Option<WeakView<Workspace>>,
915 cx: &mut ViewContext<Editor>,
916 ) -> (ContextMenuOrigin, AnyElement) {
917 match self {
918 ContextMenu::Completions(menu) => (
919 ContextMenuOrigin::EditorPoint(cursor_position),
920 menu.render(style, max_height, workspace, cx),
921 ),
922 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
923 }
924 }
925}
926
927enum ContextMenuOrigin {
928 EditorPoint(DisplayPoint),
929 GutterIndicator(DisplayRow),
930}
931
932#[derive(Clone)]
933struct CompletionsMenu {
934 id: CompletionId,
935 sort_completions: bool,
936 initial_position: Anchor,
937 buffer: Model<Buffer>,
938 completions: Arc<RwLock<Box<[Completion]>>>,
939 match_candidates: Arc<[StringMatchCandidate]>,
940 matches: Arc<[StringMatch]>,
941 selected_item: usize,
942 scroll_handle: UniformListScrollHandle,
943 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
944}
945
946impl CompletionsMenu {
947 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
948 self.selected_item = 0;
949 self.scroll_handle.scroll_to_item(self.selected_item);
950 self.attempt_resolve_selected_completion_documentation(project, cx);
951 cx.notify();
952 }
953
954 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
955 if self.selected_item > 0 {
956 self.selected_item -= 1;
957 } else {
958 self.selected_item = self.matches.len() - 1;
959 }
960 self.scroll_handle.scroll_to_item(self.selected_item);
961 self.attempt_resolve_selected_completion_documentation(project, cx);
962 cx.notify();
963 }
964
965 fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
966 if self.selected_item + 1 < self.matches.len() {
967 self.selected_item += 1;
968 } else {
969 self.selected_item = 0;
970 }
971 self.scroll_handle.scroll_to_item(self.selected_item);
972 self.attempt_resolve_selected_completion_documentation(project, cx);
973 cx.notify();
974 }
975
976 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
977 self.selected_item = self.matches.len() - 1;
978 self.scroll_handle.scroll_to_item(self.selected_item);
979 self.attempt_resolve_selected_completion_documentation(project, cx);
980 cx.notify();
981 }
982
983 fn pre_resolve_completion_documentation(
984 buffer: Model<Buffer>,
985 completions: Arc<RwLock<Box<[Completion]>>>,
986 matches: Arc<[StringMatch]>,
987 editor: &Editor,
988 cx: &mut ViewContext<Editor>,
989 ) -> Task<()> {
990 let settings = EditorSettings::get_global(cx);
991 if !settings.show_completion_documentation {
992 return Task::ready(());
993 }
994
995 let Some(provider) = editor.completion_provider.as_ref() else {
996 return Task::ready(());
997 };
998
999 let resolve_task = provider.resolve_completions(
1000 buffer,
1001 matches.iter().map(|m| m.candidate_id).collect(),
1002 completions.clone(),
1003 cx,
1004 );
1005
1006 return cx.spawn(move |this, mut cx| async move {
1007 if let Some(true) = resolve_task.await.log_err() {
1008 this.update(&mut cx, |_, cx| cx.notify()).ok();
1009 }
1010 });
1011 }
1012
1013 fn attempt_resolve_selected_completion_documentation(
1014 &mut self,
1015 project: Option<&Model<Project>>,
1016 cx: &mut ViewContext<Editor>,
1017 ) {
1018 let settings = EditorSettings::get_global(cx);
1019 if !settings.show_completion_documentation {
1020 return;
1021 }
1022
1023 let completion_index = self.matches[self.selected_item].candidate_id;
1024 let Some(project) = project else {
1025 return;
1026 };
1027
1028 let resolve_task = project.update(cx, |project, cx| {
1029 project.resolve_completions(
1030 self.buffer.clone(),
1031 vec![completion_index],
1032 self.completions.clone(),
1033 cx,
1034 )
1035 });
1036
1037 let delay_ms =
1038 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1039 let delay = Duration::from_millis(delay_ms);
1040
1041 self.selected_completion_documentation_resolve_debounce
1042 .lock()
1043 .fire_new(delay, cx, |_, cx| {
1044 cx.spawn(move |this, mut cx| async move {
1045 if let Some(true) = resolve_task.await.log_err() {
1046 this.update(&mut cx, |_, cx| cx.notify()).ok();
1047 }
1048 })
1049 });
1050 }
1051
1052 fn visible(&self) -> bool {
1053 !self.matches.is_empty()
1054 }
1055
1056 fn render(
1057 &self,
1058 style: &EditorStyle,
1059 max_height: Pixels,
1060 workspace: Option<WeakView<Workspace>>,
1061 cx: &mut ViewContext<Editor>,
1062 ) -> AnyElement {
1063 let settings = EditorSettings::get_global(cx);
1064 let show_completion_documentation = settings.show_completion_documentation;
1065
1066 let widest_completion_ix = self
1067 .matches
1068 .iter()
1069 .enumerate()
1070 .max_by_key(|(_, mat)| {
1071 let completions = self.completions.read();
1072 let completion = &completions[mat.candidate_id];
1073 let documentation = &completion.documentation;
1074
1075 let mut len = completion.label.text.chars().count();
1076 if let Some(Documentation::SingleLine(text)) = documentation {
1077 if show_completion_documentation {
1078 len += text.chars().count();
1079 }
1080 }
1081
1082 len
1083 })
1084 .map(|(ix, _)| ix);
1085
1086 let completions = self.completions.clone();
1087 let matches = self.matches.clone();
1088 let selected_item = self.selected_item;
1089 let style = style.clone();
1090
1091 let multiline_docs = if show_completion_documentation {
1092 let mat = &self.matches[selected_item];
1093 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1094 Some(Documentation::MultiLinePlainText(text)) => {
1095 Some(div().child(SharedString::from(text.clone())))
1096 }
1097 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1098 Some(div().child(render_parsed_markdown(
1099 "completions_markdown",
1100 parsed,
1101 &style,
1102 workspace,
1103 cx,
1104 )))
1105 }
1106 _ => None,
1107 };
1108 multiline_docs.map(|div| {
1109 div.id("multiline_docs")
1110 .max_h(max_height)
1111 .flex_1()
1112 .px_1p5()
1113 .py_1()
1114 .min_w(px(260.))
1115 .max_w(px(640.))
1116 .w(px(500.))
1117 .overflow_y_scroll()
1118 .occlude()
1119 })
1120 } else {
1121 None
1122 };
1123
1124 let list = uniform_list(
1125 cx.view().clone(),
1126 "completions",
1127 matches.len(),
1128 move |_editor, range, cx| {
1129 let start_ix = range.start;
1130 let completions_guard = completions.read();
1131
1132 matches[range]
1133 .iter()
1134 .enumerate()
1135 .map(|(ix, mat)| {
1136 let item_ix = start_ix + ix;
1137 let candidate_id = mat.candidate_id;
1138 let completion = &completions_guard[candidate_id];
1139
1140 let documentation = if show_completion_documentation {
1141 &completion.documentation
1142 } else {
1143 &None
1144 };
1145
1146 let highlights = gpui::combine_highlights(
1147 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1148 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1149 |(range, mut highlight)| {
1150 // Ignore font weight for syntax highlighting, as we'll use it
1151 // for fuzzy matches.
1152 highlight.font_weight = None;
1153
1154 if completion.lsp_completion.deprecated.unwrap_or(false) {
1155 highlight.strikethrough = Some(StrikethroughStyle {
1156 thickness: 1.0.into(),
1157 ..Default::default()
1158 });
1159 highlight.color = Some(cx.theme().colors().text_muted);
1160 }
1161
1162 (range, highlight)
1163 },
1164 ),
1165 );
1166 let completion_label = StyledText::new(completion.label.text.clone())
1167 .with_highlights(&style.text, highlights);
1168 let documentation_label =
1169 if let Some(Documentation::SingleLine(text)) = documentation {
1170 if text.trim().is_empty() {
1171 None
1172 } else {
1173 Some(
1174 Label::new(text.clone())
1175 .ml_4()
1176 .size(LabelSize::Small)
1177 .color(Color::Muted),
1178 )
1179 }
1180 } else {
1181 None
1182 };
1183
1184 div().min_w(px(220.)).max_w(px(540.)).child(
1185 ListItem::new(mat.candidate_id)
1186 .inset(true)
1187 .selected(item_ix == selected_item)
1188 .on_click(cx.listener(move |editor, _event, cx| {
1189 cx.stop_propagation();
1190 if let Some(task) = editor.confirm_completion(
1191 &ConfirmCompletion {
1192 item_ix: Some(item_ix),
1193 },
1194 cx,
1195 ) {
1196 task.detach_and_log_err(cx)
1197 }
1198 }))
1199 .child(h_flex().overflow_hidden().child(completion_label))
1200 .end_slot::<Label>(documentation_label),
1201 )
1202 })
1203 .collect()
1204 },
1205 )
1206 .occlude()
1207 .max_h(max_height)
1208 .track_scroll(self.scroll_handle.clone())
1209 .with_width_from_item(widest_completion_ix)
1210 .with_sizing_behavior(ListSizingBehavior::Infer);
1211
1212 Popover::new()
1213 .child(list)
1214 .when_some(multiline_docs, |popover, multiline_docs| {
1215 popover.aside(multiline_docs)
1216 })
1217 .into_any_element()
1218 }
1219
1220 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1221 let mut matches = if let Some(query) = query {
1222 fuzzy::match_strings(
1223 &self.match_candidates,
1224 query,
1225 query.chars().any(|c| c.is_uppercase()),
1226 100,
1227 &Default::default(),
1228 executor,
1229 )
1230 .await
1231 } else {
1232 self.match_candidates
1233 .iter()
1234 .enumerate()
1235 .map(|(candidate_id, candidate)| StringMatch {
1236 candidate_id,
1237 score: Default::default(),
1238 positions: Default::default(),
1239 string: candidate.string.clone(),
1240 })
1241 .collect()
1242 };
1243
1244 // Remove all candidates where the query's start does not match the start of any word in the candidate
1245 if let Some(query) = query {
1246 if let Some(query_start) = query.chars().next() {
1247 matches.retain(|string_match| {
1248 split_words(&string_match.string).any(|word| {
1249 // Check that the first codepoint of the word as lowercase matches the first
1250 // codepoint of the query as lowercase
1251 word.chars()
1252 .flat_map(|codepoint| codepoint.to_lowercase())
1253 .zip(query_start.to_lowercase())
1254 .all(|(word_cp, query_cp)| word_cp == query_cp)
1255 })
1256 });
1257 }
1258 }
1259
1260 let completions = self.completions.read();
1261 if self.sort_completions {
1262 matches.sort_unstable_by_key(|mat| {
1263 // We do want to strike a balance here between what the language server tells us
1264 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1265 // `Creat` and there is a local variable called `CreateComponent`).
1266 // So what we do is: we bucket all matches into two buckets
1267 // - Strong matches
1268 // - Weak matches
1269 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1270 // and the Weak matches are the rest.
1271 //
1272 // For the strong matches, we sort by the language-servers score first and for the weak
1273 // matches, we prefer our fuzzy finder first.
1274 //
1275 // The thinking behind that: it's useless to take the sort_text the language-server gives
1276 // us into account when it's obviously a bad match.
1277
1278 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1279 enum MatchScore<'a> {
1280 Strong {
1281 sort_text: Option<&'a str>,
1282 score: Reverse<OrderedFloat<f64>>,
1283 sort_key: (usize, &'a str),
1284 },
1285 Weak {
1286 score: Reverse<OrderedFloat<f64>>,
1287 sort_text: Option<&'a str>,
1288 sort_key: (usize, &'a str),
1289 },
1290 }
1291
1292 let completion = &completions[mat.candidate_id];
1293 let sort_key = completion.sort_key();
1294 let sort_text = completion.lsp_completion.sort_text.as_deref();
1295 let score = Reverse(OrderedFloat(mat.score));
1296
1297 if mat.score >= 0.2 {
1298 MatchScore::Strong {
1299 sort_text,
1300 score,
1301 sort_key,
1302 }
1303 } else {
1304 MatchScore::Weak {
1305 score,
1306 sort_text,
1307 sort_key,
1308 }
1309 }
1310 });
1311 }
1312
1313 for mat in &mut matches {
1314 let completion = &completions[mat.candidate_id];
1315 mat.string.clone_from(&completion.label.text);
1316 for position in &mut mat.positions {
1317 *position += completion.label.filter_range.start;
1318 }
1319 }
1320 drop(completions);
1321
1322 self.matches = matches.into();
1323 self.selected_item = 0;
1324 }
1325}
1326
1327#[derive(Clone)]
1328struct CodeActionContents {
1329 tasks: Option<Arc<ResolvedTasks>>,
1330 actions: Option<Arc<[CodeAction]>>,
1331}
1332
1333impl CodeActionContents {
1334 fn len(&self) -> usize {
1335 match (&self.tasks, &self.actions) {
1336 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1337 (Some(tasks), None) => tasks.templates.len(),
1338 (None, Some(actions)) => actions.len(),
1339 (None, None) => 0,
1340 }
1341 }
1342
1343 fn is_empty(&self) -> bool {
1344 match (&self.tasks, &self.actions) {
1345 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1346 (Some(tasks), None) => tasks.templates.is_empty(),
1347 (None, Some(actions)) => actions.is_empty(),
1348 (None, None) => true,
1349 }
1350 }
1351
1352 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1353 self.tasks
1354 .iter()
1355 .flat_map(|tasks| {
1356 tasks
1357 .templates
1358 .iter()
1359 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1360 })
1361 .chain(self.actions.iter().flat_map(|actions| {
1362 actions
1363 .iter()
1364 .map(|action| CodeActionsItem::CodeAction(action.clone()))
1365 }))
1366 }
1367 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1368 match (&self.tasks, &self.actions) {
1369 (Some(tasks), Some(actions)) => {
1370 if index < tasks.templates.len() {
1371 tasks
1372 .templates
1373 .get(index)
1374 .cloned()
1375 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1376 } else {
1377 actions
1378 .get(index - tasks.templates.len())
1379 .cloned()
1380 .map(CodeActionsItem::CodeAction)
1381 }
1382 }
1383 (Some(tasks), None) => tasks
1384 .templates
1385 .get(index)
1386 .cloned()
1387 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1388 (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
1389 (None, None) => None,
1390 }
1391 }
1392}
1393
1394#[allow(clippy::large_enum_variant)]
1395#[derive(Clone)]
1396enum CodeActionsItem {
1397 Task(TaskSourceKind, ResolvedTask),
1398 CodeAction(CodeAction),
1399}
1400
1401impl CodeActionsItem {
1402 fn as_task(&self) -> Option<&ResolvedTask> {
1403 let Self::Task(_, task) = self else {
1404 return None;
1405 };
1406 Some(task)
1407 }
1408 fn as_code_action(&self) -> Option<&CodeAction> {
1409 let Self::CodeAction(action) = self else {
1410 return None;
1411 };
1412 Some(action)
1413 }
1414 fn label(&self) -> String {
1415 match self {
1416 Self::CodeAction(action) => action.lsp_action.title.clone(),
1417 Self::Task(_, task) => task.resolved_label.clone(),
1418 }
1419 }
1420}
1421
1422struct CodeActionsMenu {
1423 actions: CodeActionContents,
1424 buffer: Model<Buffer>,
1425 selected_item: usize,
1426 scroll_handle: UniformListScrollHandle,
1427 deployed_from_indicator: Option<DisplayRow>,
1428}
1429
1430impl CodeActionsMenu {
1431 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1432 self.selected_item = 0;
1433 self.scroll_handle.scroll_to_item(self.selected_item);
1434 cx.notify()
1435 }
1436
1437 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1438 if self.selected_item > 0 {
1439 self.selected_item -= 1;
1440 } else {
1441 self.selected_item = self.actions.len() - 1;
1442 }
1443 self.scroll_handle.scroll_to_item(self.selected_item);
1444 cx.notify();
1445 }
1446
1447 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1448 if self.selected_item + 1 < self.actions.len() {
1449 self.selected_item += 1;
1450 } else {
1451 self.selected_item = 0;
1452 }
1453 self.scroll_handle.scroll_to_item(self.selected_item);
1454 cx.notify();
1455 }
1456
1457 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1458 self.selected_item = self.actions.len() - 1;
1459 self.scroll_handle.scroll_to_item(self.selected_item);
1460 cx.notify()
1461 }
1462
1463 fn visible(&self) -> bool {
1464 !self.actions.is_empty()
1465 }
1466
1467 fn render(
1468 &self,
1469 cursor_position: DisplayPoint,
1470 _style: &EditorStyle,
1471 max_height: Pixels,
1472 cx: &mut ViewContext<Editor>,
1473 ) -> (ContextMenuOrigin, AnyElement) {
1474 let actions = self.actions.clone();
1475 let selected_item = self.selected_item;
1476 let element = uniform_list(
1477 cx.view().clone(),
1478 "code_actions_menu",
1479 self.actions.len(),
1480 move |_this, range, cx| {
1481 actions
1482 .iter()
1483 .skip(range.start)
1484 .take(range.end - range.start)
1485 .enumerate()
1486 .map(|(ix, action)| {
1487 let item_ix = range.start + ix;
1488 let selected = selected_item == item_ix;
1489 let colors = cx.theme().colors();
1490 div()
1491 .px_2()
1492 .text_color(colors.text)
1493 .when(selected, |style| {
1494 style
1495 .bg(colors.element_active)
1496 .text_color(colors.text_accent)
1497 })
1498 .hover(|style| {
1499 style
1500 .bg(colors.element_hover)
1501 .text_color(colors.text_accent)
1502 })
1503 .whitespace_nowrap()
1504 .when_some(action.as_code_action(), |this, action| {
1505 this.on_mouse_down(
1506 MouseButton::Left,
1507 cx.listener(move |editor, _, cx| {
1508 cx.stop_propagation();
1509 if let Some(task) = editor.confirm_code_action(
1510 &ConfirmCodeAction {
1511 item_ix: Some(item_ix),
1512 },
1513 cx,
1514 ) {
1515 task.detach_and_log_err(cx)
1516 }
1517 }),
1518 )
1519 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1520 .child(SharedString::from(action.lsp_action.title.clone()))
1521 })
1522 .when_some(action.as_task(), |this, task| {
1523 this.on_mouse_down(
1524 MouseButton::Left,
1525 cx.listener(move |editor, _, cx| {
1526 cx.stop_propagation();
1527 if let Some(task) = editor.confirm_code_action(
1528 &ConfirmCodeAction {
1529 item_ix: Some(item_ix),
1530 },
1531 cx,
1532 ) {
1533 task.detach_and_log_err(cx)
1534 }
1535 }),
1536 )
1537 .child(SharedString::from(task.resolved_label.clone()))
1538 })
1539 })
1540 .collect()
1541 },
1542 )
1543 .elevation_1(cx)
1544 .px_2()
1545 .py_1()
1546 .max_h(max_height)
1547 .occlude()
1548 .track_scroll(self.scroll_handle.clone())
1549 .with_width_from_item(
1550 self.actions
1551 .iter()
1552 .enumerate()
1553 .max_by_key(|(_, action)| match action {
1554 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1555 CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
1556 })
1557 .map(|(ix, _)| ix),
1558 )
1559 .with_sizing_behavior(ListSizingBehavior::Infer)
1560 .into_any_element();
1561
1562 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1563 ContextMenuOrigin::GutterIndicator(row)
1564 } else {
1565 ContextMenuOrigin::EditorPoint(cursor_position)
1566 };
1567
1568 (cursor_position, element)
1569 }
1570}
1571
1572#[derive(Debug)]
1573struct ActiveDiagnosticGroup {
1574 primary_range: Range<Anchor>,
1575 primary_message: String,
1576 group_id: usize,
1577 blocks: HashMap<CustomBlockId, Diagnostic>,
1578 is_valid: bool,
1579}
1580
1581#[derive(Serialize, Deserialize, Clone, Debug)]
1582pub struct ClipboardSelection {
1583 pub len: usize,
1584 pub is_entire_line: bool,
1585 pub first_line_indent: u32,
1586}
1587
1588#[derive(Debug)]
1589pub(crate) struct NavigationData {
1590 cursor_anchor: Anchor,
1591 cursor_position: Point,
1592 scroll_anchor: ScrollAnchor,
1593 scroll_top_row: u32,
1594}
1595
1596#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1597enum GotoDefinitionKind {
1598 Symbol,
1599 Declaration,
1600 Type,
1601 Implementation,
1602}
1603
1604#[derive(Debug, Clone)]
1605enum InlayHintRefreshReason {
1606 Toggle(bool),
1607 SettingsChange(InlayHintSettings),
1608 NewLinesShown,
1609 BufferEdited(HashSet<Arc<Language>>),
1610 RefreshRequested,
1611 ExcerptsRemoved(Vec<ExcerptId>),
1612}
1613
1614impl InlayHintRefreshReason {
1615 fn description(&self) -> &'static str {
1616 match self {
1617 Self::Toggle(_) => "toggle",
1618 Self::SettingsChange(_) => "settings change",
1619 Self::NewLinesShown => "new lines shown",
1620 Self::BufferEdited(_) => "buffer edited",
1621 Self::RefreshRequested => "refresh requested",
1622 Self::ExcerptsRemoved(_) => "excerpts removed",
1623 }
1624 }
1625}
1626
1627pub(crate) struct FocusedBlock {
1628 id: BlockId,
1629 focus_handle: WeakFocusHandle,
1630}
1631
1632impl Editor {
1633 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1634 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1635 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1636 Self::new(
1637 EditorMode::SingleLine { auto_width: false },
1638 buffer,
1639 None,
1640 false,
1641 cx,
1642 )
1643 }
1644
1645 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1646 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1647 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1648 Self::new(EditorMode::Full, buffer, None, false, cx)
1649 }
1650
1651 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1652 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1653 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1654 Self::new(
1655 EditorMode::SingleLine { auto_width: true },
1656 buffer,
1657 None,
1658 false,
1659 cx,
1660 )
1661 }
1662
1663 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1664 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1665 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1666 Self::new(
1667 EditorMode::AutoHeight { max_lines },
1668 buffer,
1669 None,
1670 false,
1671 cx,
1672 )
1673 }
1674
1675 pub fn for_buffer(
1676 buffer: Model<Buffer>,
1677 project: Option<Model<Project>>,
1678 cx: &mut ViewContext<Self>,
1679 ) -> Self {
1680 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1681 Self::new(EditorMode::Full, buffer, project, false, cx)
1682 }
1683
1684 pub fn for_multibuffer(
1685 buffer: Model<MultiBuffer>,
1686 project: Option<Model<Project>>,
1687 show_excerpt_controls: bool,
1688 cx: &mut ViewContext<Self>,
1689 ) -> Self {
1690 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1691 }
1692
1693 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1694 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1695 let mut clone = Self::new(
1696 self.mode,
1697 self.buffer.clone(),
1698 self.project.clone(),
1699 show_excerpt_controls,
1700 cx,
1701 );
1702 self.display_map.update(cx, |display_map, cx| {
1703 let snapshot = display_map.snapshot(cx);
1704 clone.display_map.update(cx, |display_map, cx| {
1705 display_map.set_state(&snapshot, cx);
1706 });
1707 });
1708 clone.selections.clone_state(&self.selections);
1709 clone.scroll_manager.clone_state(&self.scroll_manager);
1710 clone.searchable = self.searchable;
1711 clone
1712 }
1713
1714 pub fn new(
1715 mode: EditorMode,
1716 buffer: Model<MultiBuffer>,
1717 project: Option<Model<Project>>,
1718 show_excerpt_controls: bool,
1719 cx: &mut ViewContext<Self>,
1720 ) -> Self {
1721 let style = cx.text_style();
1722 let font_size = style.font_size.to_pixels(cx.rem_size());
1723 let editor = cx.view().downgrade();
1724 let fold_placeholder = FoldPlaceholder {
1725 constrain_width: true,
1726 render: Arc::new(move |fold_id, fold_range, cx| {
1727 let editor = editor.clone();
1728 div()
1729 .id(fold_id)
1730 .bg(cx.theme().colors().ghost_element_background)
1731 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1732 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1733 .rounded_sm()
1734 .size_full()
1735 .cursor_pointer()
1736 .child("⋯")
1737 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1738 .on_click(move |_, cx| {
1739 editor
1740 .update(cx, |editor, cx| {
1741 editor.unfold_ranges(
1742 [fold_range.start..fold_range.end],
1743 true,
1744 false,
1745 cx,
1746 );
1747 cx.stop_propagation();
1748 })
1749 .ok();
1750 })
1751 .into_any()
1752 }),
1753 merge_adjacent: true,
1754 };
1755 let file_header_size = if show_excerpt_controls { 3 } else { 2 };
1756 let display_map = cx.new_model(|cx| {
1757 DisplayMap::new(
1758 buffer.clone(),
1759 style.font(),
1760 font_size,
1761 None,
1762 show_excerpt_controls,
1763 file_header_size,
1764 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1765 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1766 fold_placeholder,
1767 cx,
1768 )
1769 });
1770
1771 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1772
1773 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1774
1775 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1776 .then(|| language_settings::SoftWrap::PreferLine);
1777
1778 let mut project_subscriptions = Vec::new();
1779 if mode == EditorMode::Full {
1780 if let Some(project) = project.as_ref() {
1781 if buffer.read(cx).is_singleton() {
1782 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1783 cx.emit(EditorEvent::TitleChanged);
1784 }));
1785 }
1786 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1787 if let project::Event::RefreshInlayHints = event {
1788 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1789 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1790 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1791 let focus_handle = editor.focus_handle(cx);
1792 if focus_handle.is_focused(cx) {
1793 let snapshot = buffer.read(cx).snapshot();
1794 for (range, snippet) in snippet_edits {
1795 let editor_range =
1796 language::range_from_lsp(*range).to_offset(&snapshot);
1797 editor
1798 .insert_snippet(&[editor_range], snippet.clone(), cx)
1799 .ok();
1800 }
1801 }
1802 }
1803 }
1804 }));
1805 let task_inventory = project.read(cx).task_inventory().clone();
1806 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1807 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1808 }));
1809 }
1810 }
1811
1812 let inlay_hint_settings = inlay_hint_settings(
1813 selections.newest_anchor().head(),
1814 &buffer.read(cx).snapshot(cx),
1815 cx,
1816 );
1817 let focus_handle = cx.focus_handle();
1818 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1819 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1820 .detach();
1821 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1822 .detach();
1823 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1824
1825 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1826 Some(false)
1827 } else {
1828 None
1829 };
1830
1831 let mut this = Self {
1832 focus_handle,
1833 show_cursor_when_unfocused: false,
1834 last_focused_descendant: None,
1835 buffer: buffer.clone(),
1836 display_map: display_map.clone(),
1837 selections,
1838 scroll_manager: ScrollManager::new(cx),
1839 columnar_selection_tail: None,
1840 add_selections_state: None,
1841 select_next_state: None,
1842 select_prev_state: None,
1843 selection_history: Default::default(),
1844 autoclose_regions: Default::default(),
1845 snippet_stack: Default::default(),
1846 select_larger_syntax_node_stack: Vec::new(),
1847 ime_transaction: Default::default(),
1848 active_diagnostics: None,
1849 soft_wrap_mode_override,
1850 completion_provider: project.clone().map(|project| Box::new(project) as _),
1851 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1852 project,
1853 blink_manager: blink_manager.clone(),
1854 show_local_selections: true,
1855 mode,
1856 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1857 show_gutter: mode == EditorMode::Full,
1858 show_line_numbers: None,
1859 use_relative_line_numbers: None,
1860 show_git_diff_gutter: None,
1861 show_code_actions: None,
1862 show_runnables: None,
1863 show_wrap_guides: None,
1864 show_indent_guides,
1865 placeholder_text: None,
1866 highlight_order: 0,
1867 highlighted_rows: HashMap::default(),
1868 background_highlights: Default::default(),
1869 gutter_highlights: TreeMap::default(),
1870 scrollbar_marker_state: ScrollbarMarkerState::default(),
1871 active_indent_guides_state: ActiveIndentGuidesState::default(),
1872 nav_history: None,
1873 context_menu: RwLock::new(None),
1874 mouse_context_menu: None,
1875 completion_tasks: Default::default(),
1876 signature_help_state: SignatureHelpState::default(),
1877 auto_signature_help: None,
1878 find_all_references_task_sources: Vec::new(),
1879 next_completion_id: 0,
1880 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1881 next_inlay_id: 0,
1882 available_code_actions: Default::default(),
1883 code_actions_task: Default::default(),
1884 document_highlights_task: Default::default(),
1885 linked_editing_range_task: Default::default(),
1886 pending_rename: Default::default(),
1887 searchable: true,
1888 cursor_shape: Default::default(),
1889 current_line_highlight: None,
1890 autoindent_mode: Some(AutoindentMode::EachLine),
1891 collapse_matches: false,
1892 workspace: None,
1893 input_enabled: true,
1894 use_modal_editing: mode == EditorMode::Full,
1895 read_only: false,
1896 use_autoclose: true,
1897 use_auto_surround: true,
1898 auto_replace_emoji_shortcode: false,
1899 leader_peer_id: None,
1900 remote_id: None,
1901 hover_state: Default::default(),
1902 hovered_link_state: Default::default(),
1903 inline_completion_provider: None,
1904 active_inline_completion: None,
1905 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1906 expanded_hunks: ExpandedHunks::default(),
1907 gutter_hovered: false,
1908 pixel_position_of_newest_cursor: None,
1909 last_bounds: None,
1910 expect_bounds_change: None,
1911 gutter_dimensions: GutterDimensions::default(),
1912 style: None,
1913 show_cursor_names: false,
1914 hovered_cursors: Default::default(),
1915 next_editor_action_id: EditorActionId::default(),
1916 editor_actions: Rc::default(),
1917 show_inline_completions_override: None,
1918 enable_inline_completions: true,
1919 custom_context_menu: None,
1920 show_git_blame_gutter: false,
1921 show_git_blame_inline: false,
1922 show_selection_menu: None,
1923 show_git_blame_inline_delay_task: None,
1924 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1925 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1926 .session
1927 .restore_unsaved_buffers,
1928 blame: None,
1929 blame_subscription: None,
1930 file_header_size,
1931 tasks: Default::default(),
1932 _subscriptions: vec![
1933 cx.observe(&buffer, Self::on_buffer_changed),
1934 cx.subscribe(&buffer, Self::on_buffer_event),
1935 cx.observe(&display_map, Self::on_display_map_changed),
1936 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1937 cx.observe_global::<SettingsStore>(Self::settings_changed),
1938 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1939 cx.observe_window_activation(|editor, cx| {
1940 let active = cx.is_window_active();
1941 editor.blink_manager.update(cx, |blink_manager, cx| {
1942 if active {
1943 blink_manager.enable(cx);
1944 } else {
1945 blink_manager.disable(cx);
1946 }
1947 });
1948 }),
1949 ],
1950 tasks_update_task: None,
1951 linked_edit_ranges: Default::default(),
1952 previous_search_ranges: None,
1953 breadcrumb_header: None,
1954 focused_block: None,
1955 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1956 addons: HashMap::default(),
1957 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1958 };
1959 this.tasks_update_task = Some(this.refresh_runnables(cx));
1960 this._subscriptions.extend(project_subscriptions);
1961
1962 this.end_selection(cx);
1963 this.scroll_manager.show_scrollbar(cx);
1964
1965 if mode == EditorMode::Full {
1966 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1967 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1968
1969 if this.git_blame_inline_enabled {
1970 this.git_blame_inline_enabled = true;
1971 this.start_git_blame_inline(false, cx);
1972 }
1973 }
1974
1975 this.report_editor_event("open", None, cx);
1976 this
1977 }
1978
1979 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
1980 self.mouse_context_menu
1981 .as_ref()
1982 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1983 }
1984
1985 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
1986 let mut key_context = KeyContext::new_with_defaults();
1987 key_context.add("Editor");
1988 let mode = match self.mode {
1989 EditorMode::SingleLine { .. } => "single_line",
1990 EditorMode::AutoHeight { .. } => "auto_height",
1991 EditorMode::Full => "full",
1992 };
1993
1994 if EditorSettings::jupyter_enabled(cx) {
1995 key_context.add("jupyter");
1996 }
1997
1998 key_context.set("mode", mode);
1999 if self.pending_rename.is_some() {
2000 key_context.add("renaming");
2001 }
2002 if self.context_menu_visible() {
2003 match self.context_menu.read().as_ref() {
2004 Some(ContextMenu::Completions(_)) => {
2005 key_context.add("menu");
2006 key_context.add("showing_completions")
2007 }
2008 Some(ContextMenu::CodeActions(_)) => {
2009 key_context.add("menu");
2010 key_context.add("showing_code_actions")
2011 }
2012 None => {}
2013 }
2014 }
2015
2016 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2017 if !self.focus_handle(cx).contains_focused(cx)
2018 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2019 {
2020 for addon in self.addons.values() {
2021 addon.extend_key_context(&mut key_context, cx)
2022 }
2023 }
2024
2025 if let Some(extension) = self
2026 .buffer
2027 .read(cx)
2028 .as_singleton()
2029 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2030 {
2031 key_context.set("extension", extension.to_string());
2032 }
2033
2034 if self.has_active_inline_completion(cx) {
2035 key_context.add("copilot_suggestion");
2036 key_context.add("inline_completion");
2037 }
2038
2039 key_context
2040 }
2041
2042 pub fn new_file(
2043 workspace: &mut Workspace,
2044 _: &workspace::NewFile,
2045 cx: &mut ViewContext<Workspace>,
2046 ) {
2047 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2048 "Failed to create buffer",
2049 cx,
2050 |e, _| match e.error_code() {
2051 ErrorCode::RemoteUpgradeRequired => Some(format!(
2052 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2053 e.error_tag("required").unwrap_or("the latest version")
2054 )),
2055 _ => None,
2056 },
2057 );
2058 }
2059
2060 pub fn new_in_workspace(
2061 workspace: &mut Workspace,
2062 cx: &mut ViewContext<Workspace>,
2063 ) -> Task<Result<View<Editor>>> {
2064 let project = workspace.project().clone();
2065 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2066
2067 cx.spawn(|workspace, mut cx| async move {
2068 let buffer = create.await?;
2069 workspace.update(&mut cx, |workspace, cx| {
2070 let editor =
2071 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2072 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2073 editor
2074 })
2075 })
2076 }
2077
2078 fn new_file_vertical(
2079 workspace: &mut Workspace,
2080 _: &workspace::NewFileSplitVertical,
2081 cx: &mut ViewContext<Workspace>,
2082 ) {
2083 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2084 }
2085
2086 fn new_file_horizontal(
2087 workspace: &mut Workspace,
2088 _: &workspace::NewFileSplitHorizontal,
2089 cx: &mut ViewContext<Workspace>,
2090 ) {
2091 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2092 }
2093
2094 fn new_file_in_direction(
2095 workspace: &mut Workspace,
2096 direction: SplitDirection,
2097 cx: &mut ViewContext<Workspace>,
2098 ) {
2099 let project = workspace.project().clone();
2100 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2101
2102 cx.spawn(|workspace, mut cx| async move {
2103 let buffer = create.await?;
2104 workspace.update(&mut cx, move |workspace, cx| {
2105 workspace.split_item(
2106 direction,
2107 Box::new(
2108 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2109 ),
2110 cx,
2111 )
2112 })?;
2113 anyhow::Ok(())
2114 })
2115 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2116 ErrorCode::RemoteUpgradeRequired => Some(format!(
2117 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2118 e.error_tag("required").unwrap_or("the latest version")
2119 )),
2120 _ => None,
2121 });
2122 }
2123
2124 pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
2125 self.buffer.read(cx).replica_id()
2126 }
2127
2128 pub fn leader_peer_id(&self) -> Option<PeerId> {
2129 self.leader_peer_id
2130 }
2131
2132 pub fn buffer(&self) -> &Model<MultiBuffer> {
2133 &self.buffer
2134 }
2135
2136 pub fn workspace(&self) -> Option<View<Workspace>> {
2137 self.workspace.as_ref()?.0.upgrade()
2138 }
2139
2140 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2141 self.buffer().read(cx).title(cx)
2142 }
2143
2144 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2145 EditorSnapshot {
2146 mode: self.mode,
2147 show_gutter: self.show_gutter,
2148 show_line_numbers: self.show_line_numbers,
2149 show_git_diff_gutter: self.show_git_diff_gutter,
2150 show_code_actions: self.show_code_actions,
2151 show_runnables: self.show_runnables,
2152 render_git_blame_gutter: self.render_git_blame_gutter(cx),
2153 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2154 scroll_anchor: self.scroll_manager.anchor(),
2155 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2156 placeholder_text: self.placeholder_text.clone(),
2157 is_focused: self.focus_handle.is_focused(cx),
2158 current_line_highlight: self
2159 .current_line_highlight
2160 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2161 gutter_hovered: self.gutter_hovered,
2162 }
2163 }
2164
2165 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2166 self.buffer.read(cx).language_at(point, cx)
2167 }
2168
2169 pub fn file_at<T: ToOffset>(
2170 &self,
2171 point: T,
2172 cx: &AppContext,
2173 ) -> Option<Arc<dyn language::File>> {
2174 self.buffer.read(cx).read(cx).file_at(point).cloned()
2175 }
2176
2177 pub fn active_excerpt(
2178 &self,
2179 cx: &AppContext,
2180 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2181 self.buffer
2182 .read(cx)
2183 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2184 }
2185
2186 pub fn mode(&self) -> EditorMode {
2187 self.mode
2188 }
2189
2190 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2191 self.collaboration_hub.as_deref()
2192 }
2193
2194 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2195 self.collaboration_hub = Some(hub);
2196 }
2197
2198 pub fn set_custom_context_menu(
2199 &mut self,
2200 f: impl 'static
2201 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2202 ) {
2203 self.custom_context_menu = Some(Box::new(f))
2204 }
2205
2206 pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
2207 self.completion_provider = Some(provider);
2208 }
2209
2210 pub fn set_inline_completion_provider<T>(
2211 &mut self,
2212 provider: Option<Model<T>>,
2213 cx: &mut ViewContext<Self>,
2214 ) where
2215 T: InlineCompletionProvider,
2216 {
2217 self.inline_completion_provider =
2218 provider.map(|provider| RegisteredInlineCompletionProvider {
2219 _subscription: cx.observe(&provider, |this, _, cx| {
2220 if this.focus_handle.is_focused(cx) {
2221 this.update_visible_inline_completion(cx);
2222 }
2223 }),
2224 provider: Arc::new(provider),
2225 });
2226 self.refresh_inline_completion(false, false, cx);
2227 }
2228
2229 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2230 self.placeholder_text.as_deref()
2231 }
2232
2233 pub fn set_placeholder_text(
2234 &mut self,
2235 placeholder_text: impl Into<Arc<str>>,
2236 cx: &mut ViewContext<Self>,
2237 ) {
2238 let placeholder_text = Some(placeholder_text.into());
2239 if self.placeholder_text != placeholder_text {
2240 self.placeholder_text = placeholder_text;
2241 cx.notify();
2242 }
2243 }
2244
2245 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2246 self.cursor_shape = cursor_shape;
2247
2248 // Disrupt blink for immediate user feedback that the cursor shape has changed
2249 self.blink_manager.update(cx, BlinkManager::show_cursor);
2250
2251 cx.notify();
2252 }
2253
2254 pub fn set_current_line_highlight(
2255 &mut self,
2256 current_line_highlight: Option<CurrentLineHighlight>,
2257 ) {
2258 self.current_line_highlight = current_line_highlight;
2259 }
2260
2261 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2262 self.collapse_matches = collapse_matches;
2263 }
2264
2265 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2266 if self.collapse_matches {
2267 return range.start..range.start;
2268 }
2269 range.clone()
2270 }
2271
2272 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2273 if self.display_map.read(cx).clip_at_line_ends != clip {
2274 self.display_map
2275 .update(cx, |map, _| map.clip_at_line_ends = clip);
2276 }
2277 }
2278
2279 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2280 self.input_enabled = input_enabled;
2281 }
2282
2283 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
2284 self.enable_inline_completions = enabled;
2285 }
2286
2287 pub fn set_autoindent(&mut self, autoindent: bool) {
2288 if autoindent {
2289 self.autoindent_mode = Some(AutoindentMode::EachLine);
2290 } else {
2291 self.autoindent_mode = None;
2292 }
2293 }
2294
2295 pub fn read_only(&self, cx: &AppContext) -> bool {
2296 self.read_only || self.buffer.read(cx).read_only()
2297 }
2298
2299 pub fn set_read_only(&mut self, read_only: bool) {
2300 self.read_only = read_only;
2301 }
2302
2303 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2304 self.use_autoclose = autoclose;
2305 }
2306
2307 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2308 self.use_auto_surround = auto_surround;
2309 }
2310
2311 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2312 self.auto_replace_emoji_shortcode = auto_replace;
2313 }
2314
2315 pub fn toggle_inline_completions(
2316 &mut self,
2317 _: &ToggleInlineCompletions,
2318 cx: &mut ViewContext<Self>,
2319 ) {
2320 if self.show_inline_completions_override.is_some() {
2321 self.set_show_inline_completions(None, cx);
2322 } else {
2323 let cursor = self.selections.newest_anchor().head();
2324 if let Some((buffer, cursor_buffer_position)) =
2325 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2326 {
2327 let show_inline_completions =
2328 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2329 self.set_show_inline_completions(Some(show_inline_completions), cx);
2330 }
2331 }
2332 }
2333
2334 pub fn set_show_inline_completions(
2335 &mut self,
2336 show_inline_completions: Option<bool>,
2337 cx: &mut ViewContext<Self>,
2338 ) {
2339 self.show_inline_completions_override = show_inline_completions;
2340 self.refresh_inline_completion(false, true, cx);
2341 }
2342
2343 fn should_show_inline_completions(
2344 &self,
2345 buffer: &Model<Buffer>,
2346 buffer_position: language::Anchor,
2347 cx: &AppContext,
2348 ) -> bool {
2349 if let Some(provider) = self.inline_completion_provider() {
2350 if let Some(show_inline_completions) = self.show_inline_completions_override {
2351 show_inline_completions
2352 } else {
2353 self.mode == EditorMode::Full && provider.is_enabled(&buffer, buffer_position, cx)
2354 }
2355 } else {
2356 false
2357 }
2358 }
2359
2360 pub fn set_use_modal_editing(&mut self, to: bool) {
2361 self.use_modal_editing = to;
2362 }
2363
2364 pub fn use_modal_editing(&self) -> bool {
2365 self.use_modal_editing
2366 }
2367
2368 fn selections_did_change(
2369 &mut self,
2370 local: bool,
2371 old_cursor_position: &Anchor,
2372 show_completions: bool,
2373 cx: &mut ViewContext<Self>,
2374 ) {
2375 cx.invalidate_character_coordinates();
2376
2377 // Copy selections to primary selection buffer
2378 #[cfg(target_os = "linux")]
2379 if local {
2380 let selections = self.selections.all::<usize>(cx);
2381 let buffer_handle = self.buffer.read(cx).read(cx);
2382
2383 let mut text = String::new();
2384 for (index, selection) in selections.iter().enumerate() {
2385 let text_for_selection = buffer_handle
2386 .text_for_range(selection.start..selection.end)
2387 .collect::<String>();
2388
2389 text.push_str(&text_for_selection);
2390 if index != selections.len() - 1 {
2391 text.push('\n');
2392 }
2393 }
2394
2395 if !text.is_empty() {
2396 cx.write_to_primary(ClipboardItem::new_string(text));
2397 }
2398 }
2399
2400 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2401 self.buffer.update(cx, |buffer, cx| {
2402 buffer.set_active_selections(
2403 &self.selections.disjoint_anchors(),
2404 self.selections.line_mode,
2405 self.cursor_shape,
2406 cx,
2407 )
2408 });
2409 }
2410 let display_map = self
2411 .display_map
2412 .update(cx, |display_map, cx| display_map.snapshot(cx));
2413 let buffer = &display_map.buffer_snapshot;
2414 self.add_selections_state = None;
2415 self.select_next_state = None;
2416 self.select_prev_state = None;
2417 self.select_larger_syntax_node_stack.clear();
2418 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2419 self.snippet_stack
2420 .invalidate(&self.selections.disjoint_anchors(), buffer);
2421 self.take_rename(false, cx);
2422
2423 let new_cursor_position = self.selections.newest_anchor().head();
2424
2425 self.push_to_nav_history(
2426 *old_cursor_position,
2427 Some(new_cursor_position.to_point(buffer)),
2428 cx,
2429 );
2430
2431 if local {
2432 let new_cursor_position = self.selections.newest_anchor().head();
2433 let mut context_menu = self.context_menu.write();
2434 let completion_menu = match context_menu.as_ref() {
2435 Some(ContextMenu::Completions(menu)) => Some(menu),
2436
2437 _ => {
2438 *context_menu = None;
2439 None
2440 }
2441 };
2442
2443 if let Some(completion_menu) = completion_menu {
2444 let cursor_position = new_cursor_position.to_offset(buffer);
2445 let (word_range, kind) =
2446 buffer.surrounding_word(completion_menu.initial_position, true);
2447 if kind == Some(CharKind::Word)
2448 && word_range.to_inclusive().contains(&cursor_position)
2449 {
2450 let mut completion_menu = completion_menu.clone();
2451 drop(context_menu);
2452
2453 let query = Self::completion_query(buffer, cursor_position);
2454 cx.spawn(move |this, mut cx| async move {
2455 completion_menu
2456 .filter(query.as_deref(), cx.background_executor().clone())
2457 .await;
2458
2459 this.update(&mut cx, |this, cx| {
2460 let mut context_menu = this.context_menu.write();
2461 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2462 return;
2463 };
2464
2465 if menu.id > completion_menu.id {
2466 return;
2467 }
2468
2469 *context_menu = Some(ContextMenu::Completions(completion_menu));
2470 drop(context_menu);
2471 cx.notify();
2472 })
2473 })
2474 .detach();
2475
2476 if show_completions {
2477 self.show_completions(&ShowCompletions { trigger: None }, cx);
2478 }
2479 } else {
2480 drop(context_menu);
2481 self.hide_context_menu(cx);
2482 }
2483 } else {
2484 drop(context_menu);
2485 }
2486
2487 hide_hover(self, cx);
2488
2489 if old_cursor_position.to_display_point(&display_map).row()
2490 != new_cursor_position.to_display_point(&display_map).row()
2491 {
2492 self.available_code_actions.take();
2493 }
2494 self.refresh_code_actions(cx);
2495 self.refresh_document_highlights(cx);
2496 refresh_matching_bracket_highlights(self, cx);
2497 self.discard_inline_completion(false, cx);
2498 linked_editing_ranges::refresh_linked_ranges(self, cx);
2499 if self.git_blame_inline_enabled {
2500 self.start_inline_blame_timer(cx);
2501 }
2502 }
2503
2504 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2505 cx.emit(EditorEvent::SelectionsChanged { local });
2506
2507 if self.selections.disjoint_anchors().len() == 1 {
2508 cx.emit(SearchEvent::ActiveMatchChanged)
2509 }
2510 cx.notify();
2511 }
2512
2513 pub fn change_selections<R>(
2514 &mut self,
2515 autoscroll: Option<Autoscroll>,
2516 cx: &mut ViewContext<Self>,
2517 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2518 ) -> R {
2519 self.change_selections_inner(autoscroll, true, cx, change)
2520 }
2521
2522 pub fn change_selections_inner<R>(
2523 &mut self,
2524 autoscroll: Option<Autoscroll>,
2525 request_completions: bool,
2526 cx: &mut ViewContext<Self>,
2527 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2528 ) -> R {
2529 let old_cursor_position = self.selections.newest_anchor().head();
2530 self.push_to_selection_history();
2531
2532 let (changed, result) = self.selections.change_with(cx, change);
2533
2534 if changed {
2535 if let Some(autoscroll) = autoscroll {
2536 self.request_autoscroll(autoscroll, cx);
2537 }
2538 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2539
2540 if self.should_open_signature_help_automatically(
2541 &old_cursor_position,
2542 self.signature_help_state.backspace_pressed(),
2543 cx,
2544 ) {
2545 self.show_signature_help(&ShowSignatureHelp, cx);
2546 }
2547 self.signature_help_state.set_backspace_pressed(false);
2548 }
2549
2550 result
2551 }
2552
2553 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2554 where
2555 I: IntoIterator<Item = (Range<S>, T)>,
2556 S: ToOffset,
2557 T: Into<Arc<str>>,
2558 {
2559 if self.read_only(cx) {
2560 return;
2561 }
2562
2563 self.buffer
2564 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2565 }
2566
2567 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2568 where
2569 I: IntoIterator<Item = (Range<S>, T)>,
2570 S: ToOffset,
2571 T: Into<Arc<str>>,
2572 {
2573 if self.read_only(cx) {
2574 return;
2575 }
2576
2577 self.buffer.update(cx, |buffer, cx| {
2578 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2579 });
2580 }
2581
2582 pub fn edit_with_block_indent<I, S, T>(
2583 &mut self,
2584 edits: I,
2585 original_indent_columns: Vec<u32>,
2586 cx: &mut ViewContext<Self>,
2587 ) where
2588 I: IntoIterator<Item = (Range<S>, T)>,
2589 S: ToOffset,
2590 T: Into<Arc<str>>,
2591 {
2592 if self.read_only(cx) {
2593 return;
2594 }
2595
2596 self.buffer.update(cx, |buffer, cx| {
2597 buffer.edit(
2598 edits,
2599 Some(AutoindentMode::Block {
2600 original_indent_columns,
2601 }),
2602 cx,
2603 )
2604 });
2605 }
2606
2607 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2608 self.hide_context_menu(cx);
2609
2610 match phase {
2611 SelectPhase::Begin {
2612 position,
2613 add,
2614 click_count,
2615 } => self.begin_selection(position, add, click_count, cx),
2616 SelectPhase::BeginColumnar {
2617 position,
2618 goal_column,
2619 reset,
2620 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2621 SelectPhase::Extend {
2622 position,
2623 click_count,
2624 } => self.extend_selection(position, click_count, cx),
2625 SelectPhase::Update {
2626 position,
2627 goal_column,
2628 scroll_delta,
2629 } => self.update_selection(position, goal_column, scroll_delta, cx),
2630 SelectPhase::End => self.end_selection(cx),
2631 }
2632 }
2633
2634 fn extend_selection(
2635 &mut self,
2636 position: DisplayPoint,
2637 click_count: usize,
2638 cx: &mut ViewContext<Self>,
2639 ) {
2640 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2641 let tail = self.selections.newest::<usize>(cx).tail();
2642 self.begin_selection(position, false, click_count, cx);
2643
2644 let position = position.to_offset(&display_map, Bias::Left);
2645 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2646
2647 let mut pending_selection = self
2648 .selections
2649 .pending_anchor()
2650 .expect("extend_selection not called with pending selection");
2651 if position >= tail {
2652 pending_selection.start = tail_anchor;
2653 } else {
2654 pending_selection.end = tail_anchor;
2655 pending_selection.reversed = true;
2656 }
2657
2658 let mut pending_mode = self.selections.pending_mode().unwrap();
2659 match &mut pending_mode {
2660 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2661 _ => {}
2662 }
2663
2664 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2665 s.set_pending(pending_selection, pending_mode)
2666 });
2667 }
2668
2669 fn begin_selection(
2670 &mut self,
2671 position: DisplayPoint,
2672 add: bool,
2673 click_count: usize,
2674 cx: &mut ViewContext<Self>,
2675 ) {
2676 if !self.focus_handle.is_focused(cx) {
2677 self.last_focused_descendant = None;
2678 cx.focus(&self.focus_handle);
2679 }
2680
2681 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2682 let buffer = &display_map.buffer_snapshot;
2683 let newest_selection = self.selections.newest_anchor().clone();
2684 let position = display_map.clip_point(position, Bias::Left);
2685
2686 let start;
2687 let end;
2688 let mode;
2689 let auto_scroll;
2690 match click_count {
2691 1 => {
2692 start = buffer.anchor_before(position.to_point(&display_map));
2693 end = start;
2694 mode = SelectMode::Character;
2695 auto_scroll = true;
2696 }
2697 2 => {
2698 let range = movement::surrounding_word(&display_map, position);
2699 start = buffer.anchor_before(range.start.to_point(&display_map));
2700 end = buffer.anchor_before(range.end.to_point(&display_map));
2701 mode = SelectMode::Word(start..end);
2702 auto_scroll = true;
2703 }
2704 3 => {
2705 let position = display_map
2706 .clip_point(position, Bias::Left)
2707 .to_point(&display_map);
2708 let line_start = display_map.prev_line_boundary(position).0;
2709 let next_line_start = buffer.clip_point(
2710 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2711 Bias::Left,
2712 );
2713 start = buffer.anchor_before(line_start);
2714 end = buffer.anchor_before(next_line_start);
2715 mode = SelectMode::Line(start..end);
2716 auto_scroll = true;
2717 }
2718 _ => {
2719 start = buffer.anchor_before(0);
2720 end = buffer.anchor_before(buffer.len());
2721 mode = SelectMode::All;
2722 auto_scroll = false;
2723 }
2724 }
2725
2726 let point_to_delete: Option<usize> = {
2727 let selected_points: Vec<Selection<Point>> =
2728 self.selections.disjoint_in_range(start..end, cx);
2729
2730 if !add || click_count > 1 {
2731 None
2732 } else if selected_points.len() > 0 {
2733 Some(selected_points[0].id)
2734 } else {
2735 let clicked_point_already_selected =
2736 self.selections.disjoint.iter().find(|selection| {
2737 selection.start.to_point(buffer) == start.to_point(buffer)
2738 || selection.end.to_point(buffer) == end.to_point(buffer)
2739 });
2740
2741 if let Some(selection) = clicked_point_already_selected {
2742 Some(selection.id)
2743 } else {
2744 None
2745 }
2746 }
2747 };
2748
2749 let selections_count = self.selections.count();
2750
2751 self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
2752 if let Some(point_to_delete) = point_to_delete {
2753 s.delete(point_to_delete);
2754
2755 if selections_count == 1 {
2756 s.set_pending_anchor_range(start..end, mode);
2757 }
2758 } else {
2759 if !add {
2760 s.clear_disjoint();
2761 } else if click_count > 1 {
2762 s.delete(newest_selection.id)
2763 }
2764
2765 s.set_pending_anchor_range(start..end, mode);
2766 }
2767 });
2768 }
2769
2770 fn begin_columnar_selection(
2771 &mut self,
2772 position: DisplayPoint,
2773 goal_column: u32,
2774 reset: bool,
2775 cx: &mut ViewContext<Self>,
2776 ) {
2777 if !self.focus_handle.is_focused(cx) {
2778 self.last_focused_descendant = None;
2779 cx.focus(&self.focus_handle);
2780 }
2781
2782 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2783
2784 if reset {
2785 let pointer_position = display_map
2786 .buffer_snapshot
2787 .anchor_before(position.to_point(&display_map));
2788
2789 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2790 s.clear_disjoint();
2791 s.set_pending_anchor_range(
2792 pointer_position..pointer_position,
2793 SelectMode::Character,
2794 );
2795 });
2796 }
2797
2798 let tail = self.selections.newest::<Point>(cx).tail();
2799 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2800
2801 if !reset {
2802 self.select_columns(
2803 tail.to_display_point(&display_map),
2804 position,
2805 goal_column,
2806 &display_map,
2807 cx,
2808 );
2809 }
2810 }
2811
2812 fn update_selection(
2813 &mut self,
2814 position: DisplayPoint,
2815 goal_column: u32,
2816 scroll_delta: gpui::Point<f32>,
2817 cx: &mut ViewContext<Self>,
2818 ) {
2819 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2820
2821 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2822 let tail = tail.to_display_point(&display_map);
2823 self.select_columns(tail, position, goal_column, &display_map, cx);
2824 } else if let Some(mut pending) = self.selections.pending_anchor() {
2825 let buffer = self.buffer.read(cx).snapshot(cx);
2826 let head;
2827 let tail;
2828 let mode = self.selections.pending_mode().unwrap();
2829 match &mode {
2830 SelectMode::Character => {
2831 head = position.to_point(&display_map);
2832 tail = pending.tail().to_point(&buffer);
2833 }
2834 SelectMode::Word(original_range) => {
2835 let original_display_range = original_range.start.to_display_point(&display_map)
2836 ..original_range.end.to_display_point(&display_map);
2837 let original_buffer_range = original_display_range.start.to_point(&display_map)
2838 ..original_display_range.end.to_point(&display_map);
2839 if movement::is_inside_word(&display_map, position)
2840 || original_display_range.contains(&position)
2841 {
2842 let word_range = movement::surrounding_word(&display_map, position);
2843 if word_range.start < original_display_range.start {
2844 head = word_range.start.to_point(&display_map);
2845 } else {
2846 head = word_range.end.to_point(&display_map);
2847 }
2848 } else {
2849 head = position.to_point(&display_map);
2850 }
2851
2852 if head <= original_buffer_range.start {
2853 tail = original_buffer_range.end;
2854 } else {
2855 tail = original_buffer_range.start;
2856 }
2857 }
2858 SelectMode::Line(original_range) => {
2859 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2860
2861 let position = display_map
2862 .clip_point(position, Bias::Left)
2863 .to_point(&display_map);
2864 let line_start = display_map.prev_line_boundary(position).0;
2865 let next_line_start = buffer.clip_point(
2866 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2867 Bias::Left,
2868 );
2869
2870 if line_start < original_range.start {
2871 head = line_start
2872 } else {
2873 head = next_line_start
2874 }
2875
2876 if head <= original_range.start {
2877 tail = original_range.end;
2878 } else {
2879 tail = original_range.start;
2880 }
2881 }
2882 SelectMode::All => {
2883 return;
2884 }
2885 };
2886
2887 if head < tail {
2888 pending.start = buffer.anchor_before(head);
2889 pending.end = buffer.anchor_before(tail);
2890 pending.reversed = true;
2891 } else {
2892 pending.start = buffer.anchor_before(tail);
2893 pending.end = buffer.anchor_before(head);
2894 pending.reversed = false;
2895 }
2896
2897 self.change_selections(None, cx, |s| {
2898 s.set_pending(pending, mode);
2899 });
2900 } else {
2901 log::error!("update_selection dispatched with no pending selection");
2902 return;
2903 }
2904
2905 self.apply_scroll_delta(scroll_delta, cx);
2906 cx.notify();
2907 }
2908
2909 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2910 self.columnar_selection_tail.take();
2911 if self.selections.pending_anchor().is_some() {
2912 let selections = self.selections.all::<usize>(cx);
2913 self.change_selections(None, cx, |s| {
2914 s.select(selections);
2915 s.clear_pending();
2916 });
2917 }
2918 }
2919
2920 fn select_columns(
2921 &mut self,
2922 tail: DisplayPoint,
2923 head: DisplayPoint,
2924 goal_column: u32,
2925 display_map: &DisplaySnapshot,
2926 cx: &mut ViewContext<Self>,
2927 ) {
2928 let start_row = cmp::min(tail.row(), head.row());
2929 let end_row = cmp::max(tail.row(), head.row());
2930 let start_column = cmp::min(tail.column(), goal_column);
2931 let end_column = cmp::max(tail.column(), goal_column);
2932 let reversed = start_column < tail.column();
2933
2934 let selection_ranges = (start_row.0..=end_row.0)
2935 .map(DisplayRow)
2936 .filter_map(|row| {
2937 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2938 let start = display_map
2939 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2940 .to_point(display_map);
2941 let end = display_map
2942 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2943 .to_point(display_map);
2944 if reversed {
2945 Some(end..start)
2946 } else {
2947 Some(start..end)
2948 }
2949 } else {
2950 None
2951 }
2952 })
2953 .collect::<Vec<_>>();
2954
2955 self.change_selections(None, cx, |s| {
2956 s.select_ranges(selection_ranges);
2957 });
2958 cx.notify();
2959 }
2960
2961 pub fn has_pending_nonempty_selection(&self) -> bool {
2962 let pending_nonempty_selection = match self.selections.pending_anchor() {
2963 Some(Selection { start, end, .. }) => start != end,
2964 None => false,
2965 };
2966
2967 pending_nonempty_selection
2968 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2969 }
2970
2971 pub fn has_pending_selection(&self) -> bool {
2972 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2973 }
2974
2975 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2976 if self.clear_clicked_diff_hunks(cx) {
2977 cx.notify();
2978 return;
2979 }
2980 if self.dismiss_menus_and_popups(true, cx) {
2981 return;
2982 }
2983
2984 if self.mode == EditorMode::Full {
2985 if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
2986 return;
2987 }
2988 }
2989
2990 cx.propagate();
2991 }
2992
2993 pub fn dismiss_menus_and_popups(
2994 &mut self,
2995 should_report_inline_completion_event: bool,
2996 cx: &mut ViewContext<Self>,
2997 ) -> bool {
2998 if self.take_rename(false, cx).is_some() {
2999 return true;
3000 }
3001
3002 if hide_hover(self, cx) {
3003 return true;
3004 }
3005
3006 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3007 return true;
3008 }
3009
3010 if self.hide_context_menu(cx).is_some() {
3011 return true;
3012 }
3013
3014 if self.mouse_context_menu.take().is_some() {
3015 return true;
3016 }
3017
3018 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3019 return true;
3020 }
3021
3022 if self.snippet_stack.pop().is_some() {
3023 return true;
3024 }
3025
3026 if self.mode == EditorMode::Full {
3027 if self.active_diagnostics.is_some() {
3028 self.dismiss_diagnostics(cx);
3029 return true;
3030 }
3031 }
3032
3033 false
3034 }
3035
3036 fn linked_editing_ranges_for(
3037 &self,
3038 selection: Range<text::Anchor>,
3039 cx: &AppContext,
3040 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3041 if self.linked_edit_ranges.is_empty() {
3042 return None;
3043 }
3044 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3045 selection.end.buffer_id.and_then(|end_buffer_id| {
3046 if selection.start.buffer_id != Some(end_buffer_id) {
3047 return None;
3048 }
3049 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3050 let snapshot = buffer.read(cx).snapshot();
3051 self.linked_edit_ranges
3052 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3053 .map(|ranges| (ranges, snapshot, buffer))
3054 })?;
3055 use text::ToOffset as TO;
3056 // find offset from the start of current range to current cursor position
3057 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3058
3059 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3060 let start_difference = start_offset - start_byte_offset;
3061 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3062 let end_difference = end_offset - start_byte_offset;
3063 // Current range has associated linked ranges.
3064 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3065 for range in linked_ranges.iter() {
3066 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3067 let end_offset = start_offset + end_difference;
3068 let start_offset = start_offset + start_difference;
3069 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3070 continue;
3071 }
3072 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3073 if s.start.buffer_id != selection.start.buffer_id
3074 || s.end.buffer_id != selection.end.buffer_id
3075 {
3076 return false;
3077 }
3078 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3079 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3080 }) {
3081 continue;
3082 }
3083 let start = buffer_snapshot.anchor_after(start_offset);
3084 let end = buffer_snapshot.anchor_after(end_offset);
3085 linked_edits
3086 .entry(buffer.clone())
3087 .or_default()
3088 .push(start..end);
3089 }
3090 Some(linked_edits)
3091 }
3092
3093 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3094 let text: Arc<str> = text.into();
3095
3096 if self.read_only(cx) {
3097 return;
3098 }
3099
3100 let selections = self.selections.all_adjusted(cx);
3101 let mut bracket_inserted = false;
3102 let mut edits = Vec::new();
3103 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3104 let mut new_selections = Vec::with_capacity(selections.len());
3105 let mut new_autoclose_regions = Vec::new();
3106 let snapshot = self.buffer.read(cx).read(cx);
3107
3108 for (selection, autoclose_region) in
3109 self.selections_with_autoclose_regions(selections, &snapshot)
3110 {
3111 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3112 // Determine if the inserted text matches the opening or closing
3113 // bracket of any of this language's bracket pairs.
3114 let mut bracket_pair = None;
3115 let mut is_bracket_pair_start = false;
3116 let mut is_bracket_pair_end = false;
3117 if !text.is_empty() {
3118 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3119 // and they are removing the character that triggered IME popup.
3120 for (pair, enabled) in scope.brackets() {
3121 if !pair.close && !pair.surround {
3122 continue;
3123 }
3124
3125 if enabled && pair.start.ends_with(text.as_ref()) {
3126 bracket_pair = Some(pair.clone());
3127 is_bracket_pair_start = true;
3128 break;
3129 }
3130 if pair.end.as_str() == text.as_ref() {
3131 bracket_pair = Some(pair.clone());
3132 is_bracket_pair_end = true;
3133 break;
3134 }
3135 }
3136 }
3137
3138 if let Some(bracket_pair) = bracket_pair {
3139 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3140 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3141 let auto_surround =
3142 self.use_auto_surround && snapshot_settings.use_auto_surround;
3143 if selection.is_empty() {
3144 if is_bracket_pair_start {
3145 let prefix_len = bracket_pair.start.len() - text.len();
3146
3147 // If the inserted text is a suffix of an opening bracket and the
3148 // selection is preceded by the rest of the opening bracket, then
3149 // insert the closing bracket.
3150 let following_text_allows_autoclose = snapshot
3151 .chars_at(selection.start)
3152 .next()
3153 .map_or(true, |c| scope.should_autoclose_before(c));
3154 let preceding_text_matches_prefix = prefix_len == 0
3155 || (selection.start.column >= (prefix_len as u32)
3156 && snapshot.contains_str_at(
3157 Point::new(
3158 selection.start.row,
3159 selection.start.column - (prefix_len as u32),
3160 ),
3161 &bracket_pair.start[..prefix_len],
3162 ));
3163
3164 if autoclose
3165 && bracket_pair.close
3166 && following_text_allows_autoclose
3167 && preceding_text_matches_prefix
3168 {
3169 let anchor = snapshot.anchor_before(selection.end);
3170 new_selections.push((selection.map(|_| anchor), text.len()));
3171 new_autoclose_regions.push((
3172 anchor,
3173 text.len(),
3174 selection.id,
3175 bracket_pair.clone(),
3176 ));
3177 edits.push((
3178 selection.range(),
3179 format!("{}{}", text, bracket_pair.end).into(),
3180 ));
3181 bracket_inserted = true;
3182 continue;
3183 }
3184 }
3185
3186 if let Some(region) = autoclose_region {
3187 // If the selection is followed by an auto-inserted closing bracket,
3188 // then don't insert that closing bracket again; just move the selection
3189 // past the closing bracket.
3190 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3191 && text.as_ref() == region.pair.end.as_str();
3192 if should_skip {
3193 let anchor = snapshot.anchor_after(selection.end);
3194 new_selections
3195 .push((selection.map(|_| anchor), region.pair.end.len()));
3196 continue;
3197 }
3198 }
3199
3200 let always_treat_brackets_as_autoclosed = snapshot
3201 .settings_at(selection.start, cx)
3202 .always_treat_brackets_as_autoclosed;
3203 if always_treat_brackets_as_autoclosed
3204 && is_bracket_pair_end
3205 && snapshot.contains_str_at(selection.end, text.as_ref())
3206 {
3207 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3208 // and the inserted text is a closing bracket and the selection is followed
3209 // by the closing bracket then move the selection past the closing bracket.
3210 let anchor = snapshot.anchor_after(selection.end);
3211 new_selections.push((selection.map(|_| anchor), text.len()));
3212 continue;
3213 }
3214 }
3215 // If an opening bracket is 1 character long and is typed while
3216 // text is selected, then surround that text with the bracket pair.
3217 else if auto_surround
3218 && bracket_pair.surround
3219 && is_bracket_pair_start
3220 && bracket_pair.start.chars().count() == 1
3221 {
3222 edits.push((selection.start..selection.start, text.clone()));
3223 edits.push((
3224 selection.end..selection.end,
3225 bracket_pair.end.as_str().into(),
3226 ));
3227 bracket_inserted = true;
3228 new_selections.push((
3229 Selection {
3230 id: selection.id,
3231 start: snapshot.anchor_after(selection.start),
3232 end: snapshot.anchor_before(selection.end),
3233 reversed: selection.reversed,
3234 goal: selection.goal,
3235 },
3236 0,
3237 ));
3238 continue;
3239 }
3240 }
3241 }
3242
3243 if self.auto_replace_emoji_shortcode
3244 && selection.is_empty()
3245 && text.as_ref().ends_with(':')
3246 {
3247 if let Some(possible_emoji_short_code) =
3248 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3249 {
3250 if !possible_emoji_short_code.is_empty() {
3251 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3252 let emoji_shortcode_start = Point::new(
3253 selection.start.row,
3254 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3255 );
3256
3257 // Remove shortcode from buffer
3258 edits.push((
3259 emoji_shortcode_start..selection.start,
3260 "".to_string().into(),
3261 ));
3262 new_selections.push((
3263 Selection {
3264 id: selection.id,
3265 start: snapshot.anchor_after(emoji_shortcode_start),
3266 end: snapshot.anchor_before(selection.start),
3267 reversed: selection.reversed,
3268 goal: selection.goal,
3269 },
3270 0,
3271 ));
3272
3273 // Insert emoji
3274 let selection_start_anchor = snapshot.anchor_after(selection.start);
3275 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3276 edits.push((selection.start..selection.end, emoji.to_string().into()));
3277
3278 continue;
3279 }
3280 }
3281 }
3282 }
3283
3284 // If not handling any auto-close operation, then just replace the selected
3285 // text with the given input and move the selection to the end of the
3286 // newly inserted text.
3287 let anchor = snapshot.anchor_after(selection.end);
3288 if !self.linked_edit_ranges.is_empty() {
3289 let start_anchor = snapshot.anchor_before(selection.start);
3290
3291 let is_word_char = text.chars().next().map_or(true, |char| {
3292 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3293 classifier.is_word(char)
3294 });
3295
3296 if is_word_char {
3297 if let Some(ranges) = self
3298 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3299 {
3300 for (buffer, edits) in ranges {
3301 linked_edits
3302 .entry(buffer.clone())
3303 .or_default()
3304 .extend(edits.into_iter().map(|range| (range, text.clone())));
3305 }
3306 }
3307 }
3308 }
3309
3310 new_selections.push((selection.map(|_| anchor), 0));
3311 edits.push((selection.start..selection.end, text.clone()));
3312 }
3313
3314 drop(snapshot);
3315
3316 self.transact(cx, |this, cx| {
3317 this.buffer.update(cx, |buffer, cx| {
3318 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3319 });
3320 for (buffer, edits) in linked_edits {
3321 buffer.update(cx, |buffer, cx| {
3322 let snapshot = buffer.snapshot();
3323 let edits = edits
3324 .into_iter()
3325 .map(|(range, text)| {
3326 use text::ToPoint as TP;
3327 let end_point = TP::to_point(&range.end, &snapshot);
3328 let start_point = TP::to_point(&range.start, &snapshot);
3329 (start_point..end_point, text)
3330 })
3331 .sorted_by_key(|(range, _)| range.start)
3332 .collect::<Vec<_>>();
3333 buffer.edit(edits, None, cx);
3334 })
3335 }
3336 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3337 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3338 let snapshot = this.buffer.read(cx).read(cx);
3339 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3340 .zip(new_selection_deltas)
3341 .map(|(selection, delta)| Selection {
3342 id: selection.id,
3343 start: selection.start + delta,
3344 end: selection.end + delta,
3345 reversed: selection.reversed,
3346 goal: SelectionGoal::None,
3347 })
3348 .collect::<Vec<_>>();
3349
3350 let mut i = 0;
3351 for (position, delta, selection_id, pair) in new_autoclose_regions {
3352 let position = position.to_offset(&snapshot) + delta;
3353 let start = snapshot.anchor_before(position);
3354 let end = snapshot.anchor_after(position);
3355 while let Some(existing_state) = this.autoclose_regions.get(i) {
3356 match existing_state.range.start.cmp(&start, &snapshot) {
3357 Ordering::Less => i += 1,
3358 Ordering::Greater => break,
3359 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3360 Ordering::Less => i += 1,
3361 Ordering::Equal => break,
3362 Ordering::Greater => break,
3363 },
3364 }
3365 }
3366 this.autoclose_regions.insert(
3367 i,
3368 AutocloseRegion {
3369 selection_id,
3370 range: start..end,
3371 pair,
3372 },
3373 );
3374 }
3375
3376 drop(snapshot);
3377 let had_active_inline_completion = this.has_active_inline_completion(cx);
3378 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3379 s.select(new_selections)
3380 });
3381
3382 if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
3383 if let Some(on_type_format_task) =
3384 this.trigger_on_type_formatting(text.to_string(), cx)
3385 {
3386 on_type_format_task.detach_and_log_err(cx);
3387 }
3388 }
3389
3390 let editor_settings = EditorSettings::get_global(cx);
3391 if bracket_inserted
3392 && (editor_settings.auto_signature_help
3393 || editor_settings.show_signature_help_after_edits)
3394 {
3395 this.show_signature_help(&ShowSignatureHelp, cx);
3396 }
3397
3398 let trigger_in_words = !had_active_inline_completion;
3399 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3400 linked_editing_ranges::refresh_linked_ranges(this, cx);
3401 this.refresh_inline_completion(true, false, cx);
3402 });
3403 }
3404
3405 fn find_possible_emoji_shortcode_at_position(
3406 snapshot: &MultiBufferSnapshot,
3407 position: Point,
3408 ) -> Option<String> {
3409 let mut chars = Vec::new();
3410 let mut found_colon = false;
3411 for char in snapshot.reversed_chars_at(position).take(100) {
3412 // Found a possible emoji shortcode in the middle of the buffer
3413 if found_colon {
3414 if char.is_whitespace() {
3415 chars.reverse();
3416 return Some(chars.iter().collect());
3417 }
3418 // If the previous character is not a whitespace, we are in the middle of a word
3419 // and we only want to complete the shortcode if the word is made up of other emojis
3420 let mut containing_word = String::new();
3421 for ch in snapshot
3422 .reversed_chars_at(position)
3423 .skip(chars.len() + 1)
3424 .take(100)
3425 {
3426 if ch.is_whitespace() {
3427 break;
3428 }
3429 containing_word.push(ch);
3430 }
3431 let containing_word = containing_word.chars().rev().collect::<String>();
3432 if util::word_consists_of_emojis(containing_word.as_str()) {
3433 chars.reverse();
3434 return Some(chars.iter().collect());
3435 }
3436 }
3437
3438 if char.is_whitespace() || !char.is_ascii() {
3439 return None;
3440 }
3441 if char == ':' {
3442 found_colon = true;
3443 } else {
3444 chars.push(char);
3445 }
3446 }
3447 // Found a possible emoji shortcode at the beginning of the buffer
3448 chars.reverse();
3449 Some(chars.iter().collect())
3450 }
3451
3452 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3453 self.transact(cx, |this, cx| {
3454 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3455 let selections = this.selections.all::<usize>(cx);
3456 let multi_buffer = this.buffer.read(cx);
3457 let buffer = multi_buffer.snapshot(cx);
3458 selections
3459 .iter()
3460 .map(|selection| {
3461 let start_point = selection.start.to_point(&buffer);
3462 let mut indent =
3463 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3464 indent.len = cmp::min(indent.len, start_point.column);
3465 let start = selection.start;
3466 let end = selection.end;
3467 let selection_is_empty = start == end;
3468 let language_scope = buffer.language_scope_at(start);
3469 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3470 &language_scope
3471 {
3472 let leading_whitespace_len = buffer
3473 .reversed_chars_at(start)
3474 .take_while(|c| c.is_whitespace() && *c != '\n')
3475 .map(|c| c.len_utf8())
3476 .sum::<usize>();
3477
3478 let trailing_whitespace_len = buffer
3479 .chars_at(end)
3480 .take_while(|c| c.is_whitespace() && *c != '\n')
3481 .map(|c| c.len_utf8())
3482 .sum::<usize>();
3483
3484 let insert_extra_newline =
3485 language.brackets().any(|(pair, enabled)| {
3486 let pair_start = pair.start.trim_end();
3487 let pair_end = pair.end.trim_start();
3488
3489 enabled
3490 && pair.newline
3491 && buffer.contains_str_at(
3492 end + trailing_whitespace_len,
3493 pair_end,
3494 )
3495 && buffer.contains_str_at(
3496 (start - leading_whitespace_len)
3497 .saturating_sub(pair_start.len()),
3498 pair_start,
3499 )
3500 });
3501
3502 // Comment extension on newline is allowed only for cursor selections
3503 let comment_delimiter = maybe!({
3504 if !selection_is_empty {
3505 return None;
3506 }
3507
3508 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3509 return None;
3510 }
3511
3512 let delimiters = language.line_comment_prefixes();
3513 let max_len_of_delimiter =
3514 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3515 let (snapshot, range) =
3516 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3517
3518 let mut index_of_first_non_whitespace = 0;
3519 let comment_candidate = snapshot
3520 .chars_for_range(range)
3521 .skip_while(|c| {
3522 let should_skip = c.is_whitespace();
3523 if should_skip {
3524 index_of_first_non_whitespace += 1;
3525 }
3526 should_skip
3527 })
3528 .take(max_len_of_delimiter)
3529 .collect::<String>();
3530 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3531 comment_candidate.starts_with(comment_prefix.as_ref())
3532 })?;
3533 let cursor_is_placed_after_comment_marker =
3534 index_of_first_non_whitespace + comment_prefix.len()
3535 <= start_point.column as usize;
3536 if cursor_is_placed_after_comment_marker {
3537 Some(comment_prefix.clone())
3538 } else {
3539 None
3540 }
3541 });
3542 (comment_delimiter, insert_extra_newline)
3543 } else {
3544 (None, false)
3545 };
3546
3547 let capacity_for_delimiter = comment_delimiter
3548 .as_deref()
3549 .map(str::len)
3550 .unwrap_or_default();
3551 let mut new_text =
3552 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3553 new_text.push_str("\n");
3554 new_text.extend(indent.chars());
3555 if let Some(delimiter) = &comment_delimiter {
3556 new_text.push_str(&delimiter);
3557 }
3558 if insert_extra_newline {
3559 new_text = new_text.repeat(2);
3560 }
3561
3562 let anchor = buffer.anchor_after(end);
3563 let new_selection = selection.map(|_| anchor);
3564 (
3565 (start..end, new_text),
3566 (insert_extra_newline, new_selection),
3567 )
3568 })
3569 .unzip()
3570 };
3571
3572 this.edit_with_autoindent(edits, cx);
3573 let buffer = this.buffer.read(cx).snapshot(cx);
3574 let new_selections = selection_fixup_info
3575 .into_iter()
3576 .map(|(extra_newline_inserted, new_selection)| {
3577 let mut cursor = new_selection.end.to_point(&buffer);
3578 if extra_newline_inserted {
3579 cursor.row -= 1;
3580 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3581 }
3582 new_selection.map(|_| cursor)
3583 })
3584 .collect();
3585
3586 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3587 this.refresh_inline_completion(true, false, cx);
3588 });
3589 }
3590
3591 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3592 let buffer = self.buffer.read(cx);
3593 let snapshot = buffer.snapshot(cx);
3594
3595 let mut edits = Vec::new();
3596 let mut rows = Vec::new();
3597
3598 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3599 let cursor = selection.head();
3600 let row = cursor.row;
3601
3602 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3603
3604 let newline = "\n".to_string();
3605 edits.push((start_of_line..start_of_line, newline));
3606
3607 rows.push(row + rows_inserted as u32);
3608 }
3609
3610 self.transact(cx, |editor, cx| {
3611 editor.edit(edits, cx);
3612
3613 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3614 let mut index = 0;
3615 s.move_cursors_with(|map, _, _| {
3616 let row = rows[index];
3617 index += 1;
3618
3619 let point = Point::new(row, 0);
3620 let boundary = map.next_line_boundary(point).1;
3621 let clipped = map.clip_point(boundary, Bias::Left);
3622
3623 (clipped, SelectionGoal::None)
3624 });
3625 });
3626
3627 let mut indent_edits = Vec::new();
3628 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3629 for row in rows {
3630 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3631 for (row, indent) in indents {
3632 if indent.len == 0 {
3633 continue;
3634 }
3635
3636 let text = match indent.kind {
3637 IndentKind::Space => " ".repeat(indent.len as usize),
3638 IndentKind::Tab => "\t".repeat(indent.len as usize),
3639 };
3640 let point = Point::new(row.0, 0);
3641 indent_edits.push((point..point, text));
3642 }
3643 }
3644 editor.edit(indent_edits, cx);
3645 });
3646 }
3647
3648 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3649 let buffer = self.buffer.read(cx);
3650 let snapshot = buffer.snapshot(cx);
3651
3652 let mut edits = Vec::new();
3653 let mut rows = Vec::new();
3654 let mut rows_inserted = 0;
3655
3656 for selection in self.selections.all_adjusted(cx) {
3657 let cursor = selection.head();
3658 let row = cursor.row;
3659
3660 let point = Point::new(row + 1, 0);
3661 let start_of_line = snapshot.clip_point(point, Bias::Left);
3662
3663 let newline = "\n".to_string();
3664 edits.push((start_of_line..start_of_line, newline));
3665
3666 rows_inserted += 1;
3667 rows.push(row + rows_inserted);
3668 }
3669
3670 self.transact(cx, |editor, cx| {
3671 editor.edit(edits, cx);
3672
3673 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3674 let mut index = 0;
3675 s.move_cursors_with(|map, _, _| {
3676 let row = rows[index];
3677 index += 1;
3678
3679 let point = Point::new(row, 0);
3680 let boundary = map.next_line_boundary(point).1;
3681 let clipped = map.clip_point(boundary, Bias::Left);
3682
3683 (clipped, SelectionGoal::None)
3684 });
3685 });
3686
3687 let mut indent_edits = Vec::new();
3688 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3689 for row in rows {
3690 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3691 for (row, indent) in indents {
3692 if indent.len == 0 {
3693 continue;
3694 }
3695
3696 let text = match indent.kind {
3697 IndentKind::Space => " ".repeat(indent.len as usize),
3698 IndentKind::Tab => "\t".repeat(indent.len as usize),
3699 };
3700 let point = Point::new(row.0, 0);
3701 indent_edits.push((point..point, text));
3702 }
3703 }
3704 editor.edit(indent_edits, cx);
3705 });
3706 }
3707
3708 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3709 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3710 original_indent_columns: Vec::new(),
3711 });
3712 self.insert_with_autoindent_mode(text, autoindent, cx);
3713 }
3714
3715 fn insert_with_autoindent_mode(
3716 &mut self,
3717 text: &str,
3718 autoindent_mode: Option<AutoindentMode>,
3719 cx: &mut ViewContext<Self>,
3720 ) {
3721 if self.read_only(cx) {
3722 return;
3723 }
3724
3725 let text: Arc<str> = text.into();
3726 self.transact(cx, |this, cx| {
3727 let old_selections = this.selections.all_adjusted(cx);
3728 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3729 let anchors = {
3730 let snapshot = buffer.read(cx);
3731 old_selections
3732 .iter()
3733 .map(|s| {
3734 let anchor = snapshot.anchor_after(s.head());
3735 s.map(|_| anchor)
3736 })
3737 .collect::<Vec<_>>()
3738 };
3739 buffer.edit(
3740 old_selections
3741 .iter()
3742 .map(|s| (s.start..s.end, text.clone())),
3743 autoindent_mode,
3744 cx,
3745 );
3746 anchors
3747 });
3748
3749 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3750 s.select_anchors(selection_anchors);
3751 })
3752 });
3753 }
3754
3755 fn trigger_completion_on_input(
3756 &mut self,
3757 text: &str,
3758 trigger_in_words: bool,
3759 cx: &mut ViewContext<Self>,
3760 ) {
3761 if self.is_completion_trigger(text, trigger_in_words, cx) {
3762 self.show_completions(
3763 &ShowCompletions {
3764 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3765 },
3766 cx,
3767 );
3768 } else {
3769 self.hide_context_menu(cx);
3770 }
3771 }
3772
3773 fn is_completion_trigger(
3774 &self,
3775 text: &str,
3776 trigger_in_words: bool,
3777 cx: &mut ViewContext<Self>,
3778 ) -> bool {
3779 let position = self.selections.newest_anchor().head();
3780 let multibuffer = self.buffer.read(cx);
3781 let Some(buffer) = position
3782 .buffer_id
3783 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3784 else {
3785 return false;
3786 };
3787
3788 if let Some(completion_provider) = &self.completion_provider {
3789 completion_provider.is_completion_trigger(
3790 &buffer,
3791 position.text_anchor,
3792 text,
3793 trigger_in_words,
3794 cx,
3795 )
3796 } else {
3797 false
3798 }
3799 }
3800
3801 /// If any empty selections is touching the start of its innermost containing autoclose
3802 /// region, expand it to select the brackets.
3803 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3804 let selections = self.selections.all::<usize>(cx);
3805 let buffer = self.buffer.read(cx).read(cx);
3806 let new_selections = self
3807 .selections_with_autoclose_regions(selections, &buffer)
3808 .map(|(mut selection, region)| {
3809 if !selection.is_empty() {
3810 return selection;
3811 }
3812
3813 if let Some(region) = region {
3814 let mut range = region.range.to_offset(&buffer);
3815 if selection.start == range.start && range.start >= region.pair.start.len() {
3816 range.start -= region.pair.start.len();
3817 if buffer.contains_str_at(range.start, ®ion.pair.start)
3818 && buffer.contains_str_at(range.end, ®ion.pair.end)
3819 {
3820 range.end += region.pair.end.len();
3821 selection.start = range.start;
3822 selection.end = range.end;
3823
3824 return selection;
3825 }
3826 }
3827 }
3828
3829 let always_treat_brackets_as_autoclosed = buffer
3830 .settings_at(selection.start, cx)
3831 .always_treat_brackets_as_autoclosed;
3832
3833 if !always_treat_brackets_as_autoclosed {
3834 return selection;
3835 }
3836
3837 if let Some(scope) = buffer.language_scope_at(selection.start) {
3838 for (pair, enabled) in scope.brackets() {
3839 if !enabled || !pair.close {
3840 continue;
3841 }
3842
3843 if buffer.contains_str_at(selection.start, &pair.end) {
3844 let pair_start_len = pair.start.len();
3845 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3846 {
3847 selection.start -= pair_start_len;
3848 selection.end += pair.end.len();
3849
3850 return selection;
3851 }
3852 }
3853 }
3854 }
3855
3856 selection
3857 })
3858 .collect();
3859
3860 drop(buffer);
3861 self.change_selections(None, cx, |selections| selections.select(new_selections));
3862 }
3863
3864 /// Iterate the given selections, and for each one, find the smallest surrounding
3865 /// autoclose region. This uses the ordering of the selections and the autoclose
3866 /// regions to avoid repeated comparisons.
3867 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3868 &'a self,
3869 selections: impl IntoIterator<Item = Selection<D>>,
3870 buffer: &'a MultiBufferSnapshot,
3871 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3872 let mut i = 0;
3873 let mut regions = self.autoclose_regions.as_slice();
3874 selections.into_iter().map(move |selection| {
3875 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3876
3877 let mut enclosing = None;
3878 while let Some(pair_state) = regions.get(i) {
3879 if pair_state.range.end.to_offset(buffer) < range.start {
3880 regions = ®ions[i + 1..];
3881 i = 0;
3882 } else if pair_state.range.start.to_offset(buffer) > range.end {
3883 break;
3884 } else {
3885 if pair_state.selection_id == selection.id {
3886 enclosing = Some(pair_state);
3887 }
3888 i += 1;
3889 }
3890 }
3891
3892 (selection.clone(), enclosing)
3893 })
3894 }
3895
3896 /// Remove any autoclose regions that no longer contain their selection.
3897 fn invalidate_autoclose_regions(
3898 &mut self,
3899 mut selections: &[Selection<Anchor>],
3900 buffer: &MultiBufferSnapshot,
3901 ) {
3902 self.autoclose_regions.retain(|state| {
3903 let mut i = 0;
3904 while let Some(selection) = selections.get(i) {
3905 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3906 selections = &selections[1..];
3907 continue;
3908 }
3909 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3910 break;
3911 }
3912 if selection.id == state.selection_id {
3913 return true;
3914 } else {
3915 i += 1;
3916 }
3917 }
3918 false
3919 });
3920 }
3921
3922 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3923 let offset = position.to_offset(buffer);
3924 let (word_range, kind) = buffer.surrounding_word(offset, true);
3925 if offset > word_range.start && kind == Some(CharKind::Word) {
3926 Some(
3927 buffer
3928 .text_for_range(word_range.start..offset)
3929 .collect::<String>(),
3930 )
3931 } else {
3932 None
3933 }
3934 }
3935
3936 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3937 self.refresh_inlay_hints(
3938 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3939 cx,
3940 );
3941 }
3942
3943 pub fn inlay_hints_enabled(&self) -> bool {
3944 self.inlay_hint_cache.enabled
3945 }
3946
3947 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3948 if self.project.is_none() || self.mode != EditorMode::Full {
3949 return;
3950 }
3951
3952 let reason_description = reason.description();
3953 let ignore_debounce = matches!(
3954 reason,
3955 InlayHintRefreshReason::SettingsChange(_)
3956 | InlayHintRefreshReason::Toggle(_)
3957 | InlayHintRefreshReason::ExcerptsRemoved(_)
3958 );
3959 let (invalidate_cache, required_languages) = match reason {
3960 InlayHintRefreshReason::Toggle(enabled) => {
3961 self.inlay_hint_cache.enabled = enabled;
3962 if enabled {
3963 (InvalidationStrategy::RefreshRequested, None)
3964 } else {
3965 self.inlay_hint_cache.clear();
3966 self.splice_inlays(
3967 self.visible_inlay_hints(cx)
3968 .iter()
3969 .map(|inlay| inlay.id)
3970 .collect(),
3971 Vec::new(),
3972 cx,
3973 );
3974 return;
3975 }
3976 }
3977 InlayHintRefreshReason::SettingsChange(new_settings) => {
3978 match self.inlay_hint_cache.update_settings(
3979 &self.buffer,
3980 new_settings,
3981 self.visible_inlay_hints(cx),
3982 cx,
3983 ) {
3984 ControlFlow::Break(Some(InlaySplice {
3985 to_remove,
3986 to_insert,
3987 })) => {
3988 self.splice_inlays(to_remove, to_insert, cx);
3989 return;
3990 }
3991 ControlFlow::Break(None) => return,
3992 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3993 }
3994 }
3995 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3996 if let Some(InlaySplice {
3997 to_remove,
3998 to_insert,
3999 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4000 {
4001 self.splice_inlays(to_remove, to_insert, cx);
4002 }
4003 return;
4004 }
4005 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4006 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4007 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4008 }
4009 InlayHintRefreshReason::RefreshRequested => {
4010 (InvalidationStrategy::RefreshRequested, None)
4011 }
4012 };
4013
4014 if let Some(InlaySplice {
4015 to_remove,
4016 to_insert,
4017 }) = self.inlay_hint_cache.spawn_hint_refresh(
4018 reason_description,
4019 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4020 invalidate_cache,
4021 ignore_debounce,
4022 cx,
4023 ) {
4024 self.splice_inlays(to_remove, to_insert, cx);
4025 }
4026 }
4027
4028 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4029 self.display_map
4030 .read(cx)
4031 .current_inlays()
4032 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4033 .cloned()
4034 .collect()
4035 }
4036
4037 pub fn excerpts_for_inlay_hints_query(
4038 &self,
4039 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4040 cx: &mut ViewContext<Editor>,
4041 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4042 let Some(project) = self.project.as_ref() else {
4043 return HashMap::default();
4044 };
4045 let project = project.read(cx);
4046 let multi_buffer = self.buffer().read(cx);
4047 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4048 let multi_buffer_visible_start = self
4049 .scroll_manager
4050 .anchor()
4051 .anchor
4052 .to_point(&multi_buffer_snapshot);
4053 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4054 multi_buffer_visible_start
4055 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4056 Bias::Left,
4057 );
4058 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4059 multi_buffer
4060 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4061 .into_iter()
4062 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4063 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4064 let buffer = buffer_handle.read(cx);
4065 let buffer_file = project::File::from_dyn(buffer.file())?;
4066 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4067 let worktree_entry = buffer_worktree
4068 .read(cx)
4069 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4070 if worktree_entry.is_ignored {
4071 return None;
4072 }
4073
4074 let language = buffer.language()?;
4075 if let Some(restrict_to_languages) = restrict_to_languages {
4076 if !restrict_to_languages.contains(language) {
4077 return None;
4078 }
4079 }
4080 Some((
4081 excerpt_id,
4082 (
4083 buffer_handle,
4084 buffer.version().clone(),
4085 excerpt_visible_range,
4086 ),
4087 ))
4088 })
4089 .collect()
4090 }
4091
4092 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4093 TextLayoutDetails {
4094 text_system: cx.text_system().clone(),
4095 editor_style: self.style.clone().unwrap(),
4096 rem_size: cx.rem_size(),
4097 scroll_anchor: self.scroll_manager.anchor(),
4098 visible_rows: self.visible_line_count(),
4099 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4100 }
4101 }
4102
4103 fn splice_inlays(
4104 &self,
4105 to_remove: Vec<InlayId>,
4106 to_insert: Vec<Inlay>,
4107 cx: &mut ViewContext<Self>,
4108 ) {
4109 self.display_map.update(cx, |display_map, cx| {
4110 display_map.splice_inlays(to_remove, to_insert, cx);
4111 });
4112 cx.notify();
4113 }
4114
4115 fn trigger_on_type_formatting(
4116 &self,
4117 input: String,
4118 cx: &mut ViewContext<Self>,
4119 ) -> Option<Task<Result<()>>> {
4120 if input.len() != 1 {
4121 return None;
4122 }
4123
4124 let project = self.project.as_ref()?;
4125 let position = self.selections.newest_anchor().head();
4126 let (buffer, buffer_position) = self
4127 .buffer
4128 .read(cx)
4129 .text_anchor_for_position(position, cx)?;
4130
4131 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4132 // hence we do LSP request & edit on host side only — add formats to host's history.
4133 let push_to_lsp_host_history = true;
4134 // If this is not the host, append its history with new edits.
4135 let push_to_client_history = project.read(cx).is_via_collab();
4136
4137 let on_type_formatting = project.update(cx, |project, cx| {
4138 project.on_type_format(
4139 buffer.clone(),
4140 buffer_position,
4141 input,
4142 push_to_lsp_host_history,
4143 cx,
4144 )
4145 });
4146 Some(cx.spawn(|editor, mut cx| async move {
4147 if let Some(transaction) = on_type_formatting.await? {
4148 if push_to_client_history {
4149 buffer
4150 .update(&mut cx, |buffer, _| {
4151 buffer.push_transaction(transaction, Instant::now());
4152 })
4153 .ok();
4154 }
4155 editor.update(&mut cx, |editor, cx| {
4156 editor.refresh_document_highlights(cx);
4157 })?;
4158 }
4159 Ok(())
4160 }))
4161 }
4162
4163 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4164 if self.pending_rename.is_some() {
4165 return;
4166 }
4167
4168 let Some(provider) = self.completion_provider.as_ref() else {
4169 return;
4170 };
4171
4172 let position = self.selections.newest_anchor().head();
4173 let (buffer, buffer_position) =
4174 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4175 output
4176 } else {
4177 return;
4178 };
4179
4180 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4181 let is_followup_invoke = {
4182 let context_menu_state = self.context_menu.read();
4183 matches!(
4184 context_menu_state.deref(),
4185 Some(ContextMenu::Completions(_))
4186 )
4187 };
4188 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4189 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4190 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(&trigger) => {
4191 CompletionTriggerKind::TRIGGER_CHARACTER
4192 }
4193
4194 _ => CompletionTriggerKind::INVOKED,
4195 };
4196 let completion_context = CompletionContext {
4197 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4198 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4199 Some(String::from(trigger))
4200 } else {
4201 None
4202 }
4203 }),
4204 trigger_kind,
4205 };
4206 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4207 let sort_completions = provider.sort_completions();
4208
4209 let id = post_inc(&mut self.next_completion_id);
4210 let task = cx.spawn(|this, mut cx| {
4211 async move {
4212 this.update(&mut cx, |this, _| {
4213 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4214 })?;
4215 let completions = completions.await.log_err();
4216 let menu = if let Some(completions) = completions {
4217 let mut menu = CompletionsMenu {
4218 id,
4219 sort_completions,
4220 initial_position: position,
4221 match_candidates: completions
4222 .iter()
4223 .enumerate()
4224 .map(|(id, completion)| {
4225 StringMatchCandidate::new(
4226 id,
4227 completion.label.text[completion.label.filter_range.clone()]
4228 .into(),
4229 )
4230 })
4231 .collect(),
4232 buffer: buffer.clone(),
4233 completions: Arc::new(RwLock::new(completions.into())),
4234 matches: Vec::new().into(),
4235 selected_item: 0,
4236 scroll_handle: UniformListScrollHandle::new(),
4237 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4238 DebouncedDelay::new(),
4239 )),
4240 };
4241 menu.filter(query.as_deref(), cx.background_executor().clone())
4242 .await;
4243
4244 if menu.matches.is_empty() {
4245 None
4246 } else {
4247 this.update(&mut cx, |editor, cx| {
4248 let completions = menu.completions.clone();
4249 let matches = menu.matches.clone();
4250
4251 let delay_ms = EditorSettings::get_global(cx)
4252 .completion_documentation_secondary_query_debounce;
4253 let delay = Duration::from_millis(delay_ms);
4254 editor
4255 .completion_documentation_pre_resolve_debounce
4256 .fire_new(delay, cx, |editor, cx| {
4257 CompletionsMenu::pre_resolve_completion_documentation(
4258 buffer,
4259 completions,
4260 matches,
4261 editor,
4262 cx,
4263 )
4264 });
4265 })
4266 .ok();
4267 Some(menu)
4268 }
4269 } else {
4270 None
4271 };
4272
4273 this.update(&mut cx, |this, cx| {
4274 let mut context_menu = this.context_menu.write();
4275 match context_menu.as_ref() {
4276 None => {}
4277
4278 Some(ContextMenu::Completions(prev_menu)) => {
4279 if prev_menu.id > id {
4280 return;
4281 }
4282 }
4283
4284 _ => return,
4285 }
4286
4287 if this.focus_handle.is_focused(cx) && menu.is_some() {
4288 let menu = menu.unwrap();
4289 *context_menu = Some(ContextMenu::Completions(menu));
4290 drop(context_menu);
4291 this.discard_inline_completion(false, cx);
4292 cx.notify();
4293 } else if this.completion_tasks.len() <= 1 {
4294 // If there are no more completion tasks and the last menu was
4295 // empty, we should hide it. If it was already hidden, we should
4296 // also show the copilot completion when available.
4297 drop(context_menu);
4298 if this.hide_context_menu(cx).is_none() {
4299 this.update_visible_inline_completion(cx);
4300 }
4301 }
4302 })?;
4303
4304 Ok::<_, anyhow::Error>(())
4305 }
4306 .log_err()
4307 });
4308
4309 self.completion_tasks.push((id, task));
4310 }
4311
4312 pub fn confirm_completion(
4313 &mut self,
4314 action: &ConfirmCompletion,
4315 cx: &mut ViewContext<Self>,
4316 ) -> Option<Task<Result<()>>> {
4317 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4318 }
4319
4320 pub fn compose_completion(
4321 &mut self,
4322 action: &ComposeCompletion,
4323 cx: &mut ViewContext<Self>,
4324 ) -> Option<Task<Result<()>>> {
4325 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4326 }
4327
4328 fn do_completion(
4329 &mut self,
4330 item_ix: Option<usize>,
4331 intent: CompletionIntent,
4332 cx: &mut ViewContext<Editor>,
4333 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4334 use language::ToOffset as _;
4335
4336 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4337 menu
4338 } else {
4339 return None;
4340 };
4341
4342 let mat = completions_menu
4343 .matches
4344 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4345 let buffer_handle = completions_menu.buffer;
4346 let completions = completions_menu.completions.read();
4347 let completion = completions.get(mat.candidate_id)?;
4348 cx.stop_propagation();
4349
4350 let snippet;
4351 let text;
4352
4353 if completion.is_snippet() {
4354 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4355 text = snippet.as_ref().unwrap().text.clone();
4356 } else {
4357 snippet = None;
4358 text = completion.new_text.clone();
4359 };
4360 let selections = self.selections.all::<usize>(cx);
4361 let buffer = buffer_handle.read(cx);
4362 let old_range = completion.old_range.to_offset(buffer);
4363 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4364
4365 let newest_selection = self.selections.newest_anchor();
4366 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4367 return None;
4368 }
4369
4370 let lookbehind = newest_selection
4371 .start
4372 .text_anchor
4373 .to_offset(buffer)
4374 .saturating_sub(old_range.start);
4375 let lookahead = old_range
4376 .end
4377 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4378 let mut common_prefix_len = old_text
4379 .bytes()
4380 .zip(text.bytes())
4381 .take_while(|(a, b)| a == b)
4382 .count();
4383
4384 let snapshot = self.buffer.read(cx).snapshot(cx);
4385 let mut range_to_replace: Option<Range<isize>> = None;
4386 let mut ranges = Vec::new();
4387 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4388 for selection in &selections {
4389 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4390 let start = selection.start.saturating_sub(lookbehind);
4391 let end = selection.end + lookahead;
4392 if selection.id == newest_selection.id {
4393 range_to_replace = Some(
4394 ((start + common_prefix_len) as isize - selection.start as isize)
4395 ..(end as isize - selection.start as isize),
4396 );
4397 }
4398 ranges.push(start + common_prefix_len..end);
4399 } else {
4400 common_prefix_len = 0;
4401 ranges.clear();
4402 ranges.extend(selections.iter().map(|s| {
4403 if s.id == newest_selection.id {
4404 range_to_replace = Some(
4405 old_range.start.to_offset_utf16(&snapshot).0 as isize
4406 - selection.start as isize
4407 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4408 - selection.start as isize,
4409 );
4410 old_range.clone()
4411 } else {
4412 s.start..s.end
4413 }
4414 }));
4415 break;
4416 }
4417 if !self.linked_edit_ranges.is_empty() {
4418 let start_anchor = snapshot.anchor_before(selection.head());
4419 let end_anchor = snapshot.anchor_after(selection.tail());
4420 if let Some(ranges) = self
4421 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4422 {
4423 for (buffer, edits) in ranges {
4424 linked_edits.entry(buffer.clone()).or_default().extend(
4425 edits
4426 .into_iter()
4427 .map(|range| (range, text[common_prefix_len..].to_owned())),
4428 );
4429 }
4430 }
4431 }
4432 }
4433 let text = &text[common_prefix_len..];
4434
4435 cx.emit(EditorEvent::InputHandled {
4436 utf16_range_to_replace: range_to_replace,
4437 text: text.into(),
4438 });
4439
4440 self.transact(cx, |this, cx| {
4441 if let Some(mut snippet) = snippet {
4442 snippet.text = text.to_string();
4443 for tabstop in snippet.tabstops.iter_mut().flatten() {
4444 tabstop.start -= common_prefix_len as isize;
4445 tabstop.end -= common_prefix_len as isize;
4446 }
4447
4448 this.insert_snippet(&ranges, snippet, cx).log_err();
4449 } else {
4450 this.buffer.update(cx, |buffer, cx| {
4451 buffer.edit(
4452 ranges.iter().map(|range| (range.clone(), text)),
4453 this.autoindent_mode.clone(),
4454 cx,
4455 );
4456 });
4457 }
4458 for (buffer, edits) in linked_edits {
4459 buffer.update(cx, |buffer, cx| {
4460 let snapshot = buffer.snapshot();
4461 let edits = edits
4462 .into_iter()
4463 .map(|(range, text)| {
4464 use text::ToPoint as TP;
4465 let end_point = TP::to_point(&range.end, &snapshot);
4466 let start_point = TP::to_point(&range.start, &snapshot);
4467 (start_point..end_point, text)
4468 })
4469 .sorted_by_key(|(range, _)| range.start)
4470 .collect::<Vec<_>>();
4471 buffer.edit(edits, None, cx);
4472 })
4473 }
4474
4475 this.refresh_inline_completion(true, false, cx);
4476 });
4477
4478 let show_new_completions_on_confirm = completion
4479 .confirm
4480 .as_ref()
4481 .map_or(false, |confirm| confirm(intent, cx));
4482 if show_new_completions_on_confirm {
4483 self.show_completions(&ShowCompletions { trigger: None }, cx);
4484 }
4485
4486 let provider = self.completion_provider.as_ref()?;
4487 let apply_edits = provider.apply_additional_edits_for_completion(
4488 buffer_handle,
4489 completion.clone(),
4490 true,
4491 cx,
4492 );
4493
4494 let editor_settings = EditorSettings::get_global(cx);
4495 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4496 // After the code completion is finished, users often want to know what signatures are needed.
4497 // so we should automatically call signature_help
4498 self.show_signature_help(&ShowSignatureHelp, cx);
4499 }
4500
4501 Some(cx.foreground_executor().spawn(async move {
4502 apply_edits.await?;
4503 Ok(())
4504 }))
4505 }
4506
4507 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4508 let mut context_menu = self.context_menu.write();
4509 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4510 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4511 // Toggle if we're selecting the same one
4512 *context_menu = None;
4513 cx.notify();
4514 return;
4515 } else {
4516 // Otherwise, clear it and start a new one
4517 *context_menu = None;
4518 cx.notify();
4519 }
4520 }
4521 drop(context_menu);
4522 let snapshot = self.snapshot(cx);
4523 let deployed_from_indicator = action.deployed_from_indicator;
4524 let mut task = self.code_actions_task.take();
4525 let action = action.clone();
4526 cx.spawn(|editor, mut cx| async move {
4527 while let Some(prev_task) = task {
4528 prev_task.await;
4529 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4530 }
4531
4532 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4533 if editor.focus_handle.is_focused(cx) {
4534 let multibuffer_point = action
4535 .deployed_from_indicator
4536 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4537 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4538 let (buffer, buffer_row) = snapshot
4539 .buffer_snapshot
4540 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4541 .and_then(|(buffer_snapshot, range)| {
4542 editor
4543 .buffer
4544 .read(cx)
4545 .buffer(buffer_snapshot.remote_id())
4546 .map(|buffer| (buffer, range.start.row))
4547 })?;
4548 let (_, code_actions) = editor
4549 .available_code_actions
4550 .clone()
4551 .and_then(|(location, code_actions)| {
4552 let snapshot = location.buffer.read(cx).snapshot();
4553 let point_range = location.range.to_point(&snapshot);
4554 let point_range = point_range.start.row..=point_range.end.row;
4555 if point_range.contains(&buffer_row) {
4556 Some((location, code_actions))
4557 } else {
4558 None
4559 }
4560 })
4561 .unzip();
4562 let buffer_id = buffer.read(cx).remote_id();
4563 let tasks = editor
4564 .tasks
4565 .get(&(buffer_id, buffer_row))
4566 .map(|t| Arc::new(t.to_owned()));
4567 if tasks.is_none() && code_actions.is_none() {
4568 return None;
4569 }
4570
4571 editor.completion_tasks.clear();
4572 editor.discard_inline_completion(false, cx);
4573 let task_context =
4574 tasks
4575 .as_ref()
4576 .zip(editor.project.clone())
4577 .map(|(tasks, project)| {
4578 let position = Point::new(buffer_row, tasks.column);
4579 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4580 let location = Location {
4581 buffer: buffer.clone(),
4582 range: range_start..range_start,
4583 };
4584 // Fill in the environmental variables from the tree-sitter captures
4585 let mut captured_task_variables = TaskVariables::default();
4586 for (capture_name, value) in tasks.extra_variables.clone() {
4587 captured_task_variables.insert(
4588 task::VariableName::Custom(capture_name.into()),
4589 value.clone(),
4590 );
4591 }
4592 project.update(cx, |project, cx| {
4593 project.task_context_for_location(
4594 captured_task_variables,
4595 location,
4596 cx,
4597 )
4598 })
4599 });
4600
4601 Some(cx.spawn(|editor, mut cx| async move {
4602 let task_context = match task_context {
4603 Some(task_context) => task_context.await,
4604 None => None,
4605 };
4606 let resolved_tasks =
4607 tasks.zip(task_context).map(|(tasks, task_context)| {
4608 Arc::new(ResolvedTasks {
4609 templates: tasks
4610 .templates
4611 .iter()
4612 .filter_map(|(kind, template)| {
4613 template
4614 .resolve_task(&kind.to_id_base(), &task_context)
4615 .map(|task| (kind.clone(), task))
4616 })
4617 .collect(),
4618 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4619 multibuffer_point.row,
4620 tasks.column,
4621 )),
4622 })
4623 });
4624 let spawn_straight_away = resolved_tasks
4625 .as_ref()
4626 .map_or(false, |tasks| tasks.templates.len() == 1)
4627 && code_actions
4628 .as_ref()
4629 .map_or(true, |actions| actions.is_empty());
4630 if let Some(task) = editor
4631 .update(&mut cx, |editor, cx| {
4632 *editor.context_menu.write() =
4633 Some(ContextMenu::CodeActions(CodeActionsMenu {
4634 buffer,
4635 actions: CodeActionContents {
4636 tasks: resolved_tasks,
4637 actions: code_actions,
4638 },
4639 selected_item: Default::default(),
4640 scroll_handle: UniformListScrollHandle::default(),
4641 deployed_from_indicator,
4642 }));
4643 if spawn_straight_away {
4644 if let Some(task) = editor.confirm_code_action(
4645 &ConfirmCodeAction { item_ix: Some(0) },
4646 cx,
4647 ) {
4648 cx.notify();
4649 return task;
4650 }
4651 }
4652 cx.notify();
4653 Task::ready(Ok(()))
4654 })
4655 .ok()
4656 {
4657 task.await
4658 } else {
4659 Ok(())
4660 }
4661 }))
4662 } else {
4663 Some(Task::ready(Ok(())))
4664 }
4665 })?;
4666 if let Some(task) = spawned_test_task {
4667 task.await?;
4668 }
4669
4670 Ok::<_, anyhow::Error>(())
4671 })
4672 .detach_and_log_err(cx);
4673 }
4674
4675 pub fn confirm_code_action(
4676 &mut self,
4677 action: &ConfirmCodeAction,
4678 cx: &mut ViewContext<Self>,
4679 ) -> Option<Task<Result<()>>> {
4680 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4681 menu
4682 } else {
4683 return None;
4684 };
4685 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4686 let action = actions_menu.actions.get(action_ix)?;
4687 let title = action.label();
4688 let buffer = actions_menu.buffer;
4689 let workspace = self.workspace()?;
4690
4691 match action {
4692 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4693 workspace.update(cx, |workspace, cx| {
4694 workspace::tasks::schedule_resolved_task(
4695 workspace,
4696 task_source_kind,
4697 resolved_task,
4698 false,
4699 cx,
4700 );
4701
4702 Some(Task::ready(Ok(())))
4703 })
4704 }
4705 CodeActionsItem::CodeAction(action) => {
4706 let apply_code_actions = workspace
4707 .read(cx)
4708 .project()
4709 .clone()
4710 .update(cx, |project, cx| {
4711 project.apply_code_action(buffer, action, true, cx)
4712 });
4713 let workspace = workspace.downgrade();
4714 Some(cx.spawn(|editor, cx| async move {
4715 let project_transaction = apply_code_actions.await?;
4716 Self::open_project_transaction(
4717 &editor,
4718 workspace,
4719 project_transaction,
4720 title,
4721 cx,
4722 )
4723 .await
4724 }))
4725 }
4726 }
4727 }
4728
4729 pub async fn open_project_transaction(
4730 this: &WeakView<Editor>,
4731 workspace: WeakView<Workspace>,
4732 transaction: ProjectTransaction,
4733 title: String,
4734 mut cx: AsyncWindowContext,
4735 ) -> Result<()> {
4736 let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
4737
4738 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4739 cx.update(|cx| {
4740 entries.sort_unstable_by_key(|(buffer, _)| {
4741 buffer.read(cx).file().map(|f| f.path().clone())
4742 });
4743 })?;
4744
4745 // If the project transaction's edits are all contained within this editor, then
4746 // avoid opening a new editor to display them.
4747
4748 if let Some((buffer, transaction)) = entries.first() {
4749 if entries.len() == 1 {
4750 let excerpt = this.update(&mut cx, |editor, cx| {
4751 editor
4752 .buffer()
4753 .read(cx)
4754 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4755 })?;
4756 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4757 if excerpted_buffer == *buffer {
4758 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4759 let excerpt_range = excerpt_range.to_offset(buffer);
4760 buffer
4761 .edited_ranges_for_transaction::<usize>(transaction)
4762 .all(|range| {
4763 excerpt_range.start <= range.start
4764 && excerpt_range.end >= range.end
4765 })
4766 })?;
4767
4768 if all_edits_within_excerpt {
4769 return Ok(());
4770 }
4771 }
4772 }
4773 }
4774 } else {
4775 return Ok(());
4776 }
4777
4778 let mut ranges_to_highlight = Vec::new();
4779 let excerpt_buffer = cx.new_model(|cx| {
4780 let mut multibuffer =
4781 MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
4782 for (buffer_handle, transaction) in &entries {
4783 let buffer = buffer_handle.read(cx);
4784 ranges_to_highlight.extend(
4785 multibuffer.push_excerpts_with_context_lines(
4786 buffer_handle.clone(),
4787 buffer
4788 .edited_ranges_for_transaction::<usize>(transaction)
4789 .collect(),
4790 DEFAULT_MULTIBUFFER_CONTEXT,
4791 cx,
4792 ),
4793 );
4794 }
4795 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4796 multibuffer
4797 })?;
4798
4799 workspace.update(&mut cx, |workspace, cx| {
4800 let project = workspace.project().clone();
4801 let editor =
4802 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4803 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4804 editor.update(cx, |editor, cx| {
4805 editor.highlight_background::<Self>(
4806 &ranges_to_highlight,
4807 |theme| theme.editor_highlighted_line_background,
4808 cx,
4809 );
4810 });
4811 })?;
4812
4813 Ok(())
4814 }
4815
4816 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4817 let project = self.project.clone()?;
4818 let buffer = self.buffer.read(cx);
4819 let newest_selection = self.selections.newest_anchor().clone();
4820 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4821 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4822 if start_buffer != end_buffer {
4823 return None;
4824 }
4825
4826 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4827 cx.background_executor()
4828 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4829 .await;
4830
4831 let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
4832 project.code_actions(&start_buffer, start..end, cx)
4833 }) {
4834 code_actions.await
4835 } else {
4836 Vec::new()
4837 };
4838
4839 this.update(&mut cx, |this, cx| {
4840 this.available_code_actions = if actions.is_empty() {
4841 None
4842 } else {
4843 Some((
4844 Location {
4845 buffer: start_buffer,
4846 range: start..end,
4847 },
4848 actions.into(),
4849 ))
4850 };
4851 cx.notify();
4852 })
4853 .log_err();
4854 }));
4855 None
4856 }
4857
4858 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4859 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4860 self.show_git_blame_inline = false;
4861
4862 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4863 cx.background_executor().timer(delay).await;
4864
4865 this.update(&mut cx, |this, cx| {
4866 this.show_git_blame_inline = true;
4867 cx.notify();
4868 })
4869 .log_err();
4870 }));
4871 }
4872 }
4873
4874 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4875 if self.pending_rename.is_some() {
4876 return None;
4877 }
4878
4879 let project = self.project.clone()?;
4880 let buffer = self.buffer.read(cx);
4881 let newest_selection = self.selections.newest_anchor().clone();
4882 let cursor_position = newest_selection.head();
4883 let (cursor_buffer, cursor_buffer_position) =
4884 buffer.text_anchor_for_position(cursor_position, cx)?;
4885 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4886 if cursor_buffer != tail_buffer {
4887 return None;
4888 }
4889
4890 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4891 cx.background_executor()
4892 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
4893 .await;
4894
4895 let highlights = if let Some(highlights) = project
4896 .update(&mut cx, |project, cx| {
4897 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4898 })
4899 .log_err()
4900 {
4901 highlights.await.log_err()
4902 } else {
4903 None
4904 };
4905
4906 if let Some(highlights) = highlights {
4907 this.update(&mut cx, |this, cx| {
4908 if this.pending_rename.is_some() {
4909 return;
4910 }
4911
4912 let buffer_id = cursor_position.buffer_id;
4913 let buffer = this.buffer.read(cx);
4914 if !buffer
4915 .text_anchor_for_position(cursor_position, cx)
4916 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4917 {
4918 return;
4919 }
4920
4921 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4922 let mut write_ranges = Vec::new();
4923 let mut read_ranges = Vec::new();
4924 for highlight in highlights {
4925 for (excerpt_id, excerpt_range) in
4926 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4927 {
4928 let start = highlight
4929 .range
4930 .start
4931 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4932 let end = highlight
4933 .range
4934 .end
4935 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4936 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4937 continue;
4938 }
4939
4940 let range = Anchor {
4941 buffer_id,
4942 excerpt_id,
4943 text_anchor: start,
4944 }..Anchor {
4945 buffer_id,
4946 excerpt_id,
4947 text_anchor: end,
4948 };
4949 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4950 write_ranges.push(range);
4951 } else {
4952 read_ranges.push(range);
4953 }
4954 }
4955 }
4956
4957 this.highlight_background::<DocumentHighlightRead>(
4958 &read_ranges,
4959 |theme| theme.editor_document_highlight_read_background,
4960 cx,
4961 );
4962 this.highlight_background::<DocumentHighlightWrite>(
4963 &write_ranges,
4964 |theme| theme.editor_document_highlight_write_background,
4965 cx,
4966 );
4967 cx.notify();
4968 })
4969 .log_err();
4970 }
4971 }));
4972 None
4973 }
4974
4975 pub fn refresh_inline_completion(
4976 &mut self,
4977 debounce: bool,
4978 user_requested: bool,
4979 cx: &mut ViewContext<Self>,
4980 ) -> Option<()> {
4981 let provider = self.inline_completion_provider()?;
4982 let cursor = self.selections.newest_anchor().head();
4983 let (buffer, cursor_buffer_position) =
4984 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4985 if !user_requested
4986 && self.enable_inline_completions
4987 && !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4988 {
4989 self.discard_inline_completion(false, cx);
4990 return None;
4991 }
4992
4993 self.update_visible_inline_completion(cx);
4994 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4995 Some(())
4996 }
4997
4998 fn cycle_inline_completion(
4999 &mut self,
5000 direction: Direction,
5001 cx: &mut ViewContext<Self>,
5002 ) -> Option<()> {
5003 let provider = self.inline_completion_provider()?;
5004 let cursor = self.selections.newest_anchor().head();
5005 let (buffer, cursor_buffer_position) =
5006 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5007 if !self.enable_inline_completions
5008 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5009 {
5010 return None;
5011 }
5012
5013 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5014 self.update_visible_inline_completion(cx);
5015
5016 Some(())
5017 }
5018
5019 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5020 if !self.has_active_inline_completion(cx) {
5021 self.refresh_inline_completion(false, true, cx);
5022 return;
5023 }
5024
5025 self.update_visible_inline_completion(cx);
5026 }
5027
5028 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5029 self.show_cursor_names(cx);
5030 }
5031
5032 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5033 self.show_cursor_names = true;
5034 cx.notify();
5035 cx.spawn(|this, mut cx| async move {
5036 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5037 this.update(&mut cx, |this, cx| {
5038 this.show_cursor_names = false;
5039 cx.notify()
5040 })
5041 .ok()
5042 })
5043 .detach();
5044 }
5045
5046 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5047 if self.has_active_inline_completion(cx) {
5048 self.cycle_inline_completion(Direction::Next, cx);
5049 } else {
5050 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5051 if is_copilot_disabled {
5052 cx.propagate();
5053 }
5054 }
5055 }
5056
5057 pub fn previous_inline_completion(
5058 &mut self,
5059 _: &PreviousInlineCompletion,
5060 cx: &mut ViewContext<Self>,
5061 ) {
5062 if self.has_active_inline_completion(cx) {
5063 self.cycle_inline_completion(Direction::Prev, cx);
5064 } else {
5065 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5066 if is_copilot_disabled {
5067 cx.propagate();
5068 }
5069 }
5070 }
5071
5072 pub fn accept_inline_completion(
5073 &mut self,
5074 _: &AcceptInlineCompletion,
5075 cx: &mut ViewContext<Self>,
5076 ) {
5077 let Some((completion, delete_range)) = self.take_active_inline_completion(cx) else {
5078 return;
5079 };
5080 if let Some(provider) = self.inline_completion_provider() {
5081 provider.accept(cx);
5082 }
5083
5084 cx.emit(EditorEvent::InputHandled {
5085 utf16_range_to_replace: None,
5086 text: completion.text.to_string().into(),
5087 });
5088
5089 if let Some(range) = delete_range {
5090 self.change_selections(None, cx, |s| s.select_ranges([range]))
5091 }
5092 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5093 self.refresh_inline_completion(true, true, cx);
5094 cx.notify();
5095 }
5096
5097 pub fn accept_partial_inline_completion(
5098 &mut self,
5099 _: &AcceptPartialInlineCompletion,
5100 cx: &mut ViewContext<Self>,
5101 ) {
5102 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5103 if let Some((completion, delete_range)) = self.take_active_inline_completion(cx) {
5104 let mut partial_completion = completion
5105 .text
5106 .chars()
5107 .by_ref()
5108 .take_while(|c| c.is_alphabetic())
5109 .collect::<String>();
5110 if partial_completion.is_empty() {
5111 partial_completion = completion
5112 .text
5113 .chars()
5114 .by_ref()
5115 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5116 .collect::<String>();
5117 }
5118
5119 cx.emit(EditorEvent::InputHandled {
5120 utf16_range_to_replace: None,
5121 text: partial_completion.clone().into(),
5122 });
5123
5124 if let Some(range) = delete_range {
5125 self.change_selections(None, cx, |s| s.select_ranges([range]))
5126 }
5127 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5128
5129 self.refresh_inline_completion(true, true, cx);
5130 cx.notify();
5131 }
5132 }
5133 }
5134
5135 fn discard_inline_completion(
5136 &mut self,
5137 should_report_inline_completion_event: bool,
5138 cx: &mut ViewContext<Self>,
5139 ) -> bool {
5140 if let Some(provider) = self.inline_completion_provider() {
5141 provider.discard(should_report_inline_completion_event, cx);
5142 }
5143
5144 self.take_active_inline_completion(cx).is_some()
5145 }
5146
5147 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5148 if let Some(completion) = self.active_inline_completion.as_ref() {
5149 let buffer = self.buffer.read(cx).read(cx);
5150 completion.0.position.is_valid(&buffer)
5151 } else {
5152 false
5153 }
5154 }
5155
5156 fn take_active_inline_completion(
5157 &mut self,
5158 cx: &mut ViewContext<Self>,
5159 ) -> Option<(Inlay, Option<Range<Anchor>>)> {
5160 let completion = self.active_inline_completion.take()?;
5161 self.display_map.update(cx, |map, cx| {
5162 map.splice_inlays(vec![completion.0.id], Default::default(), cx);
5163 });
5164 let buffer = self.buffer.read(cx).read(cx);
5165
5166 if completion.0.position.is_valid(&buffer) {
5167 Some(completion)
5168 } else {
5169 None
5170 }
5171 }
5172
5173 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5174 let selection = self.selections.newest_anchor();
5175 let cursor = selection.head();
5176
5177 let excerpt_id = cursor.excerpt_id;
5178
5179 if self.context_menu.read().is_none()
5180 && self.completion_tasks.is_empty()
5181 && selection.start == selection.end
5182 {
5183 if let Some(provider) = self.inline_completion_provider() {
5184 if let Some((buffer, cursor_buffer_position)) =
5185 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5186 {
5187 if let Some((text, text_anchor_range)) =
5188 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5189 {
5190 let text = Rope::from(text);
5191 let mut to_remove = Vec::new();
5192 if let Some(completion) = self.active_inline_completion.take() {
5193 to_remove.push(completion.0.id);
5194 }
5195
5196 let completion_inlay =
5197 Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
5198
5199 let multibuffer_anchor_range = text_anchor_range.and_then(|range| {
5200 let snapshot = self.buffer.read(cx).snapshot(cx);
5201 Some(
5202 snapshot.anchor_in_excerpt(excerpt_id, range.start)?
5203 ..snapshot.anchor_in_excerpt(excerpt_id, range.end)?,
5204 )
5205 });
5206 self.active_inline_completion =
5207 Some((completion_inlay.clone(), multibuffer_anchor_range));
5208
5209 self.display_map.update(cx, move |map, cx| {
5210 map.splice_inlays(to_remove, vec![completion_inlay], cx)
5211 });
5212 cx.notify();
5213 return;
5214 }
5215 }
5216 }
5217 }
5218
5219 self.discard_inline_completion(false, cx);
5220 }
5221
5222 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5223 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5224 }
5225
5226 fn render_code_actions_indicator(
5227 &self,
5228 _style: &EditorStyle,
5229 row: DisplayRow,
5230 is_active: bool,
5231 cx: &mut ViewContext<Self>,
5232 ) -> Option<IconButton> {
5233 if self.available_code_actions.is_some() {
5234 Some(
5235 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5236 .shape(ui::IconButtonShape::Square)
5237 .icon_size(IconSize::XSmall)
5238 .icon_color(Color::Muted)
5239 .selected(is_active)
5240 .on_click(cx.listener(move |editor, _e, cx| {
5241 editor.focus(cx);
5242 editor.toggle_code_actions(
5243 &ToggleCodeActions {
5244 deployed_from_indicator: Some(row),
5245 },
5246 cx,
5247 );
5248 })),
5249 )
5250 } else {
5251 None
5252 }
5253 }
5254
5255 fn clear_tasks(&mut self) {
5256 self.tasks.clear()
5257 }
5258
5259 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5260 if let Some(_) = self.tasks.insert(key, value) {
5261 // This case should hopefully be rare, but just in case...
5262 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5263 }
5264 }
5265
5266 fn render_run_indicator(
5267 &self,
5268 _style: &EditorStyle,
5269 is_active: bool,
5270 row: DisplayRow,
5271 cx: &mut ViewContext<Self>,
5272 ) -> IconButton {
5273 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5274 .shape(ui::IconButtonShape::Square)
5275 .icon_size(IconSize::XSmall)
5276 .icon_color(Color::Muted)
5277 .selected(is_active)
5278 .on_click(cx.listener(move |editor, _e, cx| {
5279 editor.focus(cx);
5280 editor.toggle_code_actions(
5281 &ToggleCodeActions {
5282 deployed_from_indicator: Some(row),
5283 },
5284 cx,
5285 );
5286 }))
5287 }
5288
5289 fn close_hunk_diff_button(
5290 &self,
5291 hunk: HoveredHunk,
5292 row: DisplayRow,
5293 cx: &mut ViewContext<Self>,
5294 ) -> IconButton {
5295 IconButton::new(
5296 ("close_hunk_diff_indicator", row.0 as usize),
5297 ui::IconName::Close,
5298 )
5299 .shape(ui::IconButtonShape::Square)
5300 .icon_size(IconSize::XSmall)
5301 .icon_color(Color::Muted)
5302 .tooltip(|cx| Tooltip::for_action("Close hunk diff", &ToggleHunkDiff, cx))
5303 .on_click(cx.listener(move |editor, _e, cx| editor.toggle_hovered_hunk(&hunk, cx)))
5304 }
5305
5306 pub fn context_menu_visible(&self) -> bool {
5307 self.context_menu
5308 .read()
5309 .as_ref()
5310 .map_or(false, |menu| menu.visible())
5311 }
5312
5313 fn render_context_menu(
5314 &self,
5315 cursor_position: DisplayPoint,
5316 style: &EditorStyle,
5317 max_height: Pixels,
5318 cx: &mut ViewContext<Editor>,
5319 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5320 self.context_menu.read().as_ref().map(|menu| {
5321 menu.render(
5322 cursor_position,
5323 style,
5324 max_height,
5325 self.workspace.as_ref().map(|(w, _)| w.clone()),
5326 cx,
5327 )
5328 })
5329 }
5330
5331 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5332 cx.notify();
5333 self.completion_tasks.clear();
5334 let context_menu = self.context_menu.write().take();
5335 if context_menu.is_some() {
5336 self.update_visible_inline_completion(cx);
5337 }
5338 context_menu
5339 }
5340
5341 pub fn insert_snippet(
5342 &mut self,
5343 insertion_ranges: &[Range<usize>],
5344 snippet: Snippet,
5345 cx: &mut ViewContext<Self>,
5346 ) -> Result<()> {
5347 struct Tabstop<T> {
5348 is_end_tabstop: bool,
5349 ranges: Vec<Range<T>>,
5350 }
5351
5352 let tabstops = self.buffer.update(cx, |buffer, cx| {
5353 let snippet_text: Arc<str> = snippet.text.clone().into();
5354 buffer.edit(
5355 insertion_ranges
5356 .iter()
5357 .cloned()
5358 .map(|range| (range, snippet_text.clone())),
5359 Some(AutoindentMode::EachLine),
5360 cx,
5361 );
5362
5363 let snapshot = &*buffer.read(cx);
5364 let snippet = &snippet;
5365 snippet
5366 .tabstops
5367 .iter()
5368 .map(|tabstop| {
5369 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5370 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5371 });
5372 let mut tabstop_ranges = tabstop
5373 .iter()
5374 .flat_map(|tabstop_range| {
5375 let mut delta = 0_isize;
5376 insertion_ranges.iter().map(move |insertion_range| {
5377 let insertion_start = insertion_range.start as isize + delta;
5378 delta +=
5379 snippet.text.len() as isize - insertion_range.len() as isize;
5380
5381 let start = ((insertion_start + tabstop_range.start) as usize)
5382 .min(snapshot.len());
5383 let end = ((insertion_start + tabstop_range.end) as usize)
5384 .min(snapshot.len());
5385 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5386 })
5387 })
5388 .collect::<Vec<_>>();
5389 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5390
5391 Tabstop {
5392 is_end_tabstop,
5393 ranges: tabstop_ranges,
5394 }
5395 })
5396 .collect::<Vec<_>>()
5397 });
5398 if let Some(tabstop) = tabstops.first() {
5399 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5400 s.select_ranges(tabstop.ranges.iter().cloned());
5401 });
5402
5403 // If we're already at the last tabstop and it's at the end of the snippet,
5404 // we're done, we don't need to keep the state around.
5405 if !tabstop.is_end_tabstop {
5406 let ranges = tabstops
5407 .into_iter()
5408 .map(|tabstop| tabstop.ranges)
5409 .collect::<Vec<_>>();
5410 self.snippet_stack.push(SnippetState {
5411 active_index: 0,
5412 ranges,
5413 });
5414 }
5415
5416 // Check whether the just-entered snippet ends with an auto-closable bracket.
5417 if self.autoclose_regions.is_empty() {
5418 let snapshot = self.buffer.read(cx).snapshot(cx);
5419 for selection in &mut self.selections.all::<Point>(cx) {
5420 let selection_head = selection.head();
5421 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5422 continue;
5423 };
5424
5425 let mut bracket_pair = None;
5426 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5427 let prev_chars = snapshot
5428 .reversed_chars_at(selection_head)
5429 .collect::<String>();
5430 for (pair, enabled) in scope.brackets() {
5431 if enabled
5432 && pair.close
5433 && prev_chars.starts_with(pair.start.as_str())
5434 && next_chars.starts_with(pair.end.as_str())
5435 {
5436 bracket_pair = Some(pair.clone());
5437 break;
5438 }
5439 }
5440 if let Some(pair) = bracket_pair {
5441 let start = snapshot.anchor_after(selection_head);
5442 let end = snapshot.anchor_after(selection_head);
5443 self.autoclose_regions.push(AutocloseRegion {
5444 selection_id: selection.id,
5445 range: start..end,
5446 pair,
5447 });
5448 }
5449 }
5450 }
5451 }
5452 Ok(())
5453 }
5454
5455 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5456 self.move_to_snippet_tabstop(Bias::Right, cx)
5457 }
5458
5459 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5460 self.move_to_snippet_tabstop(Bias::Left, cx)
5461 }
5462
5463 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5464 if let Some(mut snippet) = self.snippet_stack.pop() {
5465 match bias {
5466 Bias::Left => {
5467 if snippet.active_index > 0 {
5468 snippet.active_index -= 1;
5469 } else {
5470 self.snippet_stack.push(snippet);
5471 return false;
5472 }
5473 }
5474 Bias::Right => {
5475 if snippet.active_index + 1 < snippet.ranges.len() {
5476 snippet.active_index += 1;
5477 } else {
5478 self.snippet_stack.push(snippet);
5479 return false;
5480 }
5481 }
5482 }
5483 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5484 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5485 s.select_anchor_ranges(current_ranges.iter().cloned())
5486 });
5487 // If snippet state is not at the last tabstop, push it back on the stack
5488 if snippet.active_index + 1 < snippet.ranges.len() {
5489 self.snippet_stack.push(snippet);
5490 }
5491 return true;
5492 }
5493 }
5494
5495 false
5496 }
5497
5498 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5499 self.transact(cx, |this, cx| {
5500 this.select_all(&SelectAll, cx);
5501 this.insert("", cx);
5502 });
5503 }
5504
5505 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5506 self.transact(cx, |this, cx| {
5507 this.select_autoclose_pair(cx);
5508 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5509 if !this.linked_edit_ranges.is_empty() {
5510 let selections = this.selections.all::<MultiBufferPoint>(cx);
5511 let snapshot = this.buffer.read(cx).snapshot(cx);
5512
5513 for selection in selections.iter() {
5514 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5515 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5516 if selection_start.buffer_id != selection_end.buffer_id {
5517 continue;
5518 }
5519 if let Some(ranges) =
5520 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5521 {
5522 for (buffer, entries) in ranges {
5523 linked_ranges.entry(buffer).or_default().extend(entries);
5524 }
5525 }
5526 }
5527 }
5528
5529 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5530 if !this.selections.line_mode {
5531 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5532 for selection in &mut selections {
5533 if selection.is_empty() {
5534 let old_head = selection.head();
5535 let mut new_head =
5536 movement::left(&display_map, old_head.to_display_point(&display_map))
5537 .to_point(&display_map);
5538 if let Some((buffer, line_buffer_range)) = display_map
5539 .buffer_snapshot
5540 .buffer_line_for_row(MultiBufferRow(old_head.row))
5541 {
5542 let indent_size =
5543 buffer.indent_size_for_line(line_buffer_range.start.row);
5544 let indent_len = match indent_size.kind {
5545 IndentKind::Space => {
5546 buffer.settings_at(line_buffer_range.start, cx).tab_size
5547 }
5548 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5549 };
5550 if old_head.column <= indent_size.len && old_head.column > 0 {
5551 let indent_len = indent_len.get();
5552 new_head = cmp::min(
5553 new_head,
5554 MultiBufferPoint::new(
5555 old_head.row,
5556 ((old_head.column - 1) / indent_len) * indent_len,
5557 ),
5558 );
5559 }
5560 }
5561
5562 selection.set_head(new_head, SelectionGoal::None);
5563 }
5564 }
5565 }
5566
5567 this.signature_help_state.set_backspace_pressed(true);
5568 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5569 this.insert("", cx);
5570 let empty_str: Arc<str> = Arc::from("");
5571 for (buffer, edits) in linked_ranges {
5572 let snapshot = buffer.read(cx).snapshot();
5573 use text::ToPoint as TP;
5574
5575 let edits = edits
5576 .into_iter()
5577 .map(|range| {
5578 let end_point = TP::to_point(&range.end, &snapshot);
5579 let mut start_point = TP::to_point(&range.start, &snapshot);
5580
5581 if end_point == start_point {
5582 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5583 .saturating_sub(1);
5584 start_point = TP::to_point(&offset, &snapshot);
5585 };
5586
5587 (start_point..end_point, empty_str.clone())
5588 })
5589 .sorted_by_key(|(range, _)| range.start)
5590 .collect::<Vec<_>>();
5591 buffer.update(cx, |this, cx| {
5592 this.edit(edits, None, cx);
5593 })
5594 }
5595 this.refresh_inline_completion(true, false, cx);
5596 linked_editing_ranges::refresh_linked_ranges(this, cx);
5597 });
5598 }
5599
5600 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5601 self.transact(cx, |this, cx| {
5602 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5603 let line_mode = s.line_mode;
5604 s.move_with(|map, selection| {
5605 if selection.is_empty() && !line_mode {
5606 let cursor = movement::right(map, selection.head());
5607 selection.end = cursor;
5608 selection.reversed = true;
5609 selection.goal = SelectionGoal::None;
5610 }
5611 })
5612 });
5613 this.insert("", cx);
5614 this.refresh_inline_completion(true, false, cx);
5615 });
5616 }
5617
5618 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5619 if self.move_to_prev_snippet_tabstop(cx) {
5620 return;
5621 }
5622
5623 self.outdent(&Outdent, cx);
5624 }
5625
5626 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5627 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5628 return;
5629 }
5630
5631 let mut selections = self.selections.all_adjusted(cx);
5632 let buffer = self.buffer.read(cx);
5633 let snapshot = buffer.snapshot(cx);
5634 let rows_iter = selections.iter().map(|s| s.head().row);
5635 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5636
5637 let mut edits = Vec::new();
5638 let mut prev_edited_row = 0;
5639 let mut row_delta = 0;
5640 for selection in &mut selections {
5641 if selection.start.row != prev_edited_row {
5642 row_delta = 0;
5643 }
5644 prev_edited_row = selection.end.row;
5645
5646 // If the selection is non-empty, then increase the indentation of the selected lines.
5647 if !selection.is_empty() {
5648 row_delta =
5649 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5650 continue;
5651 }
5652
5653 // If the selection is empty and the cursor is in the leading whitespace before the
5654 // suggested indentation, then auto-indent the line.
5655 let cursor = selection.head();
5656 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5657 if let Some(suggested_indent) =
5658 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5659 {
5660 if cursor.column < suggested_indent.len
5661 && cursor.column <= current_indent.len
5662 && current_indent.len <= suggested_indent.len
5663 {
5664 selection.start = Point::new(cursor.row, suggested_indent.len);
5665 selection.end = selection.start;
5666 if row_delta == 0 {
5667 edits.extend(Buffer::edit_for_indent_size_adjustment(
5668 cursor.row,
5669 current_indent,
5670 suggested_indent,
5671 ));
5672 row_delta = suggested_indent.len - current_indent.len;
5673 }
5674 continue;
5675 }
5676 }
5677
5678 // Otherwise, insert a hard or soft tab.
5679 let settings = buffer.settings_at(cursor, cx);
5680 let tab_size = if settings.hard_tabs {
5681 IndentSize::tab()
5682 } else {
5683 let tab_size = settings.tab_size.get();
5684 let char_column = snapshot
5685 .text_for_range(Point::new(cursor.row, 0)..cursor)
5686 .flat_map(str::chars)
5687 .count()
5688 + row_delta as usize;
5689 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5690 IndentSize::spaces(chars_to_next_tab_stop)
5691 };
5692 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5693 selection.end = selection.start;
5694 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5695 row_delta += tab_size.len;
5696 }
5697
5698 self.transact(cx, |this, cx| {
5699 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5700 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5701 this.refresh_inline_completion(true, false, cx);
5702 });
5703 }
5704
5705 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5706 if self.read_only(cx) {
5707 return;
5708 }
5709 let mut selections = self.selections.all::<Point>(cx);
5710 let mut prev_edited_row = 0;
5711 let mut row_delta = 0;
5712 let mut edits = Vec::new();
5713 let buffer = self.buffer.read(cx);
5714 let snapshot = buffer.snapshot(cx);
5715 for selection in &mut selections {
5716 if selection.start.row != prev_edited_row {
5717 row_delta = 0;
5718 }
5719 prev_edited_row = selection.end.row;
5720
5721 row_delta =
5722 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5723 }
5724
5725 self.transact(cx, |this, cx| {
5726 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5727 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5728 });
5729 }
5730
5731 fn indent_selection(
5732 buffer: &MultiBuffer,
5733 snapshot: &MultiBufferSnapshot,
5734 selection: &mut Selection<Point>,
5735 edits: &mut Vec<(Range<Point>, String)>,
5736 delta_for_start_row: u32,
5737 cx: &AppContext,
5738 ) -> u32 {
5739 let settings = buffer.settings_at(selection.start, cx);
5740 let tab_size = settings.tab_size.get();
5741 let indent_kind = if settings.hard_tabs {
5742 IndentKind::Tab
5743 } else {
5744 IndentKind::Space
5745 };
5746 let mut start_row = selection.start.row;
5747 let mut end_row = selection.end.row + 1;
5748
5749 // If a selection ends at the beginning of a line, don't indent
5750 // that last line.
5751 if selection.end.column == 0 && selection.end.row > selection.start.row {
5752 end_row -= 1;
5753 }
5754
5755 // Avoid re-indenting a row that has already been indented by a
5756 // previous selection, but still update this selection's column
5757 // to reflect that indentation.
5758 if delta_for_start_row > 0 {
5759 start_row += 1;
5760 selection.start.column += delta_for_start_row;
5761 if selection.end.row == selection.start.row {
5762 selection.end.column += delta_for_start_row;
5763 }
5764 }
5765
5766 let mut delta_for_end_row = 0;
5767 let has_multiple_rows = start_row + 1 != end_row;
5768 for row in start_row..end_row {
5769 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5770 let indent_delta = match (current_indent.kind, indent_kind) {
5771 (IndentKind::Space, IndentKind::Space) => {
5772 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5773 IndentSize::spaces(columns_to_next_tab_stop)
5774 }
5775 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5776 (_, IndentKind::Tab) => IndentSize::tab(),
5777 };
5778
5779 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5780 0
5781 } else {
5782 selection.start.column
5783 };
5784 let row_start = Point::new(row, start);
5785 edits.push((
5786 row_start..row_start,
5787 indent_delta.chars().collect::<String>(),
5788 ));
5789
5790 // Update this selection's endpoints to reflect the indentation.
5791 if row == selection.start.row {
5792 selection.start.column += indent_delta.len;
5793 }
5794 if row == selection.end.row {
5795 selection.end.column += indent_delta.len;
5796 delta_for_end_row = indent_delta.len;
5797 }
5798 }
5799
5800 if selection.start.row == selection.end.row {
5801 delta_for_start_row + delta_for_end_row
5802 } else {
5803 delta_for_end_row
5804 }
5805 }
5806
5807 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5808 if self.read_only(cx) {
5809 return;
5810 }
5811 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5812 let selections = self.selections.all::<Point>(cx);
5813 let mut deletion_ranges = Vec::new();
5814 let mut last_outdent = None;
5815 {
5816 let buffer = self.buffer.read(cx);
5817 let snapshot = buffer.snapshot(cx);
5818 for selection in &selections {
5819 let settings = buffer.settings_at(selection.start, cx);
5820 let tab_size = settings.tab_size.get();
5821 let mut rows = selection.spanned_rows(false, &display_map);
5822
5823 // Avoid re-outdenting a row that has already been outdented by a
5824 // previous selection.
5825 if let Some(last_row) = last_outdent {
5826 if last_row == rows.start {
5827 rows.start = rows.start.next_row();
5828 }
5829 }
5830 let has_multiple_rows = rows.len() > 1;
5831 for row in rows.iter_rows() {
5832 let indent_size = snapshot.indent_size_for_line(row);
5833 if indent_size.len > 0 {
5834 let deletion_len = match indent_size.kind {
5835 IndentKind::Space => {
5836 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5837 if columns_to_prev_tab_stop == 0 {
5838 tab_size
5839 } else {
5840 columns_to_prev_tab_stop
5841 }
5842 }
5843 IndentKind::Tab => 1,
5844 };
5845 let start = if has_multiple_rows
5846 || deletion_len > selection.start.column
5847 || indent_size.len < selection.start.column
5848 {
5849 0
5850 } else {
5851 selection.start.column - deletion_len
5852 };
5853 deletion_ranges.push(
5854 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5855 );
5856 last_outdent = Some(row);
5857 }
5858 }
5859 }
5860 }
5861
5862 self.transact(cx, |this, cx| {
5863 this.buffer.update(cx, |buffer, cx| {
5864 let empty_str: Arc<str> = Arc::default();
5865 buffer.edit(
5866 deletion_ranges
5867 .into_iter()
5868 .map(|range| (range, empty_str.clone())),
5869 None,
5870 cx,
5871 );
5872 });
5873 let selections = this.selections.all::<usize>(cx);
5874 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5875 });
5876 }
5877
5878 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5879 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5880 let selections = self.selections.all::<Point>(cx);
5881
5882 let mut new_cursors = Vec::new();
5883 let mut edit_ranges = Vec::new();
5884 let mut selections = selections.iter().peekable();
5885 while let Some(selection) = selections.next() {
5886 let mut rows = selection.spanned_rows(false, &display_map);
5887 let goal_display_column = selection.head().to_display_point(&display_map).column();
5888
5889 // Accumulate contiguous regions of rows that we want to delete.
5890 while let Some(next_selection) = selections.peek() {
5891 let next_rows = next_selection.spanned_rows(false, &display_map);
5892 if next_rows.start <= rows.end {
5893 rows.end = next_rows.end;
5894 selections.next().unwrap();
5895 } else {
5896 break;
5897 }
5898 }
5899
5900 let buffer = &display_map.buffer_snapshot;
5901 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5902 let edit_end;
5903 let cursor_buffer_row;
5904 if buffer.max_point().row >= rows.end.0 {
5905 // If there's a line after the range, delete the \n from the end of the row range
5906 // and position the cursor on the next line.
5907 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5908 cursor_buffer_row = rows.end;
5909 } else {
5910 // If there isn't a line after the range, delete the \n from the line before the
5911 // start of the row range and position the cursor there.
5912 edit_start = edit_start.saturating_sub(1);
5913 edit_end = buffer.len();
5914 cursor_buffer_row = rows.start.previous_row();
5915 }
5916
5917 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5918 *cursor.column_mut() =
5919 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5920
5921 new_cursors.push((
5922 selection.id,
5923 buffer.anchor_after(cursor.to_point(&display_map)),
5924 ));
5925 edit_ranges.push(edit_start..edit_end);
5926 }
5927
5928 self.transact(cx, |this, cx| {
5929 let buffer = this.buffer.update(cx, |buffer, cx| {
5930 let empty_str: Arc<str> = Arc::default();
5931 buffer.edit(
5932 edit_ranges
5933 .into_iter()
5934 .map(|range| (range, empty_str.clone())),
5935 None,
5936 cx,
5937 );
5938 buffer.snapshot(cx)
5939 });
5940 let new_selections = new_cursors
5941 .into_iter()
5942 .map(|(id, cursor)| {
5943 let cursor = cursor.to_point(&buffer);
5944 Selection {
5945 id,
5946 start: cursor,
5947 end: cursor,
5948 reversed: false,
5949 goal: SelectionGoal::None,
5950 }
5951 })
5952 .collect();
5953
5954 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5955 s.select(new_selections);
5956 });
5957 });
5958 }
5959
5960 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5961 if self.read_only(cx) {
5962 return;
5963 }
5964 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5965 for selection in self.selections.all::<Point>(cx) {
5966 let start = MultiBufferRow(selection.start.row);
5967 let end = if selection.start.row == selection.end.row {
5968 MultiBufferRow(selection.start.row + 1)
5969 } else {
5970 MultiBufferRow(selection.end.row)
5971 };
5972
5973 if let Some(last_row_range) = row_ranges.last_mut() {
5974 if start <= last_row_range.end {
5975 last_row_range.end = end;
5976 continue;
5977 }
5978 }
5979 row_ranges.push(start..end);
5980 }
5981
5982 let snapshot = self.buffer.read(cx).snapshot(cx);
5983 let mut cursor_positions = Vec::new();
5984 for row_range in &row_ranges {
5985 let anchor = snapshot.anchor_before(Point::new(
5986 row_range.end.previous_row().0,
5987 snapshot.line_len(row_range.end.previous_row()),
5988 ));
5989 cursor_positions.push(anchor..anchor);
5990 }
5991
5992 self.transact(cx, |this, cx| {
5993 for row_range in row_ranges.into_iter().rev() {
5994 for row in row_range.iter_rows().rev() {
5995 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5996 let next_line_row = row.next_row();
5997 let indent = snapshot.indent_size_for_line(next_line_row);
5998 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5999
6000 let replace = if snapshot.line_len(next_line_row) > indent.len {
6001 " "
6002 } else {
6003 ""
6004 };
6005
6006 this.buffer.update(cx, |buffer, cx| {
6007 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6008 });
6009 }
6010 }
6011
6012 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6013 s.select_anchor_ranges(cursor_positions)
6014 });
6015 });
6016 }
6017
6018 pub fn sort_lines_case_sensitive(
6019 &mut self,
6020 _: &SortLinesCaseSensitive,
6021 cx: &mut ViewContext<Self>,
6022 ) {
6023 self.manipulate_lines(cx, |lines| lines.sort())
6024 }
6025
6026 pub fn sort_lines_case_insensitive(
6027 &mut self,
6028 _: &SortLinesCaseInsensitive,
6029 cx: &mut ViewContext<Self>,
6030 ) {
6031 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6032 }
6033
6034 pub fn unique_lines_case_insensitive(
6035 &mut self,
6036 _: &UniqueLinesCaseInsensitive,
6037 cx: &mut ViewContext<Self>,
6038 ) {
6039 self.manipulate_lines(cx, |lines| {
6040 let mut seen = HashSet::default();
6041 lines.retain(|line| seen.insert(line.to_lowercase()));
6042 })
6043 }
6044
6045 pub fn unique_lines_case_sensitive(
6046 &mut self,
6047 _: &UniqueLinesCaseSensitive,
6048 cx: &mut ViewContext<Self>,
6049 ) {
6050 self.manipulate_lines(cx, |lines| {
6051 let mut seen = HashSet::default();
6052 lines.retain(|line| seen.insert(*line));
6053 })
6054 }
6055
6056 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6057 let mut revert_changes = HashMap::default();
6058 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6059 for hunk in hunks_for_rows(
6060 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6061 &multi_buffer_snapshot,
6062 ) {
6063 Self::prepare_revert_change(&mut revert_changes, &self.buffer(), &hunk, cx);
6064 }
6065 if !revert_changes.is_empty() {
6066 self.transact(cx, |editor, cx| {
6067 editor.revert(revert_changes, cx);
6068 });
6069 }
6070 }
6071
6072 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6073 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6074 if !revert_changes.is_empty() {
6075 self.transact(cx, |editor, cx| {
6076 editor.revert(revert_changes, cx);
6077 });
6078 }
6079 }
6080
6081 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6082 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6083 let project_path = buffer.read(cx).project_path(cx)?;
6084 let project = self.project.as_ref()?.read(cx);
6085 let entry = project.entry_for_path(&project_path, cx)?;
6086 let abs_path = project.absolute_path(&project_path, cx)?;
6087 let parent = if entry.is_symlink {
6088 abs_path.canonicalize().ok()?
6089 } else {
6090 abs_path
6091 }
6092 .parent()?
6093 .to_path_buf();
6094 Some(parent)
6095 }) {
6096 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6097 }
6098 }
6099
6100 fn gather_revert_changes(
6101 &mut self,
6102 selections: &[Selection<Anchor>],
6103 cx: &mut ViewContext<'_, Editor>,
6104 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6105 let mut revert_changes = HashMap::default();
6106 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6107 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6108 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6109 }
6110 revert_changes
6111 }
6112
6113 pub fn prepare_revert_change(
6114 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6115 multi_buffer: &Model<MultiBuffer>,
6116 hunk: &DiffHunk<MultiBufferRow>,
6117 cx: &AppContext,
6118 ) -> Option<()> {
6119 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6120 let buffer = buffer.read(cx);
6121 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6122 let buffer_snapshot = buffer.snapshot();
6123 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6124 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6125 probe
6126 .0
6127 .start
6128 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6129 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6130 }) {
6131 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6132 Some(())
6133 } else {
6134 None
6135 }
6136 }
6137
6138 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6139 self.manipulate_lines(cx, |lines| lines.reverse())
6140 }
6141
6142 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6143 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6144 }
6145
6146 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6147 where
6148 Fn: FnMut(&mut Vec<&str>),
6149 {
6150 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6151 let buffer = self.buffer.read(cx).snapshot(cx);
6152
6153 let mut edits = Vec::new();
6154
6155 let selections = self.selections.all::<Point>(cx);
6156 let mut selections = selections.iter().peekable();
6157 let mut contiguous_row_selections = Vec::new();
6158 let mut new_selections = Vec::new();
6159 let mut added_lines = 0;
6160 let mut removed_lines = 0;
6161
6162 while let Some(selection) = selections.next() {
6163 let (start_row, end_row) = consume_contiguous_rows(
6164 &mut contiguous_row_selections,
6165 selection,
6166 &display_map,
6167 &mut selections,
6168 );
6169
6170 let start_point = Point::new(start_row.0, 0);
6171 let end_point = Point::new(
6172 end_row.previous_row().0,
6173 buffer.line_len(end_row.previous_row()),
6174 );
6175 let text = buffer
6176 .text_for_range(start_point..end_point)
6177 .collect::<String>();
6178
6179 let mut lines = text.split('\n').collect_vec();
6180
6181 let lines_before = lines.len();
6182 callback(&mut lines);
6183 let lines_after = lines.len();
6184
6185 edits.push((start_point..end_point, lines.join("\n")));
6186
6187 // Selections must change based on added and removed line count
6188 let start_row =
6189 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6190 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6191 new_selections.push(Selection {
6192 id: selection.id,
6193 start: start_row,
6194 end: end_row,
6195 goal: SelectionGoal::None,
6196 reversed: selection.reversed,
6197 });
6198
6199 if lines_after > lines_before {
6200 added_lines += lines_after - lines_before;
6201 } else if lines_before > lines_after {
6202 removed_lines += lines_before - lines_after;
6203 }
6204 }
6205
6206 self.transact(cx, |this, cx| {
6207 let buffer = this.buffer.update(cx, |buffer, cx| {
6208 buffer.edit(edits, None, cx);
6209 buffer.snapshot(cx)
6210 });
6211
6212 // Recalculate offsets on newly edited buffer
6213 let new_selections = new_selections
6214 .iter()
6215 .map(|s| {
6216 let start_point = Point::new(s.start.0, 0);
6217 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6218 Selection {
6219 id: s.id,
6220 start: buffer.point_to_offset(start_point),
6221 end: buffer.point_to_offset(end_point),
6222 goal: s.goal,
6223 reversed: s.reversed,
6224 }
6225 })
6226 .collect();
6227
6228 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6229 s.select(new_selections);
6230 });
6231
6232 this.request_autoscroll(Autoscroll::fit(), cx);
6233 });
6234 }
6235
6236 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6237 self.manipulate_text(cx, |text| text.to_uppercase())
6238 }
6239
6240 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6241 self.manipulate_text(cx, |text| text.to_lowercase())
6242 }
6243
6244 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6245 self.manipulate_text(cx, |text| {
6246 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6247 // https://github.com/rutrum/convert-case/issues/16
6248 text.split('\n')
6249 .map(|line| line.to_case(Case::Title))
6250 .join("\n")
6251 })
6252 }
6253
6254 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6255 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6256 }
6257
6258 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6259 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6260 }
6261
6262 pub fn convert_to_upper_camel_case(
6263 &mut self,
6264 _: &ConvertToUpperCamelCase,
6265 cx: &mut ViewContext<Self>,
6266 ) {
6267 self.manipulate_text(cx, |text| {
6268 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6269 // https://github.com/rutrum/convert-case/issues/16
6270 text.split('\n')
6271 .map(|line| line.to_case(Case::UpperCamel))
6272 .join("\n")
6273 })
6274 }
6275
6276 pub fn convert_to_lower_camel_case(
6277 &mut self,
6278 _: &ConvertToLowerCamelCase,
6279 cx: &mut ViewContext<Self>,
6280 ) {
6281 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6282 }
6283
6284 pub fn convert_to_opposite_case(
6285 &mut self,
6286 _: &ConvertToOppositeCase,
6287 cx: &mut ViewContext<Self>,
6288 ) {
6289 self.manipulate_text(cx, |text| {
6290 text.chars()
6291 .fold(String::with_capacity(text.len()), |mut t, c| {
6292 if c.is_uppercase() {
6293 t.extend(c.to_lowercase());
6294 } else {
6295 t.extend(c.to_uppercase());
6296 }
6297 t
6298 })
6299 })
6300 }
6301
6302 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6303 where
6304 Fn: FnMut(&str) -> String,
6305 {
6306 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6307 let buffer = self.buffer.read(cx).snapshot(cx);
6308
6309 let mut new_selections = Vec::new();
6310 let mut edits = Vec::new();
6311 let mut selection_adjustment = 0i32;
6312
6313 for selection in self.selections.all::<usize>(cx) {
6314 let selection_is_empty = selection.is_empty();
6315
6316 let (start, end) = if selection_is_empty {
6317 let word_range = movement::surrounding_word(
6318 &display_map,
6319 selection.start.to_display_point(&display_map),
6320 );
6321 let start = word_range.start.to_offset(&display_map, Bias::Left);
6322 let end = word_range.end.to_offset(&display_map, Bias::Left);
6323 (start, end)
6324 } else {
6325 (selection.start, selection.end)
6326 };
6327
6328 let text = buffer.text_for_range(start..end).collect::<String>();
6329 let old_length = text.len() as i32;
6330 let text = callback(&text);
6331
6332 new_selections.push(Selection {
6333 start: (start as i32 - selection_adjustment) as usize,
6334 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6335 goal: SelectionGoal::None,
6336 ..selection
6337 });
6338
6339 selection_adjustment += old_length - text.len() as i32;
6340
6341 edits.push((start..end, text));
6342 }
6343
6344 self.transact(cx, |this, cx| {
6345 this.buffer.update(cx, |buffer, cx| {
6346 buffer.edit(edits, None, cx);
6347 });
6348
6349 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6350 s.select(new_selections);
6351 });
6352
6353 this.request_autoscroll(Autoscroll::fit(), cx);
6354 });
6355 }
6356
6357 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6358 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6359 let buffer = &display_map.buffer_snapshot;
6360 let selections = self.selections.all::<Point>(cx);
6361
6362 let mut edits = Vec::new();
6363 let mut selections_iter = selections.iter().peekable();
6364 while let Some(selection) = selections_iter.next() {
6365 // Avoid duplicating the same lines twice.
6366 let mut rows = selection.spanned_rows(false, &display_map);
6367
6368 while let Some(next_selection) = selections_iter.peek() {
6369 let next_rows = next_selection.spanned_rows(false, &display_map);
6370 if next_rows.start < rows.end {
6371 rows.end = next_rows.end;
6372 selections_iter.next().unwrap();
6373 } else {
6374 break;
6375 }
6376 }
6377
6378 // Copy the text from the selected row region and splice it either at the start
6379 // or end of the region.
6380 let start = Point::new(rows.start.0, 0);
6381 let end = Point::new(
6382 rows.end.previous_row().0,
6383 buffer.line_len(rows.end.previous_row()),
6384 );
6385 let text = buffer
6386 .text_for_range(start..end)
6387 .chain(Some("\n"))
6388 .collect::<String>();
6389 let insert_location = if upwards {
6390 Point::new(rows.end.0, 0)
6391 } else {
6392 start
6393 };
6394 edits.push((insert_location..insert_location, text));
6395 }
6396
6397 self.transact(cx, |this, cx| {
6398 this.buffer.update(cx, |buffer, cx| {
6399 buffer.edit(edits, None, cx);
6400 });
6401
6402 this.request_autoscroll(Autoscroll::fit(), cx);
6403 });
6404 }
6405
6406 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6407 self.duplicate_line(true, cx);
6408 }
6409
6410 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6411 self.duplicate_line(false, cx);
6412 }
6413
6414 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6415 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6416 let buffer = self.buffer.read(cx).snapshot(cx);
6417
6418 let mut edits = Vec::new();
6419 let mut unfold_ranges = Vec::new();
6420 let mut refold_ranges = Vec::new();
6421
6422 let selections = self.selections.all::<Point>(cx);
6423 let mut selections = selections.iter().peekable();
6424 let mut contiguous_row_selections = Vec::new();
6425 let mut new_selections = Vec::new();
6426
6427 while let Some(selection) = selections.next() {
6428 // Find all the selections that span a contiguous row range
6429 let (start_row, end_row) = consume_contiguous_rows(
6430 &mut contiguous_row_selections,
6431 selection,
6432 &display_map,
6433 &mut selections,
6434 );
6435
6436 // Move the text spanned by the row range to be before the line preceding the row range
6437 if start_row.0 > 0 {
6438 let range_to_move = Point::new(
6439 start_row.previous_row().0,
6440 buffer.line_len(start_row.previous_row()),
6441 )
6442 ..Point::new(
6443 end_row.previous_row().0,
6444 buffer.line_len(end_row.previous_row()),
6445 );
6446 let insertion_point = display_map
6447 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6448 .0;
6449
6450 // Don't move lines across excerpts
6451 if buffer
6452 .excerpt_boundaries_in_range((
6453 Bound::Excluded(insertion_point),
6454 Bound::Included(range_to_move.end),
6455 ))
6456 .next()
6457 .is_none()
6458 {
6459 let text = buffer
6460 .text_for_range(range_to_move.clone())
6461 .flat_map(|s| s.chars())
6462 .skip(1)
6463 .chain(['\n'])
6464 .collect::<String>();
6465
6466 edits.push((
6467 buffer.anchor_after(range_to_move.start)
6468 ..buffer.anchor_before(range_to_move.end),
6469 String::new(),
6470 ));
6471 let insertion_anchor = buffer.anchor_after(insertion_point);
6472 edits.push((insertion_anchor..insertion_anchor, text));
6473
6474 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6475
6476 // Move selections up
6477 new_selections.extend(contiguous_row_selections.drain(..).map(
6478 |mut selection| {
6479 selection.start.row -= row_delta;
6480 selection.end.row -= row_delta;
6481 selection
6482 },
6483 ));
6484
6485 // Move folds up
6486 unfold_ranges.push(range_to_move.clone());
6487 for fold in display_map.folds_in_range(
6488 buffer.anchor_before(range_to_move.start)
6489 ..buffer.anchor_after(range_to_move.end),
6490 ) {
6491 let mut start = fold.range.start.to_point(&buffer);
6492 let mut end = fold.range.end.to_point(&buffer);
6493 start.row -= row_delta;
6494 end.row -= row_delta;
6495 refold_ranges.push((start..end, fold.placeholder.clone()));
6496 }
6497 }
6498 }
6499
6500 // If we didn't move line(s), preserve the existing selections
6501 new_selections.append(&mut contiguous_row_selections);
6502 }
6503
6504 self.transact(cx, |this, cx| {
6505 this.unfold_ranges(unfold_ranges, true, true, cx);
6506 this.buffer.update(cx, |buffer, cx| {
6507 for (range, text) in edits {
6508 buffer.edit([(range, text)], None, cx);
6509 }
6510 });
6511 this.fold_ranges(refold_ranges, true, cx);
6512 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6513 s.select(new_selections);
6514 })
6515 });
6516 }
6517
6518 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6519 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6520 let buffer = self.buffer.read(cx).snapshot(cx);
6521
6522 let mut edits = Vec::new();
6523 let mut unfold_ranges = Vec::new();
6524 let mut refold_ranges = Vec::new();
6525
6526 let selections = self.selections.all::<Point>(cx);
6527 let mut selections = selections.iter().peekable();
6528 let mut contiguous_row_selections = Vec::new();
6529 let mut new_selections = Vec::new();
6530
6531 while let Some(selection) = selections.next() {
6532 // Find all the selections that span a contiguous row range
6533 let (start_row, end_row) = consume_contiguous_rows(
6534 &mut contiguous_row_selections,
6535 selection,
6536 &display_map,
6537 &mut selections,
6538 );
6539
6540 // Move the text spanned by the row range to be after the last line of the row range
6541 if end_row.0 <= buffer.max_point().row {
6542 let range_to_move =
6543 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6544 let insertion_point = display_map
6545 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6546 .0;
6547
6548 // Don't move lines across excerpt boundaries
6549 if buffer
6550 .excerpt_boundaries_in_range((
6551 Bound::Excluded(range_to_move.start),
6552 Bound::Included(insertion_point),
6553 ))
6554 .next()
6555 .is_none()
6556 {
6557 let mut text = String::from("\n");
6558 text.extend(buffer.text_for_range(range_to_move.clone()));
6559 text.pop(); // Drop trailing newline
6560 edits.push((
6561 buffer.anchor_after(range_to_move.start)
6562 ..buffer.anchor_before(range_to_move.end),
6563 String::new(),
6564 ));
6565 let insertion_anchor = buffer.anchor_after(insertion_point);
6566 edits.push((insertion_anchor..insertion_anchor, text));
6567
6568 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6569
6570 // Move selections down
6571 new_selections.extend(contiguous_row_selections.drain(..).map(
6572 |mut selection| {
6573 selection.start.row += row_delta;
6574 selection.end.row += row_delta;
6575 selection
6576 },
6577 ));
6578
6579 // Move folds down
6580 unfold_ranges.push(range_to_move.clone());
6581 for fold in display_map.folds_in_range(
6582 buffer.anchor_before(range_to_move.start)
6583 ..buffer.anchor_after(range_to_move.end),
6584 ) {
6585 let mut start = fold.range.start.to_point(&buffer);
6586 let mut end = fold.range.end.to_point(&buffer);
6587 start.row += row_delta;
6588 end.row += row_delta;
6589 refold_ranges.push((start..end, fold.placeholder.clone()));
6590 }
6591 }
6592 }
6593
6594 // If we didn't move line(s), preserve the existing selections
6595 new_selections.append(&mut contiguous_row_selections);
6596 }
6597
6598 self.transact(cx, |this, cx| {
6599 this.unfold_ranges(unfold_ranges, true, true, cx);
6600 this.buffer.update(cx, |buffer, cx| {
6601 for (range, text) in edits {
6602 buffer.edit([(range, text)], None, cx);
6603 }
6604 });
6605 this.fold_ranges(refold_ranges, true, cx);
6606 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6607 });
6608 }
6609
6610 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6611 let text_layout_details = &self.text_layout_details(cx);
6612 self.transact(cx, |this, cx| {
6613 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6614 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6615 let line_mode = s.line_mode;
6616 s.move_with(|display_map, selection| {
6617 if !selection.is_empty() || line_mode {
6618 return;
6619 }
6620
6621 let mut head = selection.head();
6622 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6623 if head.column() == display_map.line_len(head.row()) {
6624 transpose_offset = display_map
6625 .buffer_snapshot
6626 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6627 }
6628
6629 if transpose_offset == 0 {
6630 return;
6631 }
6632
6633 *head.column_mut() += 1;
6634 head = display_map.clip_point(head, Bias::Right);
6635 let goal = SelectionGoal::HorizontalPosition(
6636 display_map
6637 .x_for_display_point(head, &text_layout_details)
6638 .into(),
6639 );
6640 selection.collapse_to(head, goal);
6641
6642 let transpose_start = display_map
6643 .buffer_snapshot
6644 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6645 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6646 let transpose_end = display_map
6647 .buffer_snapshot
6648 .clip_offset(transpose_offset + 1, Bias::Right);
6649 if let Some(ch) =
6650 display_map.buffer_snapshot.chars_at(transpose_start).next()
6651 {
6652 edits.push((transpose_start..transpose_offset, String::new()));
6653 edits.push((transpose_end..transpose_end, ch.to_string()));
6654 }
6655 }
6656 });
6657 edits
6658 });
6659 this.buffer
6660 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6661 let selections = this.selections.all::<usize>(cx);
6662 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6663 s.select(selections);
6664 });
6665 });
6666 }
6667
6668 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6669 let mut text = String::new();
6670 let buffer = self.buffer.read(cx).snapshot(cx);
6671 let mut selections = self.selections.all::<Point>(cx);
6672 let mut clipboard_selections = Vec::with_capacity(selections.len());
6673 {
6674 let max_point = buffer.max_point();
6675 let mut is_first = true;
6676 for selection in &mut selections {
6677 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6678 if is_entire_line {
6679 selection.start = Point::new(selection.start.row, 0);
6680 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6681 selection.goal = SelectionGoal::None;
6682 }
6683 if is_first {
6684 is_first = false;
6685 } else {
6686 text += "\n";
6687 }
6688 let mut len = 0;
6689 for chunk in buffer.text_for_range(selection.start..selection.end) {
6690 text.push_str(chunk);
6691 len += chunk.len();
6692 }
6693 clipboard_selections.push(ClipboardSelection {
6694 len,
6695 is_entire_line,
6696 first_line_indent: buffer
6697 .indent_size_for_line(MultiBufferRow(selection.start.row))
6698 .len,
6699 });
6700 }
6701 }
6702
6703 self.transact(cx, |this, cx| {
6704 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6705 s.select(selections);
6706 });
6707 this.insert("", cx);
6708 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6709 text,
6710 clipboard_selections,
6711 ));
6712 });
6713 }
6714
6715 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6716 let selections = self.selections.all::<Point>(cx);
6717 let buffer = self.buffer.read(cx).read(cx);
6718 let mut text = String::new();
6719
6720 let mut clipboard_selections = Vec::with_capacity(selections.len());
6721 {
6722 let max_point = buffer.max_point();
6723 let mut is_first = true;
6724 for selection in selections.iter() {
6725 let mut start = selection.start;
6726 let mut end = selection.end;
6727 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6728 if is_entire_line {
6729 start = Point::new(start.row, 0);
6730 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6731 }
6732 if is_first {
6733 is_first = false;
6734 } else {
6735 text += "\n";
6736 }
6737 let mut len = 0;
6738 for chunk in buffer.text_for_range(start..end) {
6739 text.push_str(chunk);
6740 len += chunk.len();
6741 }
6742 clipboard_selections.push(ClipboardSelection {
6743 len,
6744 is_entire_line,
6745 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6746 });
6747 }
6748 }
6749
6750 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6751 text,
6752 clipboard_selections,
6753 ));
6754 }
6755
6756 pub fn do_paste(
6757 &mut self,
6758 text: &String,
6759 clipboard_selections: Option<Vec<ClipboardSelection>>,
6760 handle_entire_lines: bool,
6761 cx: &mut ViewContext<Self>,
6762 ) {
6763 if self.read_only(cx) {
6764 return;
6765 }
6766
6767 let clipboard_text = Cow::Borrowed(text);
6768
6769 self.transact(cx, |this, cx| {
6770 if let Some(mut clipboard_selections) = clipboard_selections {
6771 let old_selections = this.selections.all::<usize>(cx);
6772 let all_selections_were_entire_line =
6773 clipboard_selections.iter().all(|s| s.is_entire_line);
6774 let first_selection_indent_column =
6775 clipboard_selections.first().map(|s| s.first_line_indent);
6776 if clipboard_selections.len() != old_selections.len() {
6777 clipboard_selections.drain(..);
6778 }
6779
6780 this.buffer.update(cx, |buffer, cx| {
6781 let snapshot = buffer.read(cx);
6782 let mut start_offset = 0;
6783 let mut edits = Vec::new();
6784 let mut original_indent_columns = Vec::new();
6785 for (ix, selection) in old_selections.iter().enumerate() {
6786 let to_insert;
6787 let entire_line;
6788 let original_indent_column;
6789 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6790 let end_offset = start_offset + clipboard_selection.len;
6791 to_insert = &clipboard_text[start_offset..end_offset];
6792 entire_line = clipboard_selection.is_entire_line;
6793 start_offset = end_offset + 1;
6794 original_indent_column = Some(clipboard_selection.first_line_indent);
6795 } else {
6796 to_insert = clipboard_text.as_str();
6797 entire_line = all_selections_were_entire_line;
6798 original_indent_column = first_selection_indent_column
6799 }
6800
6801 // If the corresponding selection was empty when this slice of the
6802 // clipboard text was written, then the entire line containing the
6803 // selection was copied. If this selection is also currently empty,
6804 // then paste the line before the current line of the buffer.
6805 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6806 let column = selection.start.to_point(&snapshot).column as usize;
6807 let line_start = selection.start - column;
6808 line_start..line_start
6809 } else {
6810 selection.range()
6811 };
6812
6813 edits.push((range, to_insert));
6814 original_indent_columns.extend(original_indent_column);
6815 }
6816 drop(snapshot);
6817
6818 buffer.edit(
6819 edits,
6820 Some(AutoindentMode::Block {
6821 original_indent_columns,
6822 }),
6823 cx,
6824 );
6825 });
6826
6827 let selections = this.selections.all::<usize>(cx);
6828 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6829 } else {
6830 this.insert(&clipboard_text, cx);
6831 }
6832 });
6833 }
6834
6835 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
6836 if let Some(item) = cx.read_from_clipboard() {
6837 let entries = item.entries();
6838
6839 match entries.first() {
6840 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
6841 // of all the pasted entries.
6842 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
6843 .do_paste(
6844 clipboard_string.text(),
6845 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
6846 true,
6847 cx,
6848 ),
6849 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
6850 }
6851 }
6852 }
6853
6854 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
6855 if self.read_only(cx) {
6856 return;
6857 }
6858
6859 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
6860 if let Some((selections, _)) =
6861 self.selection_history.transaction(transaction_id).cloned()
6862 {
6863 self.change_selections(None, cx, |s| {
6864 s.select_anchors(selections.to_vec());
6865 });
6866 }
6867 self.request_autoscroll(Autoscroll::fit(), cx);
6868 self.unmark_text(cx);
6869 self.refresh_inline_completion(true, false, cx);
6870 cx.emit(EditorEvent::Edited { transaction_id });
6871 cx.emit(EditorEvent::TransactionUndone { transaction_id });
6872 }
6873 }
6874
6875 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
6876 if self.read_only(cx) {
6877 return;
6878 }
6879
6880 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
6881 if let Some((_, Some(selections))) =
6882 self.selection_history.transaction(transaction_id).cloned()
6883 {
6884 self.change_selections(None, cx, |s| {
6885 s.select_anchors(selections.to_vec());
6886 });
6887 }
6888 self.request_autoscroll(Autoscroll::fit(), cx);
6889 self.unmark_text(cx);
6890 self.refresh_inline_completion(true, false, cx);
6891 cx.emit(EditorEvent::Edited { transaction_id });
6892 }
6893 }
6894
6895 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
6896 self.buffer
6897 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
6898 }
6899
6900 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
6901 self.buffer
6902 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
6903 }
6904
6905 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
6906 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6907 let line_mode = s.line_mode;
6908 s.move_with(|map, selection| {
6909 let cursor = if selection.is_empty() && !line_mode {
6910 movement::left(map, selection.start)
6911 } else {
6912 selection.start
6913 };
6914 selection.collapse_to(cursor, SelectionGoal::None);
6915 });
6916 })
6917 }
6918
6919 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
6920 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6921 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
6922 })
6923 }
6924
6925 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
6926 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6927 let line_mode = s.line_mode;
6928 s.move_with(|map, selection| {
6929 let cursor = if selection.is_empty() && !line_mode {
6930 movement::right(map, selection.end)
6931 } else {
6932 selection.end
6933 };
6934 selection.collapse_to(cursor, SelectionGoal::None)
6935 });
6936 })
6937 }
6938
6939 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
6940 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6941 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
6942 })
6943 }
6944
6945 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
6946 if self.take_rename(true, cx).is_some() {
6947 return;
6948 }
6949
6950 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6951 cx.propagate();
6952 return;
6953 }
6954
6955 let text_layout_details = &self.text_layout_details(cx);
6956 let selection_count = self.selections.count();
6957 let first_selection = self.selections.first_anchor();
6958
6959 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6960 let line_mode = s.line_mode;
6961 s.move_with(|map, selection| {
6962 if !selection.is_empty() && !line_mode {
6963 selection.goal = SelectionGoal::None;
6964 }
6965 let (cursor, goal) = movement::up(
6966 map,
6967 selection.start,
6968 selection.goal,
6969 false,
6970 &text_layout_details,
6971 );
6972 selection.collapse_to(cursor, goal);
6973 });
6974 });
6975
6976 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
6977 {
6978 cx.propagate();
6979 }
6980 }
6981
6982 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
6983 if self.take_rename(true, cx).is_some() {
6984 return;
6985 }
6986
6987 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6988 cx.propagate();
6989 return;
6990 }
6991
6992 let text_layout_details = &self.text_layout_details(cx);
6993
6994 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6995 let line_mode = s.line_mode;
6996 s.move_with(|map, selection| {
6997 if !selection.is_empty() && !line_mode {
6998 selection.goal = SelectionGoal::None;
6999 }
7000 let (cursor, goal) = movement::up_by_rows(
7001 map,
7002 selection.start,
7003 action.lines,
7004 selection.goal,
7005 false,
7006 &text_layout_details,
7007 );
7008 selection.collapse_to(cursor, goal);
7009 });
7010 })
7011 }
7012
7013 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7014 if self.take_rename(true, cx).is_some() {
7015 return;
7016 }
7017
7018 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7019 cx.propagate();
7020 return;
7021 }
7022
7023 let text_layout_details = &self.text_layout_details(cx);
7024
7025 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7026 let line_mode = s.line_mode;
7027 s.move_with(|map, selection| {
7028 if !selection.is_empty() && !line_mode {
7029 selection.goal = SelectionGoal::None;
7030 }
7031 let (cursor, goal) = movement::down_by_rows(
7032 map,
7033 selection.start,
7034 action.lines,
7035 selection.goal,
7036 false,
7037 &text_layout_details,
7038 );
7039 selection.collapse_to(cursor, goal);
7040 });
7041 })
7042 }
7043
7044 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7045 let text_layout_details = &self.text_layout_details(cx);
7046 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7047 s.move_heads_with(|map, head, goal| {
7048 movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
7049 })
7050 })
7051 }
7052
7053 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7054 let text_layout_details = &self.text_layout_details(cx);
7055 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7056 s.move_heads_with(|map, head, goal| {
7057 movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
7058 })
7059 })
7060 }
7061
7062 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7063 let Some(row_count) = self.visible_row_count() else {
7064 return;
7065 };
7066
7067 let text_layout_details = &self.text_layout_details(cx);
7068
7069 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7070 s.move_heads_with(|map, head, goal| {
7071 movement::up_by_rows(map, head, row_count, goal, false, &text_layout_details)
7072 })
7073 })
7074 }
7075
7076 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7077 if self.take_rename(true, cx).is_some() {
7078 return;
7079 }
7080
7081 if self
7082 .context_menu
7083 .write()
7084 .as_mut()
7085 .map(|menu| menu.select_first(self.project.as_ref(), cx))
7086 .unwrap_or(false)
7087 {
7088 return;
7089 }
7090
7091 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7092 cx.propagate();
7093 return;
7094 }
7095
7096 let Some(row_count) = self.visible_row_count() else {
7097 return;
7098 };
7099
7100 let autoscroll = if action.center_cursor {
7101 Autoscroll::center()
7102 } else {
7103 Autoscroll::fit()
7104 };
7105
7106 let text_layout_details = &self.text_layout_details(cx);
7107
7108 self.change_selections(Some(autoscroll), cx, |s| {
7109 let line_mode = s.line_mode;
7110 s.move_with(|map, selection| {
7111 if !selection.is_empty() && !line_mode {
7112 selection.goal = SelectionGoal::None;
7113 }
7114 let (cursor, goal) = movement::up_by_rows(
7115 map,
7116 selection.end,
7117 row_count,
7118 selection.goal,
7119 false,
7120 &text_layout_details,
7121 );
7122 selection.collapse_to(cursor, goal);
7123 });
7124 });
7125 }
7126
7127 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7128 let text_layout_details = &self.text_layout_details(cx);
7129 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7130 s.move_heads_with(|map, head, goal| {
7131 movement::up(map, head, goal, false, &text_layout_details)
7132 })
7133 })
7134 }
7135
7136 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7137 self.take_rename(true, cx);
7138
7139 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7140 cx.propagate();
7141 return;
7142 }
7143
7144 let text_layout_details = &self.text_layout_details(cx);
7145 let selection_count = self.selections.count();
7146 let first_selection = self.selections.first_anchor();
7147
7148 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7149 let line_mode = s.line_mode;
7150 s.move_with(|map, selection| {
7151 if !selection.is_empty() && !line_mode {
7152 selection.goal = SelectionGoal::None;
7153 }
7154 let (cursor, goal) = movement::down(
7155 map,
7156 selection.end,
7157 selection.goal,
7158 false,
7159 &text_layout_details,
7160 );
7161 selection.collapse_to(cursor, goal);
7162 });
7163 });
7164
7165 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7166 {
7167 cx.propagate();
7168 }
7169 }
7170
7171 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7172 let Some(row_count) = self.visible_row_count() else {
7173 return;
7174 };
7175
7176 let text_layout_details = &self.text_layout_details(cx);
7177
7178 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7179 s.move_heads_with(|map, head, goal| {
7180 movement::down_by_rows(map, head, row_count, goal, false, &text_layout_details)
7181 })
7182 })
7183 }
7184
7185 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7186 if self.take_rename(true, cx).is_some() {
7187 return;
7188 }
7189
7190 if self
7191 .context_menu
7192 .write()
7193 .as_mut()
7194 .map(|menu| menu.select_last(self.project.as_ref(), cx))
7195 .unwrap_or(false)
7196 {
7197 return;
7198 }
7199
7200 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7201 cx.propagate();
7202 return;
7203 }
7204
7205 let Some(row_count) = self.visible_row_count() else {
7206 return;
7207 };
7208
7209 let autoscroll = if action.center_cursor {
7210 Autoscroll::center()
7211 } else {
7212 Autoscroll::fit()
7213 };
7214
7215 let text_layout_details = &self.text_layout_details(cx);
7216 self.change_selections(Some(autoscroll), cx, |s| {
7217 let line_mode = s.line_mode;
7218 s.move_with(|map, selection| {
7219 if !selection.is_empty() && !line_mode {
7220 selection.goal = SelectionGoal::None;
7221 }
7222 let (cursor, goal) = movement::down_by_rows(
7223 map,
7224 selection.end,
7225 row_count,
7226 selection.goal,
7227 false,
7228 &text_layout_details,
7229 );
7230 selection.collapse_to(cursor, goal);
7231 });
7232 });
7233 }
7234
7235 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7236 let text_layout_details = &self.text_layout_details(cx);
7237 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7238 s.move_heads_with(|map, head, goal| {
7239 movement::down(map, head, goal, false, &text_layout_details)
7240 })
7241 });
7242 }
7243
7244 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7245 if let Some(context_menu) = self.context_menu.write().as_mut() {
7246 context_menu.select_first(self.project.as_ref(), cx);
7247 }
7248 }
7249
7250 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7251 if let Some(context_menu) = self.context_menu.write().as_mut() {
7252 context_menu.select_prev(self.project.as_ref(), cx);
7253 }
7254 }
7255
7256 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7257 if let Some(context_menu) = self.context_menu.write().as_mut() {
7258 context_menu.select_next(self.project.as_ref(), cx);
7259 }
7260 }
7261
7262 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7263 if let Some(context_menu) = self.context_menu.write().as_mut() {
7264 context_menu.select_last(self.project.as_ref(), cx);
7265 }
7266 }
7267
7268 pub fn move_to_previous_word_start(
7269 &mut self,
7270 _: &MoveToPreviousWordStart,
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::previous_word_start(map, head),
7277 SelectionGoal::None,
7278 )
7279 });
7280 })
7281 }
7282
7283 pub fn move_to_previous_subword_start(
7284 &mut self,
7285 _: &MoveToPreviousSubwordStart,
7286 cx: &mut ViewContext<Self>,
7287 ) {
7288 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7289 s.move_cursors_with(|map, head, _| {
7290 (
7291 movement::previous_subword_start(map, head),
7292 SelectionGoal::None,
7293 )
7294 });
7295 })
7296 }
7297
7298 pub fn select_to_previous_word_start(
7299 &mut self,
7300 _: &SelectToPreviousWordStart,
7301 cx: &mut ViewContext<Self>,
7302 ) {
7303 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7304 s.move_heads_with(|map, head, _| {
7305 (
7306 movement::previous_word_start(map, head),
7307 SelectionGoal::None,
7308 )
7309 });
7310 })
7311 }
7312
7313 pub fn select_to_previous_subword_start(
7314 &mut self,
7315 _: &SelectToPreviousSubwordStart,
7316 cx: &mut ViewContext<Self>,
7317 ) {
7318 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7319 s.move_heads_with(|map, head, _| {
7320 (
7321 movement::previous_subword_start(map, head),
7322 SelectionGoal::None,
7323 )
7324 });
7325 })
7326 }
7327
7328 pub fn delete_to_previous_word_start(
7329 &mut self,
7330 _: &DeleteToPreviousWordStart,
7331 cx: &mut ViewContext<Self>,
7332 ) {
7333 self.transact(cx, |this, cx| {
7334 this.select_autoclose_pair(cx);
7335 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7336 let line_mode = s.line_mode;
7337 s.move_with(|map, selection| {
7338 if selection.is_empty() && !line_mode {
7339 let cursor = movement::previous_word_start(map, selection.head());
7340 selection.set_head(cursor, SelectionGoal::None);
7341 }
7342 });
7343 });
7344 this.insert("", cx);
7345 });
7346 }
7347
7348 pub fn delete_to_previous_subword_start(
7349 &mut self,
7350 _: &DeleteToPreviousSubwordStart,
7351 cx: &mut ViewContext<Self>,
7352 ) {
7353 self.transact(cx, |this, cx| {
7354 this.select_autoclose_pair(cx);
7355 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7356 let line_mode = s.line_mode;
7357 s.move_with(|map, selection| {
7358 if selection.is_empty() && !line_mode {
7359 let cursor = movement::previous_subword_start(map, selection.head());
7360 selection.set_head(cursor, SelectionGoal::None);
7361 }
7362 });
7363 });
7364 this.insert("", cx);
7365 });
7366 }
7367
7368 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7369 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7370 s.move_cursors_with(|map, head, _| {
7371 (movement::next_word_end(map, head), SelectionGoal::None)
7372 });
7373 })
7374 }
7375
7376 pub fn move_to_next_subword_end(
7377 &mut self,
7378 _: &MoveToNextSubwordEnd,
7379 cx: &mut ViewContext<Self>,
7380 ) {
7381 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7382 s.move_cursors_with(|map, head, _| {
7383 (movement::next_subword_end(map, head), SelectionGoal::None)
7384 });
7385 })
7386 }
7387
7388 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7389 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7390 s.move_heads_with(|map, head, _| {
7391 (movement::next_word_end(map, head), SelectionGoal::None)
7392 });
7393 })
7394 }
7395
7396 pub fn select_to_next_subword_end(
7397 &mut self,
7398 _: &SelectToNextSubwordEnd,
7399 cx: &mut ViewContext<Self>,
7400 ) {
7401 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7402 s.move_heads_with(|map, head, _| {
7403 (movement::next_subword_end(map, head), SelectionGoal::None)
7404 });
7405 })
7406 }
7407
7408 pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
7409 self.transact(cx, |this, cx| {
7410 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7411 let line_mode = s.line_mode;
7412 s.move_with(|map, selection| {
7413 if selection.is_empty() && !line_mode {
7414 let cursor = movement::next_word_end(map, selection.head());
7415 selection.set_head(cursor, SelectionGoal::None);
7416 }
7417 });
7418 });
7419 this.insert("", cx);
7420 });
7421 }
7422
7423 pub fn delete_to_next_subword_end(
7424 &mut self,
7425 _: &DeleteToNextSubwordEnd,
7426 cx: &mut ViewContext<Self>,
7427 ) {
7428 self.transact(cx, |this, cx| {
7429 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7430 s.move_with(|map, selection| {
7431 if selection.is_empty() {
7432 let cursor = movement::next_subword_end(map, selection.head());
7433 selection.set_head(cursor, SelectionGoal::None);
7434 }
7435 });
7436 });
7437 this.insert("", cx);
7438 });
7439 }
7440
7441 pub fn move_to_beginning_of_line(
7442 &mut self,
7443 action: &MoveToBeginningOfLine,
7444 cx: &mut ViewContext<Self>,
7445 ) {
7446 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7447 s.move_cursors_with(|map, head, _| {
7448 (
7449 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7450 SelectionGoal::None,
7451 )
7452 });
7453 })
7454 }
7455
7456 pub fn select_to_beginning_of_line(
7457 &mut self,
7458 action: &SelectToBeginningOfLine,
7459 cx: &mut ViewContext<Self>,
7460 ) {
7461 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7462 s.move_heads_with(|map, head, _| {
7463 (
7464 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7465 SelectionGoal::None,
7466 )
7467 });
7468 });
7469 }
7470
7471 pub fn delete_to_beginning_of_line(
7472 &mut self,
7473 _: &DeleteToBeginningOfLine,
7474 cx: &mut ViewContext<Self>,
7475 ) {
7476 self.transact(cx, |this, cx| {
7477 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7478 s.move_with(|_, selection| {
7479 selection.reversed = true;
7480 });
7481 });
7482
7483 this.select_to_beginning_of_line(
7484 &SelectToBeginningOfLine {
7485 stop_at_soft_wraps: false,
7486 },
7487 cx,
7488 );
7489 this.backspace(&Backspace, cx);
7490 });
7491 }
7492
7493 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7494 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7495 s.move_cursors_with(|map, head, _| {
7496 (
7497 movement::line_end(map, head, action.stop_at_soft_wraps),
7498 SelectionGoal::None,
7499 )
7500 });
7501 })
7502 }
7503
7504 pub fn select_to_end_of_line(
7505 &mut self,
7506 action: &SelectToEndOfLine,
7507 cx: &mut ViewContext<Self>,
7508 ) {
7509 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7510 s.move_heads_with(|map, head, _| {
7511 (
7512 movement::line_end(map, head, action.stop_at_soft_wraps),
7513 SelectionGoal::None,
7514 )
7515 });
7516 })
7517 }
7518
7519 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7520 self.transact(cx, |this, cx| {
7521 this.select_to_end_of_line(
7522 &SelectToEndOfLine {
7523 stop_at_soft_wraps: false,
7524 },
7525 cx,
7526 );
7527 this.delete(&Delete, cx);
7528 });
7529 }
7530
7531 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7532 self.transact(cx, |this, cx| {
7533 this.select_to_end_of_line(
7534 &SelectToEndOfLine {
7535 stop_at_soft_wraps: false,
7536 },
7537 cx,
7538 );
7539 this.cut(&Cut, cx);
7540 });
7541 }
7542
7543 pub fn move_to_start_of_paragraph(
7544 &mut self,
7545 _: &MoveToStartOfParagraph,
7546 cx: &mut ViewContext<Self>,
7547 ) {
7548 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7549 cx.propagate();
7550 return;
7551 }
7552
7553 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7554 s.move_with(|map, selection| {
7555 selection.collapse_to(
7556 movement::start_of_paragraph(map, selection.head(), 1),
7557 SelectionGoal::None,
7558 )
7559 });
7560 })
7561 }
7562
7563 pub fn move_to_end_of_paragraph(
7564 &mut self,
7565 _: &MoveToEndOfParagraph,
7566 cx: &mut ViewContext<Self>,
7567 ) {
7568 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7569 cx.propagate();
7570 return;
7571 }
7572
7573 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7574 s.move_with(|map, selection| {
7575 selection.collapse_to(
7576 movement::end_of_paragraph(map, selection.head(), 1),
7577 SelectionGoal::None,
7578 )
7579 });
7580 })
7581 }
7582
7583 pub fn select_to_start_of_paragraph(
7584 &mut self,
7585 _: &SelectToStartOfParagraph,
7586 cx: &mut ViewContext<Self>,
7587 ) {
7588 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7589 cx.propagate();
7590 return;
7591 }
7592
7593 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7594 s.move_heads_with(|map, head, _| {
7595 (
7596 movement::start_of_paragraph(map, head, 1),
7597 SelectionGoal::None,
7598 )
7599 });
7600 })
7601 }
7602
7603 pub fn select_to_end_of_paragraph(
7604 &mut self,
7605 _: &SelectToEndOfParagraph,
7606 cx: &mut ViewContext<Self>,
7607 ) {
7608 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7609 cx.propagate();
7610 return;
7611 }
7612
7613 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7614 s.move_heads_with(|map, head, _| {
7615 (
7616 movement::end_of_paragraph(map, head, 1),
7617 SelectionGoal::None,
7618 )
7619 });
7620 })
7621 }
7622
7623 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7624 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7625 cx.propagate();
7626 return;
7627 }
7628
7629 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7630 s.select_ranges(vec![0..0]);
7631 });
7632 }
7633
7634 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7635 let mut selection = self.selections.last::<Point>(cx);
7636 selection.set_head(Point::zero(), SelectionGoal::None);
7637
7638 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7639 s.select(vec![selection]);
7640 });
7641 }
7642
7643 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7644 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7645 cx.propagate();
7646 return;
7647 }
7648
7649 let cursor = self.buffer.read(cx).read(cx).len();
7650 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7651 s.select_ranges(vec![cursor..cursor])
7652 });
7653 }
7654
7655 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7656 self.nav_history = nav_history;
7657 }
7658
7659 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7660 self.nav_history.as_ref()
7661 }
7662
7663 fn push_to_nav_history(
7664 &mut self,
7665 cursor_anchor: Anchor,
7666 new_position: Option<Point>,
7667 cx: &mut ViewContext<Self>,
7668 ) {
7669 if let Some(nav_history) = self.nav_history.as_mut() {
7670 let buffer = self.buffer.read(cx).read(cx);
7671 let cursor_position = cursor_anchor.to_point(&buffer);
7672 let scroll_state = self.scroll_manager.anchor();
7673 let scroll_top_row = scroll_state.top_row(&buffer);
7674 drop(buffer);
7675
7676 if let Some(new_position) = new_position {
7677 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7678 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7679 return;
7680 }
7681 }
7682
7683 nav_history.push(
7684 Some(NavigationData {
7685 cursor_anchor,
7686 cursor_position,
7687 scroll_anchor: scroll_state,
7688 scroll_top_row,
7689 }),
7690 cx,
7691 );
7692 }
7693 }
7694
7695 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7696 let buffer = self.buffer.read(cx).snapshot(cx);
7697 let mut selection = self.selections.first::<usize>(cx);
7698 selection.set_head(buffer.len(), SelectionGoal::None);
7699 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7700 s.select(vec![selection]);
7701 });
7702 }
7703
7704 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7705 let end = self.buffer.read(cx).read(cx).len();
7706 self.change_selections(None, cx, |s| {
7707 s.select_ranges(vec![0..end]);
7708 });
7709 }
7710
7711 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7712 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7713 let mut selections = self.selections.all::<Point>(cx);
7714 let max_point = display_map.buffer_snapshot.max_point();
7715 for selection in &mut selections {
7716 let rows = selection.spanned_rows(true, &display_map);
7717 selection.start = Point::new(rows.start.0, 0);
7718 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7719 selection.reversed = false;
7720 }
7721 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7722 s.select(selections);
7723 });
7724 }
7725
7726 pub fn split_selection_into_lines(
7727 &mut self,
7728 _: &SplitSelectionIntoLines,
7729 cx: &mut ViewContext<Self>,
7730 ) {
7731 let mut to_unfold = Vec::new();
7732 let mut new_selection_ranges = Vec::new();
7733 {
7734 let selections = self.selections.all::<Point>(cx);
7735 let buffer = self.buffer.read(cx).read(cx);
7736 for selection in selections {
7737 for row in selection.start.row..selection.end.row {
7738 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7739 new_selection_ranges.push(cursor..cursor);
7740 }
7741 new_selection_ranges.push(selection.end..selection.end);
7742 to_unfold.push(selection.start..selection.end);
7743 }
7744 }
7745 self.unfold_ranges(to_unfold, true, true, cx);
7746 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7747 s.select_ranges(new_selection_ranges);
7748 });
7749 }
7750
7751 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7752 self.add_selection(true, cx);
7753 }
7754
7755 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7756 self.add_selection(false, cx);
7757 }
7758
7759 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7760 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7761 let mut selections = self.selections.all::<Point>(cx);
7762 let text_layout_details = self.text_layout_details(cx);
7763 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7764 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7765 let range = oldest_selection.display_range(&display_map).sorted();
7766
7767 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7768 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7769 let positions = start_x.min(end_x)..start_x.max(end_x);
7770
7771 selections.clear();
7772 let mut stack = Vec::new();
7773 for row in range.start.row().0..=range.end.row().0 {
7774 if let Some(selection) = self.selections.build_columnar_selection(
7775 &display_map,
7776 DisplayRow(row),
7777 &positions,
7778 oldest_selection.reversed,
7779 &text_layout_details,
7780 ) {
7781 stack.push(selection.id);
7782 selections.push(selection);
7783 }
7784 }
7785
7786 if above {
7787 stack.reverse();
7788 }
7789
7790 AddSelectionsState { above, stack }
7791 });
7792
7793 let last_added_selection = *state.stack.last().unwrap();
7794 let mut new_selections = Vec::new();
7795 if above == state.above {
7796 let end_row = if above {
7797 DisplayRow(0)
7798 } else {
7799 display_map.max_point().row()
7800 };
7801
7802 'outer: for selection in selections {
7803 if selection.id == last_added_selection {
7804 let range = selection.display_range(&display_map).sorted();
7805 debug_assert_eq!(range.start.row(), range.end.row());
7806 let mut row = range.start.row();
7807 let positions =
7808 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7809 px(start)..px(end)
7810 } else {
7811 let start_x =
7812 display_map.x_for_display_point(range.start, &text_layout_details);
7813 let end_x =
7814 display_map.x_for_display_point(range.end, &text_layout_details);
7815 start_x.min(end_x)..start_x.max(end_x)
7816 };
7817
7818 while row != end_row {
7819 if above {
7820 row.0 -= 1;
7821 } else {
7822 row.0 += 1;
7823 }
7824
7825 if let Some(new_selection) = self.selections.build_columnar_selection(
7826 &display_map,
7827 row,
7828 &positions,
7829 selection.reversed,
7830 &text_layout_details,
7831 ) {
7832 state.stack.push(new_selection.id);
7833 if above {
7834 new_selections.push(new_selection);
7835 new_selections.push(selection);
7836 } else {
7837 new_selections.push(selection);
7838 new_selections.push(new_selection);
7839 }
7840
7841 continue 'outer;
7842 }
7843 }
7844 }
7845
7846 new_selections.push(selection);
7847 }
7848 } else {
7849 new_selections = selections;
7850 new_selections.retain(|s| s.id != last_added_selection);
7851 state.stack.pop();
7852 }
7853
7854 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7855 s.select(new_selections);
7856 });
7857 if state.stack.len() > 1 {
7858 self.add_selections_state = Some(state);
7859 }
7860 }
7861
7862 pub fn select_next_match_internal(
7863 &mut self,
7864 display_map: &DisplaySnapshot,
7865 replace_newest: bool,
7866 autoscroll: Option<Autoscroll>,
7867 cx: &mut ViewContext<Self>,
7868 ) -> Result<()> {
7869 fn select_next_match_ranges(
7870 this: &mut Editor,
7871 range: Range<usize>,
7872 replace_newest: bool,
7873 auto_scroll: Option<Autoscroll>,
7874 cx: &mut ViewContext<Editor>,
7875 ) {
7876 this.unfold_ranges([range.clone()], false, true, cx);
7877 this.change_selections(auto_scroll, cx, |s| {
7878 if replace_newest {
7879 s.delete(s.newest_anchor().id);
7880 }
7881 s.insert_range(range.clone());
7882 });
7883 }
7884
7885 let buffer = &display_map.buffer_snapshot;
7886 let mut selections = self.selections.all::<usize>(cx);
7887 if let Some(mut select_next_state) = self.select_next_state.take() {
7888 let query = &select_next_state.query;
7889 if !select_next_state.done {
7890 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7891 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7892 let mut next_selected_range = None;
7893
7894 let bytes_after_last_selection =
7895 buffer.bytes_in_range(last_selection.end..buffer.len());
7896 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
7897 let query_matches = query
7898 .stream_find_iter(bytes_after_last_selection)
7899 .map(|result| (last_selection.end, result))
7900 .chain(
7901 query
7902 .stream_find_iter(bytes_before_first_selection)
7903 .map(|result| (0, result)),
7904 );
7905
7906 for (start_offset, query_match) in query_matches {
7907 let query_match = query_match.unwrap(); // can only fail due to I/O
7908 let offset_range =
7909 start_offset + query_match.start()..start_offset + query_match.end();
7910 let display_range = offset_range.start.to_display_point(&display_map)
7911 ..offset_range.end.to_display_point(&display_map);
7912
7913 if !select_next_state.wordwise
7914 || (!movement::is_inside_word(&display_map, display_range.start)
7915 && !movement::is_inside_word(&display_map, display_range.end))
7916 {
7917 // TODO: This is n^2, because we might check all the selections
7918 if !selections
7919 .iter()
7920 .any(|selection| selection.range().overlaps(&offset_range))
7921 {
7922 next_selected_range = Some(offset_range);
7923 break;
7924 }
7925 }
7926 }
7927
7928 if let Some(next_selected_range) = next_selected_range {
7929 select_next_match_ranges(
7930 self,
7931 next_selected_range,
7932 replace_newest,
7933 autoscroll,
7934 cx,
7935 );
7936 } else {
7937 select_next_state.done = true;
7938 }
7939 }
7940
7941 self.select_next_state = Some(select_next_state);
7942 } else {
7943 let mut only_carets = true;
7944 let mut same_text_selected = true;
7945 let mut selected_text = None;
7946
7947 let mut selections_iter = selections.iter().peekable();
7948 while let Some(selection) = selections_iter.next() {
7949 if selection.start != selection.end {
7950 only_carets = false;
7951 }
7952
7953 if same_text_selected {
7954 if selected_text.is_none() {
7955 selected_text =
7956 Some(buffer.text_for_range(selection.range()).collect::<String>());
7957 }
7958
7959 if let Some(next_selection) = selections_iter.peek() {
7960 if next_selection.range().len() == selection.range().len() {
7961 let next_selected_text = buffer
7962 .text_for_range(next_selection.range())
7963 .collect::<String>();
7964 if Some(next_selected_text) != selected_text {
7965 same_text_selected = false;
7966 selected_text = None;
7967 }
7968 } else {
7969 same_text_selected = false;
7970 selected_text = None;
7971 }
7972 }
7973 }
7974 }
7975
7976 if only_carets {
7977 for selection in &mut selections {
7978 let word_range = movement::surrounding_word(
7979 &display_map,
7980 selection.start.to_display_point(&display_map),
7981 );
7982 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
7983 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
7984 selection.goal = SelectionGoal::None;
7985 selection.reversed = false;
7986 select_next_match_ranges(
7987 self,
7988 selection.start..selection.end,
7989 replace_newest,
7990 autoscroll,
7991 cx,
7992 );
7993 }
7994
7995 if selections.len() == 1 {
7996 let selection = selections
7997 .last()
7998 .expect("ensured that there's only one selection");
7999 let query = buffer
8000 .text_for_range(selection.start..selection.end)
8001 .collect::<String>();
8002 let is_empty = query.is_empty();
8003 let select_state = SelectNextState {
8004 query: AhoCorasick::new(&[query])?,
8005 wordwise: true,
8006 done: is_empty,
8007 };
8008 self.select_next_state = Some(select_state);
8009 } else {
8010 self.select_next_state = None;
8011 }
8012 } else if let Some(selected_text) = selected_text {
8013 self.select_next_state = Some(SelectNextState {
8014 query: AhoCorasick::new(&[selected_text])?,
8015 wordwise: false,
8016 done: false,
8017 });
8018 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8019 }
8020 }
8021 Ok(())
8022 }
8023
8024 pub fn select_all_matches(
8025 &mut self,
8026 _action: &SelectAllMatches,
8027 cx: &mut ViewContext<Self>,
8028 ) -> Result<()> {
8029 self.push_to_selection_history();
8030 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8031
8032 self.select_next_match_internal(&display_map, false, None, cx)?;
8033 let Some(select_next_state) = self.select_next_state.as_mut() else {
8034 return Ok(());
8035 };
8036 if select_next_state.done {
8037 return Ok(());
8038 }
8039
8040 let mut new_selections = self.selections.all::<usize>(cx);
8041
8042 let buffer = &display_map.buffer_snapshot;
8043 let query_matches = select_next_state
8044 .query
8045 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8046
8047 for query_match in query_matches {
8048 let query_match = query_match.unwrap(); // can only fail due to I/O
8049 let offset_range = query_match.start()..query_match.end();
8050 let display_range = offset_range.start.to_display_point(&display_map)
8051 ..offset_range.end.to_display_point(&display_map);
8052
8053 if !select_next_state.wordwise
8054 || (!movement::is_inside_word(&display_map, display_range.start)
8055 && !movement::is_inside_word(&display_map, display_range.end))
8056 {
8057 self.selections.change_with(cx, |selections| {
8058 new_selections.push(Selection {
8059 id: selections.new_selection_id(),
8060 start: offset_range.start,
8061 end: offset_range.end,
8062 reversed: false,
8063 goal: SelectionGoal::None,
8064 });
8065 });
8066 }
8067 }
8068
8069 new_selections.sort_by_key(|selection| selection.start);
8070 let mut ix = 0;
8071 while ix + 1 < new_selections.len() {
8072 let current_selection = &new_selections[ix];
8073 let next_selection = &new_selections[ix + 1];
8074 if current_selection.range().overlaps(&next_selection.range()) {
8075 if current_selection.id < next_selection.id {
8076 new_selections.remove(ix + 1);
8077 } else {
8078 new_selections.remove(ix);
8079 }
8080 } else {
8081 ix += 1;
8082 }
8083 }
8084
8085 select_next_state.done = true;
8086 self.unfold_ranges(
8087 new_selections.iter().map(|selection| selection.range()),
8088 false,
8089 false,
8090 cx,
8091 );
8092 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8093 selections.select(new_selections)
8094 });
8095
8096 Ok(())
8097 }
8098
8099 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8100 self.push_to_selection_history();
8101 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8102 self.select_next_match_internal(
8103 &display_map,
8104 action.replace_newest,
8105 Some(Autoscroll::newest()),
8106 cx,
8107 )?;
8108 Ok(())
8109 }
8110
8111 pub fn select_previous(
8112 &mut self,
8113 action: &SelectPrevious,
8114 cx: &mut ViewContext<Self>,
8115 ) -> Result<()> {
8116 self.push_to_selection_history();
8117 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8118 let buffer = &display_map.buffer_snapshot;
8119 let mut selections = self.selections.all::<usize>(cx);
8120 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8121 let query = &select_prev_state.query;
8122 if !select_prev_state.done {
8123 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8124 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8125 let mut next_selected_range = None;
8126 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8127 let bytes_before_last_selection =
8128 buffer.reversed_bytes_in_range(0..last_selection.start);
8129 let bytes_after_first_selection =
8130 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8131 let query_matches = query
8132 .stream_find_iter(bytes_before_last_selection)
8133 .map(|result| (last_selection.start, result))
8134 .chain(
8135 query
8136 .stream_find_iter(bytes_after_first_selection)
8137 .map(|result| (buffer.len(), result)),
8138 );
8139 for (end_offset, query_match) in query_matches {
8140 let query_match = query_match.unwrap(); // can only fail due to I/O
8141 let offset_range =
8142 end_offset - query_match.end()..end_offset - query_match.start();
8143 let display_range = offset_range.start.to_display_point(&display_map)
8144 ..offset_range.end.to_display_point(&display_map);
8145
8146 if !select_prev_state.wordwise
8147 || (!movement::is_inside_word(&display_map, display_range.start)
8148 && !movement::is_inside_word(&display_map, display_range.end))
8149 {
8150 next_selected_range = Some(offset_range);
8151 break;
8152 }
8153 }
8154
8155 if let Some(next_selected_range) = next_selected_range {
8156 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8157 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8158 if action.replace_newest {
8159 s.delete(s.newest_anchor().id);
8160 }
8161 s.insert_range(next_selected_range);
8162 });
8163 } else {
8164 select_prev_state.done = true;
8165 }
8166 }
8167
8168 self.select_prev_state = Some(select_prev_state);
8169 } else {
8170 let mut only_carets = true;
8171 let mut same_text_selected = true;
8172 let mut selected_text = None;
8173
8174 let mut selections_iter = selections.iter().peekable();
8175 while let Some(selection) = selections_iter.next() {
8176 if selection.start != selection.end {
8177 only_carets = false;
8178 }
8179
8180 if same_text_selected {
8181 if selected_text.is_none() {
8182 selected_text =
8183 Some(buffer.text_for_range(selection.range()).collect::<String>());
8184 }
8185
8186 if let Some(next_selection) = selections_iter.peek() {
8187 if next_selection.range().len() == selection.range().len() {
8188 let next_selected_text = buffer
8189 .text_for_range(next_selection.range())
8190 .collect::<String>();
8191 if Some(next_selected_text) != selected_text {
8192 same_text_selected = false;
8193 selected_text = None;
8194 }
8195 } else {
8196 same_text_selected = false;
8197 selected_text = None;
8198 }
8199 }
8200 }
8201 }
8202
8203 if only_carets {
8204 for selection in &mut selections {
8205 let word_range = movement::surrounding_word(
8206 &display_map,
8207 selection.start.to_display_point(&display_map),
8208 );
8209 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8210 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8211 selection.goal = SelectionGoal::None;
8212 selection.reversed = false;
8213 }
8214 if selections.len() == 1 {
8215 let selection = selections
8216 .last()
8217 .expect("ensured that there's only one selection");
8218 let query = buffer
8219 .text_for_range(selection.start..selection.end)
8220 .collect::<String>();
8221 let is_empty = query.is_empty();
8222 let select_state = SelectNextState {
8223 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8224 wordwise: true,
8225 done: is_empty,
8226 };
8227 self.select_prev_state = Some(select_state);
8228 } else {
8229 self.select_prev_state = None;
8230 }
8231
8232 self.unfold_ranges(
8233 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8234 false,
8235 true,
8236 cx,
8237 );
8238 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8239 s.select(selections);
8240 });
8241 } else if let Some(selected_text) = selected_text {
8242 self.select_prev_state = Some(SelectNextState {
8243 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8244 wordwise: false,
8245 done: false,
8246 });
8247 self.select_previous(action, cx)?;
8248 }
8249 }
8250 Ok(())
8251 }
8252
8253 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8254 let text_layout_details = &self.text_layout_details(cx);
8255 self.transact(cx, |this, cx| {
8256 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8257 let mut edits = Vec::new();
8258 let mut selection_edit_ranges = Vec::new();
8259 let mut last_toggled_row = None;
8260 let snapshot = this.buffer.read(cx).read(cx);
8261 let empty_str: Arc<str> = Arc::default();
8262 let mut suffixes_inserted = Vec::new();
8263
8264 fn comment_prefix_range(
8265 snapshot: &MultiBufferSnapshot,
8266 row: MultiBufferRow,
8267 comment_prefix: &str,
8268 comment_prefix_whitespace: &str,
8269 ) -> Range<Point> {
8270 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8271
8272 let mut line_bytes = snapshot
8273 .bytes_in_range(start..snapshot.max_point())
8274 .flatten()
8275 .copied();
8276
8277 // If this line currently begins with the line comment prefix, then record
8278 // the range containing the prefix.
8279 if line_bytes
8280 .by_ref()
8281 .take(comment_prefix.len())
8282 .eq(comment_prefix.bytes())
8283 {
8284 // Include any whitespace that matches the comment prefix.
8285 let matching_whitespace_len = line_bytes
8286 .zip(comment_prefix_whitespace.bytes())
8287 .take_while(|(a, b)| a == b)
8288 .count() as u32;
8289 let end = Point::new(
8290 start.row,
8291 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8292 );
8293 start..end
8294 } else {
8295 start..start
8296 }
8297 }
8298
8299 fn comment_suffix_range(
8300 snapshot: &MultiBufferSnapshot,
8301 row: MultiBufferRow,
8302 comment_suffix: &str,
8303 comment_suffix_has_leading_space: bool,
8304 ) -> Range<Point> {
8305 let end = Point::new(row.0, snapshot.line_len(row));
8306 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8307
8308 let mut line_end_bytes = snapshot
8309 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8310 .flatten()
8311 .copied();
8312
8313 let leading_space_len = if suffix_start_column > 0
8314 && line_end_bytes.next() == Some(b' ')
8315 && comment_suffix_has_leading_space
8316 {
8317 1
8318 } else {
8319 0
8320 };
8321
8322 // If this line currently begins with the line comment prefix, then record
8323 // the range containing the prefix.
8324 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8325 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8326 start..end
8327 } else {
8328 end..end
8329 }
8330 }
8331
8332 // TODO: Handle selections that cross excerpts
8333 for selection in &mut selections {
8334 let start_column = snapshot
8335 .indent_size_for_line(MultiBufferRow(selection.start.row))
8336 .len;
8337 let language = if let Some(language) =
8338 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8339 {
8340 language
8341 } else {
8342 continue;
8343 };
8344
8345 selection_edit_ranges.clear();
8346
8347 // If multiple selections contain a given row, avoid processing that
8348 // row more than once.
8349 let mut start_row = MultiBufferRow(selection.start.row);
8350 if last_toggled_row == Some(start_row) {
8351 start_row = start_row.next_row();
8352 }
8353 let end_row =
8354 if selection.end.row > selection.start.row && selection.end.column == 0 {
8355 MultiBufferRow(selection.end.row - 1)
8356 } else {
8357 MultiBufferRow(selection.end.row)
8358 };
8359 last_toggled_row = Some(end_row);
8360
8361 if start_row > end_row {
8362 continue;
8363 }
8364
8365 // If the language has line comments, toggle those.
8366 let full_comment_prefixes = language.line_comment_prefixes();
8367 if !full_comment_prefixes.is_empty() {
8368 let first_prefix = full_comment_prefixes
8369 .first()
8370 .expect("prefixes is non-empty");
8371 let prefix_trimmed_lengths = full_comment_prefixes
8372 .iter()
8373 .map(|p| p.trim_end_matches(' ').len())
8374 .collect::<SmallVec<[usize; 4]>>();
8375
8376 let mut all_selection_lines_are_comments = true;
8377
8378 for row in start_row.0..=end_row.0 {
8379 let row = MultiBufferRow(row);
8380 if start_row < end_row && snapshot.is_line_blank(row) {
8381 continue;
8382 }
8383
8384 let prefix_range = full_comment_prefixes
8385 .iter()
8386 .zip(prefix_trimmed_lengths.iter().copied())
8387 .map(|(prefix, trimmed_prefix_len)| {
8388 comment_prefix_range(
8389 snapshot.deref(),
8390 row,
8391 &prefix[..trimmed_prefix_len],
8392 &prefix[trimmed_prefix_len..],
8393 )
8394 })
8395 .max_by_key(|range| range.end.column - range.start.column)
8396 .expect("prefixes is non-empty");
8397
8398 if prefix_range.is_empty() {
8399 all_selection_lines_are_comments = false;
8400 }
8401
8402 selection_edit_ranges.push(prefix_range);
8403 }
8404
8405 if all_selection_lines_are_comments {
8406 edits.extend(
8407 selection_edit_ranges
8408 .iter()
8409 .cloned()
8410 .map(|range| (range, empty_str.clone())),
8411 );
8412 } else {
8413 let min_column = selection_edit_ranges
8414 .iter()
8415 .map(|range| range.start.column)
8416 .min()
8417 .unwrap_or(0);
8418 edits.extend(selection_edit_ranges.iter().map(|range| {
8419 let position = Point::new(range.start.row, min_column);
8420 (position..position, first_prefix.clone())
8421 }));
8422 }
8423 } else if let Some((full_comment_prefix, comment_suffix)) =
8424 language.block_comment_delimiters()
8425 {
8426 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8427 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8428 let prefix_range = comment_prefix_range(
8429 snapshot.deref(),
8430 start_row,
8431 comment_prefix,
8432 comment_prefix_whitespace,
8433 );
8434 let suffix_range = comment_suffix_range(
8435 snapshot.deref(),
8436 end_row,
8437 comment_suffix.trim_start_matches(' '),
8438 comment_suffix.starts_with(' '),
8439 );
8440
8441 if prefix_range.is_empty() || suffix_range.is_empty() {
8442 edits.push((
8443 prefix_range.start..prefix_range.start,
8444 full_comment_prefix.clone(),
8445 ));
8446 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8447 suffixes_inserted.push((end_row, comment_suffix.len()));
8448 } else {
8449 edits.push((prefix_range, empty_str.clone()));
8450 edits.push((suffix_range, empty_str.clone()));
8451 }
8452 } else {
8453 continue;
8454 }
8455 }
8456
8457 drop(snapshot);
8458 this.buffer.update(cx, |buffer, cx| {
8459 buffer.edit(edits, None, cx);
8460 });
8461
8462 // Adjust selections so that they end before any comment suffixes that
8463 // were inserted.
8464 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8465 let mut selections = this.selections.all::<Point>(cx);
8466 let snapshot = this.buffer.read(cx).read(cx);
8467 for selection in &mut selections {
8468 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8469 match row.cmp(&MultiBufferRow(selection.end.row)) {
8470 Ordering::Less => {
8471 suffixes_inserted.next();
8472 continue;
8473 }
8474 Ordering::Greater => break,
8475 Ordering::Equal => {
8476 if selection.end.column == snapshot.line_len(row) {
8477 if selection.is_empty() {
8478 selection.start.column -= suffix_len as u32;
8479 }
8480 selection.end.column -= suffix_len as u32;
8481 }
8482 break;
8483 }
8484 }
8485 }
8486 }
8487
8488 drop(snapshot);
8489 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8490
8491 let selections = this.selections.all::<Point>(cx);
8492 let selections_on_single_row = selections.windows(2).all(|selections| {
8493 selections[0].start.row == selections[1].start.row
8494 && selections[0].end.row == selections[1].end.row
8495 && selections[0].start.row == selections[0].end.row
8496 });
8497 let selections_selecting = selections
8498 .iter()
8499 .any(|selection| selection.start != selection.end);
8500 let advance_downwards = action.advance_downwards
8501 && selections_on_single_row
8502 && !selections_selecting
8503 && !matches!(this.mode, EditorMode::SingleLine { .. });
8504
8505 if advance_downwards {
8506 let snapshot = this.buffer.read(cx).snapshot(cx);
8507
8508 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8509 s.move_cursors_with(|display_snapshot, display_point, _| {
8510 let mut point = display_point.to_point(display_snapshot);
8511 point.row += 1;
8512 point = snapshot.clip_point(point, Bias::Left);
8513 let display_point = point.to_display_point(display_snapshot);
8514 let goal = SelectionGoal::HorizontalPosition(
8515 display_snapshot
8516 .x_for_display_point(display_point, &text_layout_details)
8517 .into(),
8518 );
8519 (display_point, goal)
8520 })
8521 });
8522 }
8523 });
8524 }
8525
8526 pub fn select_enclosing_symbol(
8527 &mut self,
8528 _: &SelectEnclosingSymbol,
8529 cx: &mut ViewContext<Self>,
8530 ) {
8531 let buffer = self.buffer.read(cx).snapshot(cx);
8532 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8533
8534 fn update_selection(
8535 selection: &Selection<usize>,
8536 buffer_snap: &MultiBufferSnapshot,
8537 ) -> Option<Selection<usize>> {
8538 let cursor = selection.head();
8539 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8540 for symbol in symbols.iter().rev() {
8541 let start = symbol.range.start.to_offset(&buffer_snap);
8542 let end = symbol.range.end.to_offset(&buffer_snap);
8543 let new_range = start..end;
8544 if start < selection.start || end > selection.end {
8545 return Some(Selection {
8546 id: selection.id,
8547 start: new_range.start,
8548 end: new_range.end,
8549 goal: SelectionGoal::None,
8550 reversed: selection.reversed,
8551 });
8552 }
8553 }
8554 None
8555 }
8556
8557 let mut selected_larger_symbol = false;
8558 let new_selections = old_selections
8559 .iter()
8560 .map(|selection| match update_selection(selection, &buffer) {
8561 Some(new_selection) => {
8562 if new_selection.range() != selection.range() {
8563 selected_larger_symbol = true;
8564 }
8565 new_selection
8566 }
8567 None => selection.clone(),
8568 })
8569 .collect::<Vec<_>>();
8570
8571 if selected_larger_symbol {
8572 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8573 s.select(new_selections);
8574 });
8575 }
8576 }
8577
8578 pub fn select_larger_syntax_node(
8579 &mut self,
8580 _: &SelectLargerSyntaxNode,
8581 cx: &mut ViewContext<Self>,
8582 ) {
8583 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8584 let buffer = self.buffer.read(cx).snapshot(cx);
8585 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8586
8587 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8588 let mut selected_larger_node = false;
8589 let new_selections = old_selections
8590 .iter()
8591 .map(|selection| {
8592 let old_range = selection.start..selection.end;
8593 let mut new_range = old_range.clone();
8594 while let Some(containing_range) =
8595 buffer.range_for_syntax_ancestor(new_range.clone())
8596 {
8597 new_range = containing_range;
8598 if !display_map.intersects_fold(new_range.start)
8599 && !display_map.intersects_fold(new_range.end)
8600 {
8601 break;
8602 }
8603 }
8604
8605 selected_larger_node |= new_range != old_range;
8606 Selection {
8607 id: selection.id,
8608 start: new_range.start,
8609 end: new_range.end,
8610 goal: SelectionGoal::None,
8611 reversed: selection.reversed,
8612 }
8613 })
8614 .collect::<Vec<_>>();
8615
8616 if selected_larger_node {
8617 stack.push(old_selections);
8618 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8619 s.select(new_selections);
8620 });
8621 }
8622 self.select_larger_syntax_node_stack = stack;
8623 }
8624
8625 pub fn select_smaller_syntax_node(
8626 &mut self,
8627 _: &SelectSmallerSyntaxNode,
8628 cx: &mut ViewContext<Self>,
8629 ) {
8630 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8631 if let Some(selections) = stack.pop() {
8632 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8633 s.select(selections.to_vec());
8634 });
8635 }
8636 self.select_larger_syntax_node_stack = stack;
8637 }
8638
8639 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8640 if !EditorSettings::get_global(cx).gutter.runnables {
8641 self.clear_tasks();
8642 return Task::ready(());
8643 }
8644 let project = self.project.clone();
8645 cx.spawn(|this, mut cx| async move {
8646 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8647 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8648 }) else {
8649 return;
8650 };
8651
8652 let Some(project) = project else {
8653 return;
8654 };
8655
8656 let hide_runnables = project
8657 .update(&mut cx, |project, cx| {
8658 // Do not display any test indicators in non-dev server remote projects.
8659 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8660 })
8661 .unwrap_or(true);
8662 if hide_runnables {
8663 return;
8664 }
8665 let new_rows =
8666 cx.background_executor()
8667 .spawn({
8668 let snapshot = display_snapshot.clone();
8669 async move {
8670 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8671 }
8672 })
8673 .await;
8674 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8675
8676 this.update(&mut cx, |this, _| {
8677 this.clear_tasks();
8678 for (key, value) in rows {
8679 this.insert_tasks(key, value);
8680 }
8681 })
8682 .ok();
8683 })
8684 }
8685 fn fetch_runnable_ranges(
8686 snapshot: &DisplaySnapshot,
8687 range: Range<Anchor>,
8688 ) -> Vec<language::RunnableRange> {
8689 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8690 }
8691
8692 fn runnable_rows(
8693 project: Model<Project>,
8694 snapshot: DisplaySnapshot,
8695 runnable_ranges: Vec<RunnableRange>,
8696 mut cx: AsyncWindowContext,
8697 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8698 runnable_ranges
8699 .into_iter()
8700 .filter_map(|mut runnable| {
8701 let tasks = cx
8702 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8703 .ok()?;
8704 if tasks.is_empty() {
8705 return None;
8706 }
8707
8708 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8709
8710 let row = snapshot
8711 .buffer_snapshot
8712 .buffer_line_for_row(MultiBufferRow(point.row))?
8713 .1
8714 .start
8715 .row;
8716
8717 let context_range =
8718 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8719 Some((
8720 (runnable.buffer_id, row),
8721 RunnableTasks {
8722 templates: tasks,
8723 offset: MultiBufferOffset(runnable.run_range.start),
8724 context_range,
8725 column: point.column,
8726 extra_variables: runnable.extra_captures,
8727 },
8728 ))
8729 })
8730 .collect()
8731 }
8732
8733 fn templates_with_tags(
8734 project: &Model<Project>,
8735 runnable: &mut Runnable,
8736 cx: &WindowContext<'_>,
8737 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8738 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8739 let (worktree_id, file) = project
8740 .buffer_for_id(runnable.buffer, cx)
8741 .and_then(|buffer| buffer.read(cx).file())
8742 .map(|file| (WorktreeId::from_usize(file.worktree_id()), file.clone()))
8743 .unzip();
8744
8745 (project.task_inventory().clone(), worktree_id, file)
8746 });
8747
8748 let inventory = inventory.read(cx);
8749 let tags = mem::take(&mut runnable.tags);
8750 let mut tags: Vec<_> = tags
8751 .into_iter()
8752 .flat_map(|tag| {
8753 let tag = tag.0.clone();
8754 inventory
8755 .list_tasks(
8756 file.clone(),
8757 Some(runnable.language.clone()),
8758 worktree_id,
8759 cx,
8760 )
8761 .into_iter()
8762 .filter(move |(_, template)| {
8763 template.tags.iter().any(|source_tag| source_tag == &tag)
8764 })
8765 })
8766 .sorted_by_key(|(kind, _)| kind.to_owned())
8767 .collect();
8768 if let Some((leading_tag_source, _)) = tags.first() {
8769 // Strongest source wins; if we have worktree tag binding, prefer that to
8770 // global and language bindings;
8771 // if we have a global binding, prefer that to language binding.
8772 let first_mismatch = tags
8773 .iter()
8774 .position(|(tag_source, _)| tag_source != leading_tag_source);
8775 if let Some(index) = first_mismatch {
8776 tags.truncate(index);
8777 }
8778 }
8779
8780 tags
8781 }
8782
8783 pub fn move_to_enclosing_bracket(
8784 &mut self,
8785 _: &MoveToEnclosingBracket,
8786 cx: &mut ViewContext<Self>,
8787 ) {
8788 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8789 s.move_offsets_with(|snapshot, selection| {
8790 let Some(enclosing_bracket_ranges) =
8791 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
8792 else {
8793 return;
8794 };
8795
8796 let mut best_length = usize::MAX;
8797 let mut best_inside = false;
8798 let mut best_in_bracket_range = false;
8799 let mut best_destination = None;
8800 for (open, close) in enclosing_bracket_ranges {
8801 let close = close.to_inclusive();
8802 let length = close.end() - open.start;
8803 let inside = selection.start >= open.end && selection.end <= *close.start();
8804 let in_bracket_range = open.to_inclusive().contains(&selection.head())
8805 || close.contains(&selection.head());
8806
8807 // If best is next to a bracket and current isn't, skip
8808 if !in_bracket_range && best_in_bracket_range {
8809 continue;
8810 }
8811
8812 // Prefer smaller lengths unless best is inside and current isn't
8813 if length > best_length && (best_inside || !inside) {
8814 continue;
8815 }
8816
8817 best_length = length;
8818 best_inside = inside;
8819 best_in_bracket_range = in_bracket_range;
8820 best_destination = Some(
8821 if close.contains(&selection.start) && close.contains(&selection.end) {
8822 if inside {
8823 open.end
8824 } else {
8825 open.start
8826 }
8827 } else {
8828 if inside {
8829 *close.start()
8830 } else {
8831 *close.end()
8832 }
8833 },
8834 );
8835 }
8836
8837 if let Some(destination) = best_destination {
8838 selection.collapse_to(destination, SelectionGoal::None);
8839 }
8840 })
8841 });
8842 }
8843
8844 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
8845 self.end_selection(cx);
8846 self.selection_history.mode = SelectionHistoryMode::Undoing;
8847 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
8848 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8849 self.select_next_state = entry.select_next_state;
8850 self.select_prev_state = entry.select_prev_state;
8851 self.add_selections_state = entry.add_selections_state;
8852 self.request_autoscroll(Autoscroll::newest(), cx);
8853 }
8854 self.selection_history.mode = SelectionHistoryMode::Normal;
8855 }
8856
8857 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
8858 self.end_selection(cx);
8859 self.selection_history.mode = SelectionHistoryMode::Redoing;
8860 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
8861 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8862 self.select_next_state = entry.select_next_state;
8863 self.select_prev_state = entry.select_prev_state;
8864 self.add_selections_state = entry.add_selections_state;
8865 self.request_autoscroll(Autoscroll::newest(), cx);
8866 }
8867 self.selection_history.mode = SelectionHistoryMode::Normal;
8868 }
8869
8870 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
8871 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
8872 }
8873
8874 pub fn expand_excerpts_down(
8875 &mut self,
8876 action: &ExpandExcerptsDown,
8877 cx: &mut ViewContext<Self>,
8878 ) {
8879 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
8880 }
8881
8882 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
8883 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
8884 }
8885
8886 pub fn expand_excerpts_for_direction(
8887 &mut self,
8888 lines: u32,
8889 direction: ExpandExcerptDirection,
8890 cx: &mut ViewContext<Self>,
8891 ) {
8892 let selections = self.selections.disjoint_anchors();
8893
8894 let lines = if lines == 0 {
8895 EditorSettings::get_global(cx).expand_excerpt_lines
8896 } else {
8897 lines
8898 };
8899
8900 self.buffer.update(cx, |buffer, cx| {
8901 buffer.expand_excerpts(
8902 selections
8903 .into_iter()
8904 .map(|selection| selection.head().excerpt_id)
8905 .dedup(),
8906 lines,
8907 direction,
8908 cx,
8909 )
8910 })
8911 }
8912
8913 pub fn expand_excerpt(
8914 &mut self,
8915 excerpt: ExcerptId,
8916 direction: ExpandExcerptDirection,
8917 cx: &mut ViewContext<Self>,
8918 ) {
8919 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
8920 self.buffer.update(cx, |buffer, cx| {
8921 buffer.expand_excerpts([excerpt], lines, direction, cx)
8922 })
8923 }
8924
8925 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
8926 self.go_to_diagnostic_impl(Direction::Next, cx)
8927 }
8928
8929 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
8930 self.go_to_diagnostic_impl(Direction::Prev, cx)
8931 }
8932
8933 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
8934 let buffer = self.buffer.read(cx).snapshot(cx);
8935 let selection = self.selections.newest::<usize>(cx);
8936
8937 // If there is an active Diagnostic Popover jump to its diagnostic instead.
8938 if direction == Direction::Next {
8939 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
8940 let (group_id, jump_to) = popover.activation_info();
8941 if self.activate_diagnostics(group_id, cx) {
8942 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8943 let mut new_selection = s.newest_anchor().clone();
8944 new_selection.collapse_to(jump_to, SelectionGoal::None);
8945 s.select_anchors(vec![new_selection.clone()]);
8946 });
8947 }
8948 return;
8949 }
8950 }
8951
8952 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
8953 active_diagnostics
8954 .primary_range
8955 .to_offset(&buffer)
8956 .to_inclusive()
8957 });
8958 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
8959 if active_primary_range.contains(&selection.head()) {
8960 *active_primary_range.start()
8961 } else {
8962 selection.head()
8963 }
8964 } else {
8965 selection.head()
8966 };
8967 let snapshot = self.snapshot(cx);
8968 loop {
8969 let diagnostics = if direction == Direction::Prev {
8970 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
8971 } else {
8972 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
8973 }
8974 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
8975 let group = diagnostics
8976 // relies on diagnostics_in_range to return diagnostics with the same starting range to
8977 // be sorted in a stable way
8978 // skip until we are at current active diagnostic, if it exists
8979 .skip_while(|entry| {
8980 (match direction {
8981 Direction::Prev => entry.range.start >= search_start,
8982 Direction::Next => entry.range.start <= search_start,
8983 }) && self
8984 .active_diagnostics
8985 .as_ref()
8986 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
8987 })
8988 .find_map(|entry| {
8989 if entry.diagnostic.is_primary
8990 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
8991 && !entry.range.is_empty()
8992 // if we match with the active diagnostic, skip it
8993 && Some(entry.diagnostic.group_id)
8994 != self.active_diagnostics.as_ref().map(|d| d.group_id)
8995 {
8996 Some((entry.range, entry.diagnostic.group_id))
8997 } else {
8998 None
8999 }
9000 });
9001
9002 if let Some((primary_range, group_id)) = group {
9003 if self.activate_diagnostics(group_id, cx) {
9004 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9005 s.select(vec![Selection {
9006 id: selection.id,
9007 start: primary_range.start,
9008 end: primary_range.start,
9009 reversed: false,
9010 goal: SelectionGoal::None,
9011 }]);
9012 });
9013 }
9014 break;
9015 } else {
9016 // Cycle around to the start of the buffer, potentially moving back to the start of
9017 // the currently active diagnostic.
9018 active_primary_range.take();
9019 if direction == Direction::Prev {
9020 if search_start == buffer.len() {
9021 break;
9022 } else {
9023 search_start = buffer.len();
9024 }
9025 } else if search_start == 0 {
9026 break;
9027 } else {
9028 search_start = 0;
9029 }
9030 }
9031 }
9032 }
9033
9034 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9035 let snapshot = self
9036 .display_map
9037 .update(cx, |display_map, cx| display_map.snapshot(cx));
9038 let selection = self.selections.newest::<Point>(cx);
9039
9040 if !self.seek_in_direction(
9041 &snapshot,
9042 selection.head(),
9043 false,
9044 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9045 MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
9046 ),
9047 cx,
9048 ) {
9049 let wrapped_point = Point::zero();
9050 self.seek_in_direction(
9051 &snapshot,
9052 wrapped_point,
9053 true,
9054 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9055 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9056 ),
9057 cx,
9058 );
9059 }
9060 }
9061
9062 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9063 let snapshot = self
9064 .display_map
9065 .update(cx, |display_map, cx| display_map.snapshot(cx));
9066 let selection = self.selections.newest::<Point>(cx);
9067
9068 if !self.seek_in_direction(
9069 &snapshot,
9070 selection.head(),
9071 false,
9072 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9073 MultiBufferRow(0)..MultiBufferRow(selection.head().row),
9074 ),
9075 cx,
9076 ) {
9077 let wrapped_point = snapshot.buffer_snapshot.max_point();
9078 self.seek_in_direction(
9079 &snapshot,
9080 wrapped_point,
9081 true,
9082 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9083 MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
9084 ),
9085 cx,
9086 );
9087 }
9088 }
9089
9090 fn seek_in_direction(
9091 &mut self,
9092 snapshot: &DisplaySnapshot,
9093 initial_point: Point,
9094 is_wrapped: bool,
9095 hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
9096 cx: &mut ViewContext<Editor>,
9097 ) -> bool {
9098 let display_point = initial_point.to_display_point(snapshot);
9099 let mut hunks = hunks
9100 .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
9101 .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
9102 .dedup();
9103
9104 if let Some(hunk) = hunks.next() {
9105 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9106 let row = hunk.start_display_row();
9107 let point = DisplayPoint::new(row, 0);
9108 s.select_display_ranges([point..point]);
9109 });
9110
9111 true
9112 } else {
9113 false
9114 }
9115 }
9116
9117 pub fn go_to_definition(
9118 &mut self,
9119 _: &GoToDefinition,
9120 cx: &mut ViewContext<Self>,
9121 ) -> Task<Result<Navigated>> {
9122 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9123 cx.spawn(|editor, mut cx| async move {
9124 if definition.await? == Navigated::Yes {
9125 return Ok(Navigated::Yes);
9126 }
9127 match editor.update(&mut cx, |editor, cx| {
9128 editor.find_all_references(&FindAllReferences, cx)
9129 })? {
9130 Some(references) => references.await,
9131 None => Ok(Navigated::No),
9132 }
9133 })
9134 }
9135
9136 pub fn go_to_declaration(
9137 &mut self,
9138 _: &GoToDeclaration,
9139 cx: &mut ViewContext<Self>,
9140 ) -> Task<Result<Navigated>> {
9141 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9142 }
9143
9144 pub fn go_to_declaration_split(
9145 &mut self,
9146 _: &GoToDeclaration,
9147 cx: &mut ViewContext<Self>,
9148 ) -> Task<Result<Navigated>> {
9149 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9150 }
9151
9152 pub fn go_to_implementation(
9153 &mut self,
9154 _: &GoToImplementation,
9155 cx: &mut ViewContext<Self>,
9156 ) -> Task<Result<Navigated>> {
9157 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9158 }
9159
9160 pub fn go_to_implementation_split(
9161 &mut self,
9162 _: &GoToImplementationSplit,
9163 cx: &mut ViewContext<Self>,
9164 ) -> Task<Result<Navigated>> {
9165 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9166 }
9167
9168 pub fn go_to_type_definition(
9169 &mut self,
9170 _: &GoToTypeDefinition,
9171 cx: &mut ViewContext<Self>,
9172 ) -> Task<Result<Navigated>> {
9173 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9174 }
9175
9176 pub fn go_to_definition_split(
9177 &mut self,
9178 _: &GoToDefinitionSplit,
9179 cx: &mut ViewContext<Self>,
9180 ) -> Task<Result<Navigated>> {
9181 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9182 }
9183
9184 pub fn go_to_type_definition_split(
9185 &mut self,
9186 _: &GoToTypeDefinitionSplit,
9187 cx: &mut ViewContext<Self>,
9188 ) -> Task<Result<Navigated>> {
9189 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9190 }
9191
9192 fn go_to_definition_of_kind(
9193 &mut self,
9194 kind: GotoDefinitionKind,
9195 split: bool,
9196 cx: &mut ViewContext<Self>,
9197 ) -> Task<Result<Navigated>> {
9198 let Some(workspace) = self.workspace() else {
9199 return Task::ready(Ok(Navigated::No));
9200 };
9201 let buffer = self.buffer.read(cx);
9202 let head = self.selections.newest::<usize>(cx).head();
9203 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9204 text_anchor
9205 } else {
9206 return Task::ready(Ok(Navigated::No));
9207 };
9208
9209 let project = workspace.read(cx).project().clone();
9210 let definitions = project.update(cx, |project, cx| match kind {
9211 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
9212 GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
9213 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
9214 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
9215 });
9216
9217 cx.spawn(|editor, mut cx| async move {
9218 let definitions = definitions.await?;
9219 let navigated = editor
9220 .update(&mut cx, |editor, cx| {
9221 editor.navigate_to_hover_links(
9222 Some(kind),
9223 definitions
9224 .into_iter()
9225 .filter(|location| {
9226 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9227 })
9228 .map(HoverLink::Text)
9229 .collect::<Vec<_>>(),
9230 split,
9231 cx,
9232 )
9233 })?
9234 .await?;
9235 anyhow::Ok(navigated)
9236 })
9237 }
9238
9239 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9240 let position = self.selections.newest_anchor().head();
9241 let Some((buffer, buffer_position)) =
9242 self.buffer.read(cx).text_anchor_for_position(position, cx)
9243 else {
9244 return;
9245 };
9246
9247 cx.spawn(|editor, mut cx| async move {
9248 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9249 editor.update(&mut cx, |_, cx| {
9250 cx.open_url(&url);
9251 })
9252 } else {
9253 Ok(())
9254 }
9255 })
9256 .detach();
9257 }
9258
9259 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9260 let Some(workspace) = self.workspace() else {
9261 return;
9262 };
9263
9264 let position = self.selections.newest_anchor().head();
9265
9266 let Some((buffer, buffer_position)) =
9267 self.buffer.read(cx).text_anchor_for_position(position, cx)
9268 else {
9269 return;
9270 };
9271
9272 let Some(project) = self.project.clone() else {
9273 return;
9274 };
9275
9276 cx.spawn(|_, mut cx| async move {
9277 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9278
9279 if let Some((_, path)) = result {
9280 workspace
9281 .update(&mut cx, |workspace, cx| {
9282 workspace.open_resolved_path(path, cx)
9283 })?
9284 .await?;
9285 }
9286 anyhow::Ok(())
9287 })
9288 .detach();
9289 }
9290
9291 pub(crate) fn navigate_to_hover_links(
9292 &mut self,
9293 kind: Option<GotoDefinitionKind>,
9294 mut definitions: Vec<HoverLink>,
9295 split: bool,
9296 cx: &mut ViewContext<Editor>,
9297 ) -> Task<Result<Navigated>> {
9298 // If there is one definition, just open it directly
9299 if definitions.len() == 1 {
9300 let definition = definitions.pop().unwrap();
9301
9302 enum TargetTaskResult {
9303 Location(Option<Location>),
9304 AlreadyNavigated,
9305 }
9306
9307 let target_task = match definition {
9308 HoverLink::Text(link) => {
9309 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9310 }
9311 HoverLink::InlayHint(lsp_location, server_id) => {
9312 let computation = self.compute_target_location(lsp_location, server_id, cx);
9313 cx.background_executor().spawn(async move {
9314 let location = computation.await?;
9315 Ok(TargetTaskResult::Location(location))
9316 })
9317 }
9318 HoverLink::Url(url) => {
9319 cx.open_url(&url);
9320 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9321 }
9322 HoverLink::File(path) => {
9323 if let Some(workspace) = self.workspace() {
9324 cx.spawn(|_, mut cx| async move {
9325 workspace
9326 .update(&mut cx, |workspace, cx| {
9327 workspace.open_resolved_path(path, cx)
9328 })?
9329 .await
9330 .map(|_| TargetTaskResult::AlreadyNavigated)
9331 })
9332 } else {
9333 Task::ready(Ok(TargetTaskResult::Location(None)))
9334 }
9335 }
9336 };
9337 cx.spawn(|editor, mut cx| async move {
9338 let target = match target_task.await.context("target resolution task")? {
9339 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9340 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9341 TargetTaskResult::Location(Some(target)) => target,
9342 };
9343
9344 editor.update(&mut cx, |editor, cx| {
9345 let Some(workspace) = editor.workspace() else {
9346 return Navigated::No;
9347 };
9348 let pane = workspace.read(cx).active_pane().clone();
9349
9350 let range = target.range.to_offset(target.buffer.read(cx));
9351 let range = editor.range_for_match(&range);
9352
9353 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9354 let buffer = target.buffer.read(cx);
9355 let range = check_multiline_range(buffer, range);
9356 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
9357 s.select_ranges([range]);
9358 });
9359 } else {
9360 cx.window_context().defer(move |cx| {
9361 let target_editor: View<Self> =
9362 workspace.update(cx, |workspace, cx| {
9363 let pane = if split {
9364 workspace.adjacent_pane(cx)
9365 } else {
9366 workspace.active_pane().clone()
9367 };
9368
9369 workspace.open_project_item(
9370 pane,
9371 target.buffer.clone(),
9372 true,
9373 true,
9374 cx,
9375 )
9376 });
9377 target_editor.update(cx, |target_editor, cx| {
9378 // When selecting a definition in a different buffer, disable the nav history
9379 // to avoid creating a history entry at the previous cursor location.
9380 pane.update(cx, |pane, _| pane.disable_history());
9381 let buffer = target.buffer.read(cx);
9382 let range = check_multiline_range(buffer, range);
9383 target_editor.change_selections(
9384 Some(Autoscroll::focused()),
9385 cx,
9386 |s| {
9387 s.select_ranges([range]);
9388 },
9389 );
9390 pane.update(cx, |pane, _| pane.enable_history());
9391 });
9392 });
9393 }
9394 Navigated::Yes
9395 })
9396 })
9397 } else if !definitions.is_empty() {
9398 let replica_id = self.replica_id(cx);
9399 cx.spawn(|editor, mut cx| async move {
9400 let (title, location_tasks, workspace) = editor
9401 .update(&mut cx, |editor, cx| {
9402 let tab_kind = match kind {
9403 Some(GotoDefinitionKind::Implementation) => "Implementations",
9404 _ => "Definitions",
9405 };
9406 let title = definitions
9407 .iter()
9408 .find_map(|definition| match definition {
9409 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9410 let buffer = origin.buffer.read(cx);
9411 format!(
9412 "{} for {}",
9413 tab_kind,
9414 buffer
9415 .text_for_range(origin.range.clone())
9416 .collect::<String>()
9417 )
9418 }),
9419 HoverLink::InlayHint(_, _) => None,
9420 HoverLink::Url(_) => None,
9421 HoverLink::File(_) => None,
9422 })
9423 .unwrap_or(tab_kind.to_string());
9424 let location_tasks = definitions
9425 .into_iter()
9426 .map(|definition| match definition {
9427 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9428 HoverLink::InlayHint(lsp_location, server_id) => {
9429 editor.compute_target_location(lsp_location, server_id, cx)
9430 }
9431 HoverLink::Url(_) => Task::ready(Ok(None)),
9432 HoverLink::File(_) => Task::ready(Ok(None)),
9433 })
9434 .collect::<Vec<_>>();
9435 (title, location_tasks, editor.workspace().clone())
9436 })
9437 .context("location tasks preparation")?;
9438
9439 let locations = futures::future::join_all(location_tasks)
9440 .await
9441 .into_iter()
9442 .filter_map(|location| location.transpose())
9443 .collect::<Result<_>>()
9444 .context("location tasks")?;
9445
9446 let Some(workspace) = workspace else {
9447 return Ok(Navigated::No);
9448 };
9449 let opened = workspace
9450 .update(&mut cx, |workspace, cx| {
9451 Self::open_locations_in_multibuffer(
9452 workspace, locations, replica_id, title, split, cx,
9453 )
9454 })
9455 .ok();
9456
9457 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9458 })
9459 } else {
9460 Task::ready(Ok(Navigated::No))
9461 }
9462 }
9463
9464 fn compute_target_location(
9465 &self,
9466 lsp_location: lsp::Location,
9467 server_id: LanguageServerId,
9468 cx: &mut ViewContext<Editor>,
9469 ) -> Task<anyhow::Result<Option<Location>>> {
9470 let Some(project) = self.project.clone() else {
9471 return Task::Ready(Some(Ok(None)));
9472 };
9473
9474 cx.spawn(move |editor, mut cx| async move {
9475 let location_task = editor.update(&mut cx, |editor, cx| {
9476 project.update(cx, |project, cx| {
9477 let language_server_name =
9478 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9479 project
9480 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9481 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9482 });
9483 language_server_name.map(|language_server_name| {
9484 project.open_local_buffer_via_lsp(
9485 lsp_location.uri.clone(),
9486 server_id,
9487 language_server_name,
9488 cx,
9489 )
9490 })
9491 })
9492 })?;
9493 let location = match location_task {
9494 Some(task) => Some({
9495 let target_buffer_handle = task.await.context("open local buffer")?;
9496 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9497 let target_start = target_buffer
9498 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9499 let target_end = target_buffer
9500 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9501 target_buffer.anchor_after(target_start)
9502 ..target_buffer.anchor_before(target_end)
9503 })?;
9504 Location {
9505 buffer: target_buffer_handle,
9506 range,
9507 }
9508 }),
9509 None => None,
9510 };
9511 Ok(location)
9512 })
9513 }
9514
9515 pub fn find_all_references(
9516 &mut self,
9517 _: &FindAllReferences,
9518 cx: &mut ViewContext<Self>,
9519 ) -> Option<Task<Result<Navigated>>> {
9520 let multi_buffer = self.buffer.read(cx);
9521 let selection = self.selections.newest::<usize>(cx);
9522 let head = selection.head();
9523
9524 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9525 let head_anchor = multi_buffer_snapshot.anchor_at(
9526 head,
9527 if head < selection.tail() {
9528 Bias::Right
9529 } else {
9530 Bias::Left
9531 },
9532 );
9533
9534 match self
9535 .find_all_references_task_sources
9536 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9537 {
9538 Ok(_) => {
9539 log::info!(
9540 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9541 );
9542 return None;
9543 }
9544 Err(i) => {
9545 self.find_all_references_task_sources.insert(i, head_anchor);
9546 }
9547 }
9548
9549 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9550 let replica_id = self.replica_id(cx);
9551 let workspace = self.workspace()?;
9552 let project = workspace.read(cx).project().clone();
9553 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9554 Some(cx.spawn(|editor, mut cx| async move {
9555 let _cleanup = defer({
9556 let mut cx = cx.clone();
9557 move || {
9558 let _ = editor.update(&mut cx, |editor, _| {
9559 if let Ok(i) =
9560 editor
9561 .find_all_references_task_sources
9562 .binary_search_by(|anchor| {
9563 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9564 })
9565 {
9566 editor.find_all_references_task_sources.remove(i);
9567 }
9568 });
9569 }
9570 });
9571
9572 let locations = references.await?;
9573 if locations.is_empty() {
9574 return anyhow::Ok(Navigated::No);
9575 }
9576
9577 workspace.update(&mut cx, |workspace, cx| {
9578 let title = locations
9579 .first()
9580 .as_ref()
9581 .map(|location| {
9582 let buffer = location.buffer.read(cx);
9583 format!(
9584 "References to `{}`",
9585 buffer
9586 .text_for_range(location.range.clone())
9587 .collect::<String>()
9588 )
9589 })
9590 .unwrap();
9591 Self::open_locations_in_multibuffer(
9592 workspace, locations, replica_id, title, false, cx,
9593 );
9594 Navigated::Yes
9595 })
9596 }))
9597 }
9598
9599 /// Opens a multibuffer with the given project locations in it
9600 pub fn open_locations_in_multibuffer(
9601 workspace: &mut Workspace,
9602 mut locations: Vec<Location>,
9603 replica_id: ReplicaId,
9604 title: String,
9605 split: bool,
9606 cx: &mut ViewContext<Workspace>,
9607 ) {
9608 // If there are multiple definitions, open them in a multibuffer
9609 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9610 let mut locations = locations.into_iter().peekable();
9611 let mut ranges_to_highlight = Vec::new();
9612 let capability = workspace.project().read(cx).capability();
9613
9614 let excerpt_buffer = cx.new_model(|cx| {
9615 let mut multibuffer = MultiBuffer::new(replica_id, capability);
9616 while let Some(location) = locations.next() {
9617 let buffer = location.buffer.read(cx);
9618 let mut ranges_for_buffer = Vec::new();
9619 let range = location.range.to_offset(buffer);
9620 ranges_for_buffer.push(range.clone());
9621
9622 while let Some(next_location) = locations.peek() {
9623 if next_location.buffer == location.buffer {
9624 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9625 locations.next();
9626 } else {
9627 break;
9628 }
9629 }
9630
9631 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9632 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9633 location.buffer.clone(),
9634 ranges_for_buffer,
9635 DEFAULT_MULTIBUFFER_CONTEXT,
9636 cx,
9637 ))
9638 }
9639
9640 multibuffer.with_title(title)
9641 });
9642
9643 let editor = cx.new_view(|cx| {
9644 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9645 });
9646 editor.update(cx, |editor, cx| {
9647 if let Some(first_range) = ranges_to_highlight.first() {
9648 editor.change_selections(None, cx, |selections| {
9649 selections.clear_disjoint();
9650 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9651 });
9652 }
9653 editor.highlight_background::<Self>(
9654 &ranges_to_highlight,
9655 |theme| theme.editor_highlighted_line_background,
9656 cx,
9657 );
9658 });
9659
9660 let item = Box::new(editor);
9661 let item_id = item.item_id();
9662
9663 if split {
9664 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9665 } else {
9666 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9667 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9668 pane.close_current_preview_item(cx)
9669 } else {
9670 None
9671 }
9672 });
9673 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9674 }
9675 workspace.active_pane().update(cx, |pane, cx| {
9676 pane.set_preview_item_id(Some(item_id), cx);
9677 });
9678 }
9679
9680 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9681 use language::ToOffset as _;
9682
9683 let project = self.project.clone()?;
9684 let selection = self.selections.newest_anchor().clone();
9685 let (cursor_buffer, cursor_buffer_position) = self
9686 .buffer
9687 .read(cx)
9688 .text_anchor_for_position(selection.head(), cx)?;
9689 let (tail_buffer, cursor_buffer_position_end) = self
9690 .buffer
9691 .read(cx)
9692 .text_anchor_for_position(selection.tail(), cx)?;
9693 if tail_buffer != cursor_buffer {
9694 return None;
9695 }
9696
9697 let snapshot = cursor_buffer.read(cx).snapshot();
9698 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9699 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9700 let prepare_rename = project.update(cx, |project, cx| {
9701 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
9702 });
9703 drop(snapshot);
9704
9705 Some(cx.spawn(|this, mut cx| async move {
9706 let rename_range = if let Some(range) = prepare_rename.await? {
9707 Some(range)
9708 } else {
9709 this.update(&mut cx, |this, cx| {
9710 let buffer = this.buffer.read(cx).snapshot(cx);
9711 let mut buffer_highlights = this
9712 .document_highlights_for_position(selection.head(), &buffer)
9713 .filter(|highlight| {
9714 highlight.start.excerpt_id == selection.head().excerpt_id
9715 && highlight.end.excerpt_id == selection.head().excerpt_id
9716 });
9717 buffer_highlights
9718 .next()
9719 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9720 })?
9721 };
9722 if let Some(rename_range) = rename_range {
9723 this.update(&mut cx, |this, cx| {
9724 let snapshot = cursor_buffer.read(cx).snapshot();
9725 let rename_buffer_range = rename_range.to_offset(&snapshot);
9726 let cursor_offset_in_rename_range =
9727 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9728 let cursor_offset_in_rename_range_end =
9729 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9730
9731 this.take_rename(false, cx);
9732 let buffer = this.buffer.read(cx).read(cx);
9733 let cursor_offset = selection.head().to_offset(&buffer);
9734 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9735 let rename_end = rename_start + rename_buffer_range.len();
9736 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9737 let mut old_highlight_id = None;
9738 let old_name: Arc<str> = buffer
9739 .chunks(rename_start..rename_end, true)
9740 .map(|chunk| {
9741 if old_highlight_id.is_none() {
9742 old_highlight_id = chunk.syntax_highlight_id;
9743 }
9744 chunk.text
9745 })
9746 .collect::<String>()
9747 .into();
9748
9749 drop(buffer);
9750
9751 // Position the selection in the rename editor so that it matches the current selection.
9752 this.show_local_selections = false;
9753 let rename_editor = cx.new_view(|cx| {
9754 let mut editor = Editor::single_line(cx);
9755 editor.buffer.update(cx, |buffer, cx| {
9756 buffer.edit([(0..0, old_name.clone())], None, cx)
9757 });
9758 let rename_selection_range = match cursor_offset_in_rename_range
9759 .cmp(&cursor_offset_in_rename_range_end)
9760 {
9761 Ordering::Equal => {
9762 editor.select_all(&SelectAll, cx);
9763 return editor;
9764 }
9765 Ordering::Less => {
9766 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9767 }
9768 Ordering::Greater => {
9769 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9770 }
9771 };
9772 if rename_selection_range.end > old_name.len() {
9773 editor.select_all(&SelectAll, cx);
9774 } else {
9775 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9776 s.select_ranges([rename_selection_range]);
9777 });
9778 }
9779 editor
9780 });
9781 cx.subscribe(&rename_editor, |_, _, e, cx| match e {
9782 EditorEvent::Focused => cx.emit(EditorEvent::FocusedIn),
9783 _ => {}
9784 })
9785 .detach();
9786
9787 let write_highlights =
9788 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
9789 let read_highlights =
9790 this.clear_background_highlights::<DocumentHighlightRead>(cx);
9791 let ranges = write_highlights
9792 .iter()
9793 .flat_map(|(_, ranges)| ranges.iter())
9794 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
9795 .cloned()
9796 .collect();
9797
9798 this.highlight_text::<Rename>(
9799 ranges,
9800 HighlightStyle {
9801 fade_out: Some(0.6),
9802 ..Default::default()
9803 },
9804 cx,
9805 );
9806 let rename_focus_handle = rename_editor.focus_handle(cx);
9807 cx.focus(&rename_focus_handle);
9808 let block_id = this.insert_blocks(
9809 [BlockProperties {
9810 style: BlockStyle::Flex,
9811 position: range.start,
9812 height: 1,
9813 render: Box::new({
9814 let rename_editor = rename_editor.clone();
9815 move |cx: &mut BlockContext| {
9816 let mut text_style = cx.editor_style.text.clone();
9817 if let Some(highlight_style) = old_highlight_id
9818 .and_then(|h| h.style(&cx.editor_style.syntax))
9819 {
9820 text_style = text_style.highlight(highlight_style);
9821 }
9822 div()
9823 .pl(cx.anchor_x)
9824 .child(EditorElement::new(
9825 &rename_editor,
9826 EditorStyle {
9827 background: cx.theme().system().transparent,
9828 local_player: cx.editor_style.local_player,
9829 text: text_style,
9830 scrollbar_width: cx.editor_style.scrollbar_width,
9831 syntax: cx.editor_style.syntax.clone(),
9832 status: cx.editor_style.status.clone(),
9833 inlay_hints_style: HighlightStyle {
9834 color: Some(cx.theme().status().hint),
9835 font_weight: Some(FontWeight::BOLD),
9836 ..HighlightStyle::default()
9837 },
9838 suggestions_style: HighlightStyle {
9839 color: Some(cx.theme().status().predictive),
9840 ..HighlightStyle::default()
9841 },
9842 ..EditorStyle::default()
9843 },
9844 ))
9845 .into_any_element()
9846 }
9847 }),
9848 disposition: BlockDisposition::Below,
9849 priority: 0,
9850 }],
9851 Some(Autoscroll::fit()),
9852 cx,
9853 )[0];
9854 this.pending_rename = Some(RenameState {
9855 range,
9856 old_name,
9857 editor: rename_editor,
9858 block_id,
9859 });
9860 })?;
9861 }
9862
9863 Ok(())
9864 }))
9865 }
9866
9867 pub fn confirm_rename(
9868 &mut self,
9869 _: &ConfirmRename,
9870 cx: &mut ViewContext<Self>,
9871 ) -> Option<Task<Result<()>>> {
9872 let rename = self.take_rename(false, cx)?;
9873 let workspace = self.workspace()?;
9874 let (start_buffer, start) = self
9875 .buffer
9876 .read(cx)
9877 .text_anchor_for_position(rename.range.start, cx)?;
9878 let (end_buffer, end) = self
9879 .buffer
9880 .read(cx)
9881 .text_anchor_for_position(rename.range.end, cx)?;
9882 if start_buffer != end_buffer {
9883 return None;
9884 }
9885
9886 let buffer = start_buffer;
9887 let range = start..end;
9888 let old_name = rename.old_name;
9889 let new_name = rename.editor.read(cx).text(cx);
9890
9891 let rename = workspace
9892 .read(cx)
9893 .project()
9894 .clone()
9895 .update(cx, |project, cx| {
9896 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
9897 });
9898 let workspace = workspace.downgrade();
9899
9900 Some(cx.spawn(|editor, mut cx| async move {
9901 let project_transaction = rename.await?;
9902 Self::open_project_transaction(
9903 &editor,
9904 workspace,
9905 project_transaction,
9906 format!("Rename: {} → {}", old_name, new_name),
9907 cx.clone(),
9908 )
9909 .await?;
9910
9911 editor.update(&mut cx, |editor, cx| {
9912 editor.refresh_document_highlights(cx);
9913 })?;
9914 Ok(())
9915 }))
9916 }
9917
9918 fn take_rename(
9919 &mut self,
9920 moving_cursor: bool,
9921 cx: &mut ViewContext<Self>,
9922 ) -> Option<RenameState> {
9923 let rename = self.pending_rename.take()?;
9924 if rename.editor.focus_handle(cx).is_focused(cx) {
9925 cx.focus(&self.focus_handle);
9926 }
9927
9928 self.remove_blocks(
9929 [rename.block_id].into_iter().collect(),
9930 Some(Autoscroll::fit()),
9931 cx,
9932 );
9933 self.clear_highlights::<Rename>(cx);
9934 self.show_local_selections = true;
9935
9936 if moving_cursor {
9937 let rename_editor = rename.editor.read(cx);
9938 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
9939
9940 // Update the selection to match the position of the selection inside
9941 // the rename editor.
9942 let snapshot = self.buffer.read(cx).read(cx);
9943 let rename_range = rename.range.to_offset(&snapshot);
9944 let cursor_in_editor = snapshot
9945 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
9946 .min(rename_range.end);
9947 drop(snapshot);
9948
9949 self.change_selections(None, cx, |s| {
9950 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
9951 });
9952 } else {
9953 self.refresh_document_highlights(cx);
9954 }
9955
9956 Some(rename)
9957 }
9958
9959 pub fn pending_rename(&self) -> Option<&RenameState> {
9960 self.pending_rename.as_ref()
9961 }
9962
9963 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9964 let project = match &self.project {
9965 Some(project) => project.clone(),
9966 None => return None,
9967 };
9968
9969 Some(self.perform_format(project, FormatTrigger::Manual, cx))
9970 }
9971
9972 fn perform_format(
9973 &mut self,
9974 project: Model<Project>,
9975 trigger: FormatTrigger,
9976 cx: &mut ViewContext<Self>,
9977 ) -> Task<Result<()>> {
9978 let buffer = self.buffer().clone();
9979 let mut buffers = buffer.read(cx).all_buffers();
9980 if trigger == FormatTrigger::Save {
9981 buffers.retain(|buffer| buffer.read(cx).is_dirty());
9982 }
9983
9984 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
9985 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
9986
9987 cx.spawn(|_, mut cx| async move {
9988 let transaction = futures::select_biased! {
9989 () = timeout => {
9990 log::warn!("timed out waiting for formatting");
9991 None
9992 }
9993 transaction = format.log_err().fuse() => transaction,
9994 };
9995
9996 buffer
9997 .update(&mut cx, |buffer, cx| {
9998 if let Some(transaction) = transaction {
9999 if !buffer.is_singleton() {
10000 buffer.push_transaction(&transaction.0, cx);
10001 }
10002 }
10003
10004 cx.notify();
10005 })
10006 .ok();
10007
10008 Ok(())
10009 })
10010 }
10011
10012 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10013 if let Some(project) = self.project.clone() {
10014 self.buffer.update(cx, |multi_buffer, cx| {
10015 project.update(cx, |project, cx| {
10016 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10017 });
10018 })
10019 }
10020 }
10021
10022 fn cancel_language_server_work(
10023 &mut self,
10024 _: &CancelLanguageServerWork,
10025 cx: &mut ViewContext<Self>,
10026 ) {
10027 if let Some(project) = self.project.clone() {
10028 self.buffer.update(cx, |multi_buffer, cx| {
10029 project.update(cx, |project, cx| {
10030 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10031 });
10032 })
10033 }
10034 }
10035
10036 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10037 cx.show_character_palette();
10038 }
10039
10040 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10041 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10042 let buffer = self.buffer.read(cx).snapshot(cx);
10043 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10044 let is_valid = buffer
10045 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10046 .any(|entry| {
10047 entry.diagnostic.is_primary
10048 && !entry.range.is_empty()
10049 && entry.range.start == primary_range_start
10050 && entry.diagnostic.message == active_diagnostics.primary_message
10051 });
10052
10053 if is_valid != active_diagnostics.is_valid {
10054 active_diagnostics.is_valid = is_valid;
10055 let mut new_styles = HashMap::default();
10056 for (block_id, diagnostic) in &active_diagnostics.blocks {
10057 new_styles.insert(
10058 *block_id,
10059 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10060 );
10061 }
10062 self.display_map.update(cx, |display_map, _cx| {
10063 display_map.replace_blocks(new_styles)
10064 });
10065 }
10066 }
10067 }
10068
10069 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10070 self.dismiss_diagnostics(cx);
10071 let snapshot = self.snapshot(cx);
10072 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10073 let buffer = self.buffer.read(cx).snapshot(cx);
10074
10075 let mut primary_range = None;
10076 let mut primary_message = None;
10077 let mut group_end = Point::zero();
10078 let diagnostic_group = buffer
10079 .diagnostic_group::<MultiBufferPoint>(group_id)
10080 .filter_map(|entry| {
10081 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10082 && (entry.range.start.row == entry.range.end.row
10083 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10084 {
10085 return None;
10086 }
10087 if entry.range.end > group_end {
10088 group_end = entry.range.end;
10089 }
10090 if entry.diagnostic.is_primary {
10091 primary_range = Some(entry.range.clone());
10092 primary_message = Some(entry.diagnostic.message.clone());
10093 }
10094 Some(entry)
10095 })
10096 .collect::<Vec<_>>();
10097 let primary_range = primary_range?;
10098 let primary_message = primary_message?;
10099 let primary_range =
10100 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10101
10102 let blocks = display_map
10103 .insert_blocks(
10104 diagnostic_group.iter().map(|entry| {
10105 let diagnostic = entry.diagnostic.clone();
10106 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10107 BlockProperties {
10108 style: BlockStyle::Fixed,
10109 position: buffer.anchor_after(entry.range.start),
10110 height: message_height,
10111 render: diagnostic_block_renderer(diagnostic, None, true, true),
10112 disposition: BlockDisposition::Below,
10113 priority: 0,
10114 }
10115 }),
10116 cx,
10117 )
10118 .into_iter()
10119 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10120 .collect();
10121
10122 Some(ActiveDiagnosticGroup {
10123 primary_range,
10124 primary_message,
10125 group_id,
10126 blocks,
10127 is_valid: true,
10128 })
10129 });
10130 self.active_diagnostics.is_some()
10131 }
10132
10133 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10134 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10135 self.display_map.update(cx, |display_map, cx| {
10136 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10137 });
10138 cx.notify();
10139 }
10140 }
10141
10142 pub fn set_selections_from_remote(
10143 &mut self,
10144 selections: Vec<Selection<Anchor>>,
10145 pending_selection: Option<Selection<Anchor>>,
10146 cx: &mut ViewContext<Self>,
10147 ) {
10148 let old_cursor_position = self.selections.newest_anchor().head();
10149 self.selections.change_with(cx, |s| {
10150 s.select_anchors(selections);
10151 if let Some(pending_selection) = pending_selection {
10152 s.set_pending(pending_selection, SelectMode::Character);
10153 } else {
10154 s.clear_pending();
10155 }
10156 });
10157 self.selections_did_change(false, &old_cursor_position, true, cx);
10158 }
10159
10160 fn push_to_selection_history(&mut self) {
10161 self.selection_history.push(SelectionHistoryEntry {
10162 selections: self.selections.disjoint_anchors(),
10163 select_next_state: self.select_next_state.clone(),
10164 select_prev_state: self.select_prev_state.clone(),
10165 add_selections_state: self.add_selections_state.clone(),
10166 });
10167 }
10168
10169 pub fn transact(
10170 &mut self,
10171 cx: &mut ViewContext<Self>,
10172 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10173 ) -> Option<TransactionId> {
10174 self.start_transaction_at(Instant::now(), cx);
10175 update(self, cx);
10176 self.end_transaction_at(Instant::now(), cx)
10177 }
10178
10179 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10180 self.end_selection(cx);
10181 if let Some(tx_id) = self
10182 .buffer
10183 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10184 {
10185 self.selection_history
10186 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10187 cx.emit(EditorEvent::TransactionBegun {
10188 transaction_id: tx_id,
10189 })
10190 }
10191 }
10192
10193 fn end_transaction_at(
10194 &mut self,
10195 now: Instant,
10196 cx: &mut ViewContext<Self>,
10197 ) -> Option<TransactionId> {
10198 if let Some(transaction_id) = self
10199 .buffer
10200 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10201 {
10202 if let Some((_, end_selections)) =
10203 self.selection_history.transaction_mut(transaction_id)
10204 {
10205 *end_selections = Some(self.selections.disjoint_anchors());
10206 } else {
10207 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10208 }
10209
10210 cx.emit(EditorEvent::Edited { transaction_id });
10211 Some(transaction_id)
10212 } else {
10213 None
10214 }
10215 }
10216
10217 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10218 let mut fold_ranges = Vec::new();
10219
10220 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10221
10222 let selections = self.selections.all_adjusted(cx);
10223 for selection in selections {
10224 let range = selection.range().sorted();
10225 let buffer_start_row = range.start.row;
10226
10227 for row in (0..=range.end.row).rev() {
10228 if let Some((foldable_range, fold_text)) =
10229 display_map.foldable_range(MultiBufferRow(row))
10230 {
10231 if foldable_range.end.row >= buffer_start_row {
10232 fold_ranges.push((foldable_range, fold_text));
10233 if row <= range.start.row {
10234 break;
10235 }
10236 }
10237 }
10238 }
10239 }
10240
10241 self.fold_ranges(fold_ranges, true, cx);
10242 }
10243
10244 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10245 let buffer_row = fold_at.buffer_row;
10246 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10247
10248 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10249 let autoscroll = self
10250 .selections
10251 .all::<Point>(cx)
10252 .iter()
10253 .any(|selection| fold_range.overlaps(&selection.range()));
10254
10255 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10256 }
10257 }
10258
10259 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10260 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10261 let buffer = &display_map.buffer_snapshot;
10262 let selections = self.selections.all::<Point>(cx);
10263 let ranges = selections
10264 .iter()
10265 .map(|s| {
10266 let range = s.display_range(&display_map).sorted();
10267 let mut start = range.start.to_point(&display_map);
10268 let mut end = range.end.to_point(&display_map);
10269 start.column = 0;
10270 end.column = buffer.line_len(MultiBufferRow(end.row));
10271 start..end
10272 })
10273 .collect::<Vec<_>>();
10274
10275 self.unfold_ranges(ranges, true, true, cx);
10276 }
10277
10278 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10279 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10280
10281 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10282 ..Point::new(
10283 unfold_at.buffer_row.0,
10284 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10285 );
10286
10287 let autoscroll = self
10288 .selections
10289 .all::<Point>(cx)
10290 .iter()
10291 .any(|selection| selection.range().overlaps(&intersection_range));
10292
10293 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10294 }
10295
10296 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10297 let selections = self.selections.all::<Point>(cx);
10298 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10299 let line_mode = self.selections.line_mode;
10300 let ranges = selections.into_iter().map(|s| {
10301 if line_mode {
10302 let start = Point::new(s.start.row, 0);
10303 let end = Point::new(
10304 s.end.row,
10305 display_map
10306 .buffer_snapshot
10307 .line_len(MultiBufferRow(s.end.row)),
10308 );
10309 (start..end, display_map.fold_placeholder.clone())
10310 } else {
10311 (s.start..s.end, display_map.fold_placeholder.clone())
10312 }
10313 });
10314 self.fold_ranges(ranges, true, cx);
10315 }
10316
10317 pub fn fold_ranges<T: ToOffset + Clone>(
10318 &mut self,
10319 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10320 auto_scroll: bool,
10321 cx: &mut ViewContext<Self>,
10322 ) {
10323 let mut fold_ranges = Vec::new();
10324 let mut buffers_affected = HashMap::default();
10325 let multi_buffer = self.buffer().read(cx);
10326 for (fold_range, fold_text) in ranges {
10327 if let Some((_, buffer, _)) =
10328 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10329 {
10330 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10331 };
10332 fold_ranges.push((fold_range, fold_text));
10333 }
10334
10335 let mut ranges = fold_ranges.into_iter().peekable();
10336 if ranges.peek().is_some() {
10337 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10338
10339 if auto_scroll {
10340 self.request_autoscroll(Autoscroll::fit(), cx);
10341 }
10342
10343 for buffer in buffers_affected.into_values() {
10344 self.sync_expanded_diff_hunks(buffer, cx);
10345 }
10346
10347 cx.notify();
10348
10349 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10350 // Clear diagnostics block when folding a range that contains it.
10351 let snapshot = self.snapshot(cx);
10352 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10353 drop(snapshot);
10354 self.active_diagnostics = Some(active_diagnostics);
10355 self.dismiss_diagnostics(cx);
10356 } else {
10357 self.active_diagnostics = Some(active_diagnostics);
10358 }
10359 }
10360
10361 self.scrollbar_marker_state.dirty = true;
10362 }
10363 }
10364
10365 pub fn unfold_ranges<T: ToOffset + Clone>(
10366 &mut self,
10367 ranges: impl IntoIterator<Item = Range<T>>,
10368 inclusive: bool,
10369 auto_scroll: bool,
10370 cx: &mut ViewContext<Self>,
10371 ) {
10372 let mut unfold_ranges = Vec::new();
10373 let mut buffers_affected = HashMap::default();
10374 let multi_buffer = self.buffer().read(cx);
10375 for range in ranges {
10376 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10377 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10378 };
10379 unfold_ranges.push(range);
10380 }
10381
10382 let mut ranges = unfold_ranges.into_iter().peekable();
10383 if ranges.peek().is_some() {
10384 self.display_map
10385 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10386 if auto_scroll {
10387 self.request_autoscroll(Autoscroll::fit(), cx);
10388 }
10389
10390 for buffer in buffers_affected.into_values() {
10391 self.sync_expanded_diff_hunks(buffer, cx);
10392 }
10393
10394 cx.notify();
10395 self.scrollbar_marker_state.dirty = true;
10396 self.active_indent_guides_state.dirty = true;
10397 }
10398 }
10399
10400 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10401 self.display_map.read(cx).fold_placeholder.clone()
10402 }
10403
10404 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10405 if hovered != self.gutter_hovered {
10406 self.gutter_hovered = hovered;
10407 cx.notify();
10408 }
10409 }
10410
10411 pub fn insert_blocks(
10412 &mut self,
10413 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10414 autoscroll: Option<Autoscroll>,
10415 cx: &mut ViewContext<Self>,
10416 ) -> Vec<CustomBlockId> {
10417 let blocks = self
10418 .display_map
10419 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10420 if let Some(autoscroll) = autoscroll {
10421 self.request_autoscroll(autoscroll, cx);
10422 }
10423 cx.notify();
10424 blocks
10425 }
10426
10427 pub fn resize_blocks(
10428 &mut self,
10429 heights: HashMap<CustomBlockId, u32>,
10430 autoscroll: Option<Autoscroll>,
10431 cx: &mut ViewContext<Self>,
10432 ) {
10433 self.display_map
10434 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10435 if let Some(autoscroll) = autoscroll {
10436 self.request_autoscroll(autoscroll, cx);
10437 }
10438 cx.notify();
10439 }
10440
10441 pub fn replace_blocks(
10442 &mut self,
10443 renderers: HashMap<CustomBlockId, RenderBlock>,
10444 autoscroll: Option<Autoscroll>,
10445 cx: &mut ViewContext<Self>,
10446 ) {
10447 self.display_map
10448 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10449 if let Some(autoscroll) = autoscroll {
10450 self.request_autoscroll(autoscroll, cx);
10451 }
10452 cx.notify();
10453 }
10454
10455 pub fn remove_blocks(
10456 &mut self,
10457 block_ids: HashSet<CustomBlockId>,
10458 autoscroll: Option<Autoscroll>,
10459 cx: &mut ViewContext<Self>,
10460 ) {
10461 self.display_map.update(cx, |display_map, cx| {
10462 display_map.remove_blocks(block_ids, cx)
10463 });
10464 if let Some(autoscroll) = autoscroll {
10465 self.request_autoscroll(autoscroll, cx);
10466 }
10467 cx.notify();
10468 }
10469
10470 pub fn row_for_block(
10471 &self,
10472 block_id: CustomBlockId,
10473 cx: &mut ViewContext<Self>,
10474 ) -> Option<DisplayRow> {
10475 self.display_map
10476 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10477 }
10478
10479 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10480 self.focused_block = Some(focused_block);
10481 }
10482
10483 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10484 self.focused_block.take()
10485 }
10486
10487 pub fn insert_creases(
10488 &mut self,
10489 creases: impl IntoIterator<Item = Crease>,
10490 cx: &mut ViewContext<Self>,
10491 ) -> Vec<CreaseId> {
10492 self.display_map
10493 .update(cx, |map, cx| map.insert_creases(creases, cx))
10494 }
10495
10496 pub fn remove_creases(
10497 &mut self,
10498 ids: impl IntoIterator<Item = CreaseId>,
10499 cx: &mut ViewContext<Self>,
10500 ) {
10501 self.display_map
10502 .update(cx, |map, cx| map.remove_creases(ids, cx));
10503 }
10504
10505 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10506 self.display_map
10507 .update(cx, |map, cx| map.snapshot(cx))
10508 .longest_row()
10509 }
10510
10511 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10512 self.display_map
10513 .update(cx, |map, cx| map.snapshot(cx))
10514 .max_point()
10515 }
10516
10517 pub fn text(&self, cx: &AppContext) -> String {
10518 self.buffer.read(cx).read(cx).text()
10519 }
10520
10521 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10522 let text = self.text(cx);
10523 let text = text.trim();
10524
10525 if text.is_empty() {
10526 return None;
10527 }
10528
10529 Some(text.to_string())
10530 }
10531
10532 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10533 self.transact(cx, |this, cx| {
10534 this.buffer
10535 .read(cx)
10536 .as_singleton()
10537 .expect("you can only call set_text on editors for singleton buffers")
10538 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10539 });
10540 }
10541
10542 pub fn display_text(&self, cx: &mut AppContext) -> String {
10543 self.display_map
10544 .update(cx, |map, cx| map.snapshot(cx))
10545 .text()
10546 }
10547
10548 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10549 let mut wrap_guides = smallvec::smallvec![];
10550
10551 if self.show_wrap_guides == Some(false) {
10552 return wrap_guides;
10553 }
10554
10555 let settings = self.buffer.read(cx).settings_at(0, cx);
10556 if settings.show_wrap_guides {
10557 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10558 wrap_guides.push((soft_wrap as usize, true));
10559 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
10560 wrap_guides.push((soft_wrap as usize, true));
10561 }
10562 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10563 }
10564
10565 wrap_guides
10566 }
10567
10568 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10569 let settings = self.buffer.read(cx).settings_at(0, cx);
10570 let mode = self
10571 .soft_wrap_mode_override
10572 .unwrap_or_else(|| settings.soft_wrap);
10573 match mode {
10574 language_settings::SoftWrap::None => SoftWrap::None,
10575 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10576 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10577 language_settings::SoftWrap::PreferredLineLength => {
10578 SoftWrap::Column(settings.preferred_line_length)
10579 }
10580 language_settings::SoftWrap::Bounded => {
10581 SoftWrap::Bounded(settings.preferred_line_length)
10582 }
10583 }
10584 }
10585
10586 pub fn set_soft_wrap_mode(
10587 &mut self,
10588 mode: language_settings::SoftWrap,
10589 cx: &mut ViewContext<Self>,
10590 ) {
10591 self.soft_wrap_mode_override = Some(mode);
10592 cx.notify();
10593 }
10594
10595 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10596 let rem_size = cx.rem_size();
10597 self.display_map.update(cx, |map, cx| {
10598 map.set_font(
10599 style.text.font(),
10600 style.text.font_size.to_pixels(rem_size),
10601 cx,
10602 )
10603 });
10604 self.style = Some(style);
10605 }
10606
10607 pub fn style(&self) -> Option<&EditorStyle> {
10608 self.style.as_ref()
10609 }
10610
10611 // Called by the element. This method is not designed to be called outside of the editor
10612 // element's layout code because it does not notify when rewrapping is computed synchronously.
10613 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10614 self.display_map
10615 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10616 }
10617
10618 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10619 if self.soft_wrap_mode_override.is_some() {
10620 self.soft_wrap_mode_override.take();
10621 } else {
10622 let soft_wrap = match self.soft_wrap_mode(cx) {
10623 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10624 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
10625 language_settings::SoftWrap::PreferLine
10626 }
10627 };
10628 self.soft_wrap_mode_override = Some(soft_wrap);
10629 }
10630 cx.notify();
10631 }
10632
10633 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10634 let Some(workspace) = self.workspace() else {
10635 return;
10636 };
10637 let fs = workspace.read(cx).app_state().fs.clone();
10638 let current_show = TabBarSettings::get_global(cx).show;
10639 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10640 setting.show = Some(!current_show);
10641 });
10642 }
10643
10644 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10645 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10646 self.buffer
10647 .read(cx)
10648 .settings_at(0, cx)
10649 .indent_guides
10650 .enabled
10651 });
10652 self.show_indent_guides = Some(!currently_enabled);
10653 cx.notify();
10654 }
10655
10656 fn should_show_indent_guides(&self) -> Option<bool> {
10657 self.show_indent_guides
10658 }
10659
10660 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10661 let mut editor_settings = EditorSettings::get_global(cx).clone();
10662 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10663 EditorSettings::override_global(editor_settings, cx);
10664 }
10665
10666 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
10667 self.use_relative_line_numbers
10668 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
10669 }
10670
10671 pub fn toggle_relative_line_numbers(
10672 &mut self,
10673 _: &ToggleRelativeLineNumbers,
10674 cx: &mut ViewContext<Self>,
10675 ) {
10676 let is_relative = self.should_use_relative_line_numbers(cx);
10677 self.set_relative_line_number(Some(!is_relative), cx)
10678 }
10679
10680 pub fn set_relative_line_number(
10681 &mut self,
10682 is_relative: Option<bool>,
10683 cx: &mut ViewContext<Self>,
10684 ) {
10685 self.use_relative_line_numbers = is_relative;
10686 cx.notify();
10687 }
10688
10689 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10690 self.show_gutter = show_gutter;
10691 cx.notify();
10692 }
10693
10694 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10695 self.show_line_numbers = Some(show_line_numbers);
10696 cx.notify();
10697 }
10698
10699 pub fn set_show_git_diff_gutter(
10700 &mut self,
10701 show_git_diff_gutter: bool,
10702 cx: &mut ViewContext<Self>,
10703 ) {
10704 self.show_git_diff_gutter = Some(show_git_diff_gutter);
10705 cx.notify();
10706 }
10707
10708 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10709 self.show_code_actions = Some(show_code_actions);
10710 cx.notify();
10711 }
10712
10713 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10714 self.show_runnables = Some(show_runnables);
10715 cx.notify();
10716 }
10717
10718 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
10719 if self.display_map.read(cx).masked != masked {
10720 self.display_map.update(cx, |map, _| map.masked = masked);
10721 }
10722 cx.notify()
10723 }
10724
10725 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10726 self.show_wrap_guides = Some(show_wrap_guides);
10727 cx.notify();
10728 }
10729
10730 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10731 self.show_indent_guides = Some(show_indent_guides);
10732 cx.notify();
10733 }
10734
10735 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10736 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10737 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10738 if let Some(dir) = file.abs_path(cx).parent() {
10739 return Some(dir.to_owned());
10740 }
10741 }
10742
10743 if let Some(project_path) = buffer.read(cx).project_path(cx) {
10744 return Some(project_path.path.to_path_buf());
10745 }
10746 }
10747
10748 None
10749 }
10750
10751 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10752 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10753 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10754 cx.reveal_path(&file.abs_path(cx));
10755 }
10756 }
10757 }
10758
10759 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10760 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10761 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10762 if let Some(path) = file.abs_path(cx).to_str() {
10763 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10764 }
10765 }
10766 }
10767 }
10768
10769 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10770 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10771 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10772 if let Some(path) = file.path().to_str() {
10773 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10774 }
10775 }
10776 }
10777 }
10778
10779 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10780 self.show_git_blame_gutter = !self.show_git_blame_gutter;
10781
10782 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10783 self.start_git_blame(true, cx);
10784 }
10785
10786 cx.notify();
10787 }
10788
10789 pub fn toggle_git_blame_inline(
10790 &mut self,
10791 _: &ToggleGitBlameInline,
10792 cx: &mut ViewContext<Self>,
10793 ) {
10794 self.toggle_git_blame_inline_internal(true, cx);
10795 cx.notify();
10796 }
10797
10798 pub fn git_blame_inline_enabled(&self) -> bool {
10799 self.git_blame_inline_enabled
10800 }
10801
10802 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10803 self.show_selection_menu = self
10804 .show_selection_menu
10805 .map(|show_selections_menu| !show_selections_menu)
10806 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10807
10808 cx.notify();
10809 }
10810
10811 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10812 self.show_selection_menu
10813 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10814 }
10815
10816 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10817 if let Some(project) = self.project.as_ref() {
10818 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10819 return;
10820 };
10821
10822 if buffer.read(cx).file().is_none() {
10823 return;
10824 }
10825
10826 let focused = self.focus_handle(cx).contains_focused(cx);
10827
10828 let project = project.clone();
10829 let blame =
10830 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10831 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10832 self.blame = Some(blame);
10833 }
10834 }
10835
10836 fn toggle_git_blame_inline_internal(
10837 &mut self,
10838 user_triggered: bool,
10839 cx: &mut ViewContext<Self>,
10840 ) {
10841 if self.git_blame_inline_enabled {
10842 self.git_blame_inline_enabled = false;
10843 self.show_git_blame_inline = false;
10844 self.show_git_blame_inline_delay_task.take();
10845 } else {
10846 self.git_blame_inline_enabled = true;
10847 self.start_git_blame_inline(user_triggered, cx);
10848 }
10849
10850 cx.notify();
10851 }
10852
10853 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10854 self.start_git_blame(user_triggered, cx);
10855
10856 if ProjectSettings::get_global(cx)
10857 .git
10858 .inline_blame_delay()
10859 .is_some()
10860 {
10861 self.start_inline_blame_timer(cx);
10862 } else {
10863 self.show_git_blame_inline = true
10864 }
10865 }
10866
10867 pub fn blame(&self) -> Option<&Model<GitBlame>> {
10868 self.blame.as_ref()
10869 }
10870
10871 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10872 self.show_git_blame_gutter && self.has_blame_entries(cx)
10873 }
10874
10875 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10876 self.show_git_blame_inline
10877 && self.focus_handle.is_focused(cx)
10878 && !self.newest_selection_head_on_empty_line(cx)
10879 && self.has_blame_entries(cx)
10880 }
10881
10882 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10883 self.blame()
10884 .map_or(false, |blame| blame.read(cx).has_generated_entries())
10885 }
10886
10887 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10888 let cursor_anchor = self.selections.newest_anchor().head();
10889
10890 let snapshot = self.buffer.read(cx).snapshot(cx);
10891 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10892
10893 snapshot.line_len(buffer_row) == 0
10894 }
10895
10896 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10897 let (path, selection, repo) = maybe!({
10898 let project_handle = self.project.as_ref()?.clone();
10899 let project = project_handle.read(cx);
10900
10901 let selection = self.selections.newest::<Point>(cx);
10902 let selection_range = selection.range();
10903
10904 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10905 (buffer, selection_range.start.row..selection_range.end.row)
10906 } else {
10907 let buffer_ranges = self
10908 .buffer()
10909 .read(cx)
10910 .range_to_buffer_ranges(selection_range, cx);
10911
10912 let (buffer, range, _) = if selection.reversed {
10913 buffer_ranges.first()
10914 } else {
10915 buffer_ranges.last()
10916 }?;
10917
10918 let snapshot = buffer.read(cx).snapshot();
10919 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10920 ..text::ToPoint::to_point(&range.end, &snapshot).row;
10921 (buffer.clone(), selection)
10922 };
10923
10924 let path = buffer
10925 .read(cx)
10926 .file()?
10927 .as_local()?
10928 .path()
10929 .to_str()?
10930 .to_string();
10931 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10932 Some((path, selection, repo))
10933 })
10934 .ok_or_else(|| anyhow!("unable to open git repository"))?;
10935
10936 const REMOTE_NAME: &str = "origin";
10937 let origin_url = repo
10938 .remote_url(REMOTE_NAME)
10939 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10940 let sha = repo
10941 .head_sha()
10942 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10943
10944 let (provider, remote) =
10945 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10946 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10947
10948 Ok(provider.build_permalink(
10949 remote,
10950 BuildPermalinkParams {
10951 sha: &sha,
10952 path: &path,
10953 selection: Some(selection),
10954 },
10955 ))
10956 }
10957
10958 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10959 let permalink = self.get_permalink_to_line(cx);
10960
10961 match permalink {
10962 Ok(permalink) => {
10963 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
10964 }
10965 Err(err) => {
10966 let message = format!("Failed to copy permalink: {err}");
10967
10968 Err::<(), anyhow::Error>(err).log_err();
10969
10970 if let Some(workspace) = self.workspace() {
10971 workspace.update(cx, |workspace, cx| {
10972 struct CopyPermalinkToLine;
10973
10974 workspace.show_toast(
10975 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10976 cx,
10977 )
10978 })
10979 }
10980 }
10981 }
10982 }
10983
10984 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
10985 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10986 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10987 if let Some(path) = file.path().to_str() {
10988 let selection = self.selections.newest::<Point>(cx).start.row + 1;
10989 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
10990 }
10991 }
10992 }
10993 }
10994
10995 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10996 let permalink = self.get_permalink_to_line(cx);
10997
10998 match permalink {
10999 Ok(permalink) => {
11000 cx.open_url(permalink.as_ref());
11001 }
11002 Err(err) => {
11003 let message = format!("Failed to open permalink: {err}");
11004
11005 Err::<(), anyhow::Error>(err).log_err();
11006
11007 if let Some(workspace) = self.workspace() {
11008 workspace.update(cx, |workspace, cx| {
11009 struct OpenPermalinkToLine;
11010
11011 workspace.show_toast(
11012 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11013 cx,
11014 )
11015 })
11016 }
11017 }
11018 }
11019 }
11020
11021 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
11022 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
11023 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
11024 pub fn highlight_rows<T: 'static>(
11025 &mut self,
11026 rows: RangeInclusive<Anchor>,
11027 color: Option<Hsla>,
11028 should_autoscroll: bool,
11029 cx: &mut ViewContext<Self>,
11030 ) {
11031 let snapshot = self.buffer().read(cx).snapshot(cx);
11032 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11033 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
11034 highlight
11035 .range
11036 .start()
11037 .cmp(&rows.start(), &snapshot)
11038 .then(highlight.range.end().cmp(&rows.end(), &snapshot))
11039 });
11040 match (color, existing_highlight_index) {
11041 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
11042 ix,
11043 RowHighlight {
11044 index: post_inc(&mut self.highlight_order),
11045 range: rows,
11046 should_autoscroll,
11047 color,
11048 },
11049 ),
11050 (None, Ok(i)) => {
11051 row_highlights.remove(i);
11052 }
11053 }
11054 }
11055
11056 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11057 pub fn clear_row_highlights<T: 'static>(&mut self) {
11058 self.highlighted_rows.remove(&TypeId::of::<T>());
11059 }
11060
11061 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11062 pub fn highlighted_rows<T: 'static>(
11063 &self,
11064 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
11065 Some(
11066 self.highlighted_rows
11067 .get(&TypeId::of::<T>())?
11068 .iter()
11069 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
11070 )
11071 }
11072
11073 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11074 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11075 /// Allows to ignore certain kinds of highlights.
11076 pub fn highlighted_display_rows(
11077 &mut self,
11078 cx: &mut WindowContext,
11079 ) -> BTreeMap<DisplayRow, Hsla> {
11080 let snapshot = self.snapshot(cx);
11081 let mut used_highlight_orders = HashMap::default();
11082 self.highlighted_rows
11083 .iter()
11084 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11085 .fold(
11086 BTreeMap::<DisplayRow, Hsla>::new(),
11087 |mut unique_rows, highlight| {
11088 let start_row = highlight.range.start().to_display_point(&snapshot).row();
11089 let end_row = highlight.range.end().to_display_point(&snapshot).row();
11090 for row in start_row.0..=end_row.0 {
11091 let used_index =
11092 used_highlight_orders.entry(row).or_insert(highlight.index);
11093 if highlight.index >= *used_index {
11094 *used_index = highlight.index;
11095 match highlight.color {
11096 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
11097 None => unique_rows.remove(&DisplayRow(row)),
11098 };
11099 }
11100 }
11101 unique_rows
11102 },
11103 )
11104 }
11105
11106 pub fn highlighted_display_row_for_autoscroll(
11107 &self,
11108 snapshot: &DisplaySnapshot,
11109 ) -> Option<DisplayRow> {
11110 self.highlighted_rows
11111 .values()
11112 .flat_map(|highlighted_rows| highlighted_rows.iter())
11113 .filter_map(|highlight| {
11114 if highlight.color.is_none() || !highlight.should_autoscroll {
11115 return None;
11116 }
11117 Some(highlight.range.start().to_display_point(&snapshot).row())
11118 })
11119 .min()
11120 }
11121
11122 pub fn set_search_within_ranges(
11123 &mut self,
11124 ranges: &[Range<Anchor>],
11125 cx: &mut ViewContext<Self>,
11126 ) {
11127 self.highlight_background::<SearchWithinRange>(
11128 ranges,
11129 |colors| colors.editor_document_highlight_read_background,
11130 cx,
11131 )
11132 }
11133
11134 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11135 self.breadcrumb_header = Some(new_header);
11136 }
11137
11138 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11139 self.clear_background_highlights::<SearchWithinRange>(cx);
11140 }
11141
11142 pub fn highlight_background<T: 'static>(
11143 &mut self,
11144 ranges: &[Range<Anchor>],
11145 color_fetcher: fn(&ThemeColors) -> Hsla,
11146 cx: &mut ViewContext<Self>,
11147 ) {
11148 self.background_highlights
11149 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11150 self.scrollbar_marker_state.dirty = true;
11151 cx.notify();
11152 }
11153
11154 pub fn clear_background_highlights<T: 'static>(
11155 &mut self,
11156 cx: &mut ViewContext<Self>,
11157 ) -> Option<BackgroundHighlight> {
11158 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11159 if !text_highlights.1.is_empty() {
11160 self.scrollbar_marker_state.dirty = true;
11161 cx.notify();
11162 }
11163 Some(text_highlights)
11164 }
11165
11166 pub fn highlight_gutter<T: 'static>(
11167 &mut self,
11168 ranges: &[Range<Anchor>],
11169 color_fetcher: fn(&AppContext) -> Hsla,
11170 cx: &mut ViewContext<Self>,
11171 ) {
11172 self.gutter_highlights
11173 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11174 cx.notify();
11175 }
11176
11177 pub fn clear_gutter_highlights<T: 'static>(
11178 &mut self,
11179 cx: &mut ViewContext<Self>,
11180 ) -> Option<GutterHighlight> {
11181 cx.notify();
11182 self.gutter_highlights.remove(&TypeId::of::<T>())
11183 }
11184
11185 #[cfg(feature = "test-support")]
11186 pub fn all_text_background_highlights(
11187 &mut self,
11188 cx: &mut ViewContext<Self>,
11189 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11190 let snapshot = self.snapshot(cx);
11191 let buffer = &snapshot.buffer_snapshot;
11192 let start = buffer.anchor_before(0);
11193 let end = buffer.anchor_after(buffer.len());
11194 let theme = cx.theme().colors();
11195 self.background_highlights_in_range(start..end, &snapshot, theme)
11196 }
11197
11198 #[cfg(feature = "test-support")]
11199 pub fn search_background_highlights(
11200 &mut self,
11201 cx: &mut ViewContext<Self>,
11202 ) -> Vec<Range<Point>> {
11203 let snapshot = self.buffer().read(cx).snapshot(cx);
11204
11205 let highlights = self
11206 .background_highlights
11207 .get(&TypeId::of::<items::BufferSearchHighlights>());
11208
11209 if let Some((_color, ranges)) = highlights {
11210 ranges
11211 .iter()
11212 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11213 .collect_vec()
11214 } else {
11215 vec![]
11216 }
11217 }
11218
11219 fn document_highlights_for_position<'a>(
11220 &'a self,
11221 position: Anchor,
11222 buffer: &'a MultiBufferSnapshot,
11223 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
11224 let read_highlights = self
11225 .background_highlights
11226 .get(&TypeId::of::<DocumentHighlightRead>())
11227 .map(|h| &h.1);
11228 let write_highlights = self
11229 .background_highlights
11230 .get(&TypeId::of::<DocumentHighlightWrite>())
11231 .map(|h| &h.1);
11232 let left_position = position.bias_left(buffer);
11233 let right_position = position.bias_right(buffer);
11234 read_highlights
11235 .into_iter()
11236 .chain(write_highlights)
11237 .flat_map(move |ranges| {
11238 let start_ix = match ranges.binary_search_by(|probe| {
11239 let cmp = probe.end.cmp(&left_position, buffer);
11240 if cmp.is_ge() {
11241 Ordering::Greater
11242 } else {
11243 Ordering::Less
11244 }
11245 }) {
11246 Ok(i) | Err(i) => i,
11247 };
11248
11249 ranges[start_ix..]
11250 .iter()
11251 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11252 })
11253 }
11254
11255 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11256 self.background_highlights
11257 .get(&TypeId::of::<T>())
11258 .map_or(false, |(_, highlights)| !highlights.is_empty())
11259 }
11260
11261 pub fn background_highlights_in_range(
11262 &self,
11263 search_range: Range<Anchor>,
11264 display_snapshot: &DisplaySnapshot,
11265 theme: &ThemeColors,
11266 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11267 let mut results = Vec::new();
11268 for (color_fetcher, ranges) in self.background_highlights.values() {
11269 let color = color_fetcher(theme);
11270 let start_ix = match ranges.binary_search_by(|probe| {
11271 let cmp = probe
11272 .end
11273 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11274 if cmp.is_gt() {
11275 Ordering::Greater
11276 } else {
11277 Ordering::Less
11278 }
11279 }) {
11280 Ok(i) | Err(i) => i,
11281 };
11282 for range in &ranges[start_ix..] {
11283 if range
11284 .start
11285 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11286 .is_ge()
11287 {
11288 break;
11289 }
11290
11291 let start = range.start.to_display_point(&display_snapshot);
11292 let end = range.end.to_display_point(&display_snapshot);
11293 results.push((start..end, color))
11294 }
11295 }
11296 results
11297 }
11298
11299 pub fn background_highlight_row_ranges<T: 'static>(
11300 &self,
11301 search_range: Range<Anchor>,
11302 display_snapshot: &DisplaySnapshot,
11303 count: usize,
11304 ) -> Vec<RangeInclusive<DisplayPoint>> {
11305 let mut results = Vec::new();
11306 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11307 return vec![];
11308 };
11309
11310 let start_ix = match ranges.binary_search_by(|probe| {
11311 let cmp = probe
11312 .end
11313 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11314 if cmp.is_gt() {
11315 Ordering::Greater
11316 } else {
11317 Ordering::Less
11318 }
11319 }) {
11320 Ok(i) | Err(i) => i,
11321 };
11322 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11323 if let (Some(start_display), Some(end_display)) = (start, end) {
11324 results.push(
11325 start_display.to_display_point(display_snapshot)
11326 ..=end_display.to_display_point(display_snapshot),
11327 );
11328 }
11329 };
11330 let mut start_row: Option<Point> = None;
11331 let mut end_row: Option<Point> = None;
11332 if ranges.len() > count {
11333 return Vec::new();
11334 }
11335 for range in &ranges[start_ix..] {
11336 if range
11337 .start
11338 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11339 .is_ge()
11340 {
11341 break;
11342 }
11343 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11344 if let Some(current_row) = &end_row {
11345 if end.row == current_row.row {
11346 continue;
11347 }
11348 }
11349 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11350 if start_row.is_none() {
11351 assert_eq!(end_row, None);
11352 start_row = Some(start);
11353 end_row = Some(end);
11354 continue;
11355 }
11356 if let Some(current_end) = end_row.as_mut() {
11357 if start.row > current_end.row + 1 {
11358 push_region(start_row, end_row);
11359 start_row = Some(start);
11360 end_row = Some(end);
11361 } else {
11362 // Merge two hunks.
11363 *current_end = end;
11364 }
11365 } else {
11366 unreachable!();
11367 }
11368 }
11369 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11370 push_region(start_row, end_row);
11371 results
11372 }
11373
11374 pub fn gutter_highlights_in_range(
11375 &self,
11376 search_range: Range<Anchor>,
11377 display_snapshot: &DisplaySnapshot,
11378 cx: &AppContext,
11379 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11380 let mut results = Vec::new();
11381 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11382 let color = color_fetcher(cx);
11383 let start_ix = match ranges.binary_search_by(|probe| {
11384 let cmp = probe
11385 .end
11386 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11387 if cmp.is_gt() {
11388 Ordering::Greater
11389 } else {
11390 Ordering::Less
11391 }
11392 }) {
11393 Ok(i) | Err(i) => i,
11394 };
11395 for range in &ranges[start_ix..] {
11396 if range
11397 .start
11398 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11399 .is_ge()
11400 {
11401 break;
11402 }
11403
11404 let start = range.start.to_display_point(&display_snapshot);
11405 let end = range.end.to_display_point(&display_snapshot);
11406 results.push((start..end, color))
11407 }
11408 }
11409 results
11410 }
11411
11412 /// Get the text ranges corresponding to the redaction query
11413 pub fn redacted_ranges(
11414 &self,
11415 search_range: Range<Anchor>,
11416 display_snapshot: &DisplaySnapshot,
11417 cx: &WindowContext,
11418 ) -> Vec<Range<DisplayPoint>> {
11419 display_snapshot
11420 .buffer_snapshot
11421 .redacted_ranges(search_range, |file| {
11422 if let Some(file) = file {
11423 file.is_private()
11424 && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
11425 } else {
11426 false
11427 }
11428 })
11429 .map(|range| {
11430 range.start.to_display_point(display_snapshot)
11431 ..range.end.to_display_point(display_snapshot)
11432 })
11433 .collect()
11434 }
11435
11436 pub fn highlight_text<T: 'static>(
11437 &mut self,
11438 ranges: Vec<Range<Anchor>>,
11439 style: HighlightStyle,
11440 cx: &mut ViewContext<Self>,
11441 ) {
11442 self.display_map.update(cx, |map, _| {
11443 map.highlight_text(TypeId::of::<T>(), ranges, style)
11444 });
11445 cx.notify();
11446 }
11447
11448 pub(crate) fn highlight_inlays<T: 'static>(
11449 &mut self,
11450 highlights: Vec<InlayHighlight>,
11451 style: HighlightStyle,
11452 cx: &mut ViewContext<Self>,
11453 ) {
11454 self.display_map.update(cx, |map, _| {
11455 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11456 });
11457 cx.notify();
11458 }
11459
11460 pub fn text_highlights<'a, T: 'static>(
11461 &'a self,
11462 cx: &'a AppContext,
11463 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11464 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11465 }
11466
11467 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11468 let cleared = self
11469 .display_map
11470 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11471 if cleared {
11472 cx.notify();
11473 }
11474 }
11475
11476 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11477 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11478 && self.focus_handle.is_focused(cx)
11479 }
11480
11481 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11482 self.show_cursor_when_unfocused = is_enabled;
11483 cx.notify();
11484 }
11485
11486 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11487 cx.notify();
11488 }
11489
11490 fn on_buffer_event(
11491 &mut self,
11492 multibuffer: Model<MultiBuffer>,
11493 event: &multi_buffer::Event,
11494 cx: &mut ViewContext<Self>,
11495 ) {
11496 match event {
11497 multi_buffer::Event::Edited {
11498 singleton_buffer_edited,
11499 } => {
11500 self.scrollbar_marker_state.dirty = true;
11501 self.active_indent_guides_state.dirty = true;
11502 self.refresh_active_diagnostics(cx);
11503 self.refresh_code_actions(cx);
11504 if self.has_active_inline_completion(cx) {
11505 self.update_visible_inline_completion(cx);
11506 }
11507 cx.emit(EditorEvent::BufferEdited);
11508 cx.emit(SearchEvent::MatchesInvalidated);
11509 if *singleton_buffer_edited {
11510 if let Some(project) = &self.project {
11511 let project = project.read(cx);
11512 #[allow(clippy::mutable_key_type)]
11513 let languages_affected = multibuffer
11514 .read(cx)
11515 .all_buffers()
11516 .into_iter()
11517 .filter_map(|buffer| {
11518 let buffer = buffer.read(cx);
11519 let language = buffer.language()?;
11520 if project.is_local_or_ssh()
11521 && project.language_servers_for_buffer(buffer, cx).count() == 0
11522 {
11523 None
11524 } else {
11525 Some(language)
11526 }
11527 })
11528 .cloned()
11529 .collect::<HashSet<_>>();
11530 if !languages_affected.is_empty() {
11531 self.refresh_inlay_hints(
11532 InlayHintRefreshReason::BufferEdited(languages_affected),
11533 cx,
11534 );
11535 }
11536 }
11537 }
11538
11539 let Some(project) = &self.project else { return };
11540 let telemetry = project.read(cx).client().telemetry().clone();
11541 refresh_linked_ranges(self, cx);
11542 telemetry.log_edit_event("editor");
11543 }
11544 multi_buffer::Event::ExcerptsAdded {
11545 buffer,
11546 predecessor,
11547 excerpts,
11548 } => {
11549 self.tasks_update_task = Some(self.refresh_runnables(cx));
11550 cx.emit(EditorEvent::ExcerptsAdded {
11551 buffer: buffer.clone(),
11552 predecessor: *predecessor,
11553 excerpts: excerpts.clone(),
11554 });
11555 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11556 }
11557 multi_buffer::Event::ExcerptsRemoved { ids } => {
11558 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11559 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11560 }
11561 multi_buffer::Event::ExcerptsEdited { ids } => {
11562 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11563 }
11564 multi_buffer::Event::ExcerptsExpanded { ids } => {
11565 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11566 }
11567 multi_buffer::Event::Reparsed(buffer_id) => {
11568 self.tasks_update_task = Some(self.refresh_runnables(cx));
11569
11570 cx.emit(EditorEvent::Reparsed(*buffer_id));
11571 }
11572 multi_buffer::Event::LanguageChanged(buffer_id) => {
11573 linked_editing_ranges::refresh_linked_ranges(self, cx);
11574 cx.emit(EditorEvent::Reparsed(*buffer_id));
11575 cx.notify();
11576 }
11577 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11578 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11579 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11580 cx.emit(EditorEvent::TitleChanged)
11581 }
11582 multi_buffer::Event::DiffBaseChanged => {
11583 self.scrollbar_marker_state.dirty = true;
11584 cx.emit(EditorEvent::DiffBaseChanged);
11585 cx.notify();
11586 }
11587 multi_buffer::Event::DiffUpdated { buffer } => {
11588 self.sync_expanded_diff_hunks(buffer.clone(), cx);
11589 cx.notify();
11590 }
11591 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11592 multi_buffer::Event::DiagnosticsUpdated => {
11593 self.refresh_active_diagnostics(cx);
11594 self.scrollbar_marker_state.dirty = true;
11595 cx.notify();
11596 }
11597 _ => {}
11598 };
11599 }
11600
11601 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11602 cx.notify();
11603 }
11604
11605 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11606 self.tasks_update_task = Some(self.refresh_runnables(cx));
11607 self.refresh_inline_completion(true, false, cx);
11608 self.refresh_inlay_hints(
11609 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11610 self.selections.newest_anchor().head(),
11611 &self.buffer.read(cx).snapshot(cx),
11612 cx,
11613 )),
11614 cx,
11615 );
11616 let editor_settings = EditorSettings::get_global(cx);
11617 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11618 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11619
11620 let project_settings = ProjectSettings::get_global(cx);
11621 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11622
11623 if self.mode == EditorMode::Full {
11624 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11625 if self.git_blame_inline_enabled != inline_blame_enabled {
11626 self.toggle_git_blame_inline_internal(false, cx);
11627 }
11628 }
11629
11630 cx.notify();
11631 }
11632
11633 pub fn set_searchable(&mut self, searchable: bool) {
11634 self.searchable = searchable;
11635 }
11636
11637 pub fn searchable(&self) -> bool {
11638 self.searchable
11639 }
11640
11641 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11642 self.open_excerpts_common(true, cx)
11643 }
11644
11645 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11646 self.open_excerpts_common(false, cx)
11647 }
11648
11649 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11650 let buffer = self.buffer.read(cx);
11651 if buffer.is_singleton() {
11652 cx.propagate();
11653 return;
11654 }
11655
11656 let Some(workspace) = self.workspace() else {
11657 cx.propagate();
11658 return;
11659 };
11660
11661 let mut new_selections_by_buffer = HashMap::default();
11662 for selection in self.selections.all::<usize>(cx) {
11663 for (buffer, mut range, _) in
11664 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11665 {
11666 if selection.reversed {
11667 mem::swap(&mut range.start, &mut range.end);
11668 }
11669 new_selections_by_buffer
11670 .entry(buffer)
11671 .or_insert(Vec::new())
11672 .push(range)
11673 }
11674 }
11675
11676 // We defer the pane interaction because we ourselves are a workspace item
11677 // and activating a new item causes the pane to call a method on us reentrantly,
11678 // which panics if we're on the stack.
11679 cx.window_context().defer(move |cx| {
11680 workspace.update(cx, |workspace, cx| {
11681 let pane = if split {
11682 workspace.adjacent_pane(cx)
11683 } else {
11684 workspace.active_pane().clone()
11685 };
11686
11687 for (buffer, ranges) in new_selections_by_buffer {
11688 let editor =
11689 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
11690 editor.update(cx, |editor, cx| {
11691 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11692 s.select_ranges(ranges);
11693 });
11694 });
11695 }
11696 })
11697 });
11698 }
11699
11700 fn jump(
11701 &mut self,
11702 path: ProjectPath,
11703 position: Point,
11704 anchor: language::Anchor,
11705 offset_from_top: u32,
11706 cx: &mut ViewContext<Self>,
11707 ) {
11708 let workspace = self.workspace();
11709 cx.spawn(|_, mut cx| async move {
11710 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11711 let editor = workspace.update(&mut cx, |workspace, cx| {
11712 // Reset the preview item id before opening the new item
11713 workspace.active_pane().update(cx, |pane, cx| {
11714 pane.set_preview_item_id(None, cx);
11715 });
11716 workspace.open_path_preview(path, None, true, true, cx)
11717 })?;
11718 let editor = editor
11719 .await?
11720 .downcast::<Editor>()
11721 .ok_or_else(|| anyhow!("opened item was not an editor"))?
11722 .downgrade();
11723 editor.update(&mut cx, |editor, cx| {
11724 let buffer = editor
11725 .buffer()
11726 .read(cx)
11727 .as_singleton()
11728 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11729 let buffer = buffer.read(cx);
11730 let cursor = if buffer.can_resolve(&anchor) {
11731 language::ToPoint::to_point(&anchor, buffer)
11732 } else {
11733 buffer.clip_point(position, Bias::Left)
11734 };
11735
11736 let nav_history = editor.nav_history.take();
11737 editor.change_selections(
11738 Some(Autoscroll::top_relative(offset_from_top as usize)),
11739 cx,
11740 |s| {
11741 s.select_ranges([cursor..cursor]);
11742 },
11743 );
11744 editor.nav_history = nav_history;
11745
11746 anyhow::Ok(())
11747 })??;
11748
11749 anyhow::Ok(())
11750 })
11751 .detach_and_log_err(cx);
11752 }
11753
11754 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11755 let snapshot = self.buffer.read(cx).read(cx);
11756 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11757 Some(
11758 ranges
11759 .iter()
11760 .map(move |range| {
11761 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11762 })
11763 .collect(),
11764 )
11765 }
11766
11767 fn selection_replacement_ranges(
11768 &self,
11769 range: Range<OffsetUtf16>,
11770 cx: &AppContext,
11771 ) -> Vec<Range<OffsetUtf16>> {
11772 let selections = self.selections.all::<OffsetUtf16>(cx);
11773 let newest_selection = selections
11774 .iter()
11775 .max_by_key(|selection| selection.id)
11776 .unwrap();
11777 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11778 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11779 let snapshot = self.buffer.read(cx).read(cx);
11780 selections
11781 .into_iter()
11782 .map(|mut selection| {
11783 selection.start.0 =
11784 (selection.start.0 as isize).saturating_add(start_delta) as usize;
11785 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11786 snapshot.clip_offset_utf16(selection.start, Bias::Left)
11787 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11788 })
11789 .collect()
11790 }
11791
11792 fn report_editor_event(
11793 &self,
11794 operation: &'static str,
11795 file_extension: Option<String>,
11796 cx: &AppContext,
11797 ) {
11798 if cfg!(any(test, feature = "test-support")) {
11799 return;
11800 }
11801
11802 let Some(project) = &self.project else { return };
11803
11804 // If None, we are in a file without an extension
11805 let file = self
11806 .buffer
11807 .read(cx)
11808 .as_singleton()
11809 .and_then(|b| b.read(cx).file());
11810 let file_extension = file_extension.or(file
11811 .as_ref()
11812 .and_then(|file| Path::new(file.file_name(cx)).extension())
11813 .and_then(|e| e.to_str())
11814 .map(|a| a.to_string()));
11815
11816 let vim_mode = cx
11817 .global::<SettingsStore>()
11818 .raw_user_settings()
11819 .get("vim_mode")
11820 == Some(&serde_json::Value::Bool(true));
11821
11822 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11823 == language::language_settings::InlineCompletionProvider::Copilot;
11824 let copilot_enabled_for_language = self
11825 .buffer
11826 .read(cx)
11827 .settings_at(0, cx)
11828 .show_inline_completions;
11829
11830 let telemetry = project.read(cx).client().telemetry().clone();
11831 telemetry.report_editor_event(
11832 file_extension,
11833 vim_mode,
11834 operation,
11835 copilot_enabled,
11836 copilot_enabled_for_language,
11837 )
11838 }
11839
11840 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11841 /// with each line being an array of {text, highlight} objects.
11842 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11843 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11844 return;
11845 };
11846
11847 #[derive(Serialize)]
11848 struct Chunk<'a> {
11849 text: String,
11850 highlight: Option<&'a str>,
11851 }
11852
11853 let snapshot = buffer.read(cx).snapshot();
11854 let range = self
11855 .selected_text_range(false, cx)
11856 .and_then(|selection| {
11857 if selection.range.is_empty() {
11858 None
11859 } else {
11860 Some(selection.range)
11861 }
11862 })
11863 .unwrap_or_else(|| 0..snapshot.len());
11864
11865 let chunks = snapshot.chunks(range, true);
11866 let mut lines = Vec::new();
11867 let mut line: VecDeque<Chunk> = VecDeque::new();
11868
11869 let Some(style) = self.style.as_ref() else {
11870 return;
11871 };
11872
11873 for chunk in chunks {
11874 let highlight = chunk
11875 .syntax_highlight_id
11876 .and_then(|id| id.name(&style.syntax));
11877 let mut chunk_lines = chunk.text.split('\n').peekable();
11878 while let Some(text) = chunk_lines.next() {
11879 let mut merged_with_last_token = false;
11880 if let Some(last_token) = line.back_mut() {
11881 if last_token.highlight == highlight {
11882 last_token.text.push_str(text);
11883 merged_with_last_token = true;
11884 }
11885 }
11886
11887 if !merged_with_last_token {
11888 line.push_back(Chunk {
11889 text: text.into(),
11890 highlight,
11891 });
11892 }
11893
11894 if chunk_lines.peek().is_some() {
11895 if line.len() > 1 && line.front().unwrap().text.is_empty() {
11896 line.pop_front();
11897 }
11898 if line.len() > 1 && line.back().unwrap().text.is_empty() {
11899 line.pop_back();
11900 }
11901
11902 lines.push(mem::take(&mut line));
11903 }
11904 }
11905 }
11906
11907 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11908 return;
11909 };
11910 cx.write_to_clipboard(ClipboardItem::new_string(lines));
11911 }
11912
11913 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11914 &self.inlay_hint_cache
11915 }
11916
11917 pub fn replay_insert_event(
11918 &mut self,
11919 text: &str,
11920 relative_utf16_range: Option<Range<isize>>,
11921 cx: &mut ViewContext<Self>,
11922 ) {
11923 if !self.input_enabled {
11924 cx.emit(EditorEvent::InputIgnored { text: text.into() });
11925 return;
11926 }
11927 if let Some(relative_utf16_range) = relative_utf16_range {
11928 let selections = self.selections.all::<OffsetUtf16>(cx);
11929 self.change_selections(None, cx, |s| {
11930 let new_ranges = selections.into_iter().map(|range| {
11931 let start = OffsetUtf16(
11932 range
11933 .head()
11934 .0
11935 .saturating_add_signed(relative_utf16_range.start),
11936 );
11937 let end = OffsetUtf16(
11938 range
11939 .head()
11940 .0
11941 .saturating_add_signed(relative_utf16_range.end),
11942 );
11943 start..end
11944 });
11945 s.select_ranges(new_ranges);
11946 });
11947 }
11948
11949 self.handle_input(text, cx);
11950 }
11951
11952 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11953 let Some(project) = self.project.as_ref() else {
11954 return false;
11955 };
11956 let project = project.read(cx);
11957
11958 let mut supports = false;
11959 self.buffer().read(cx).for_each_buffer(|buffer| {
11960 if !supports {
11961 supports = project
11962 .language_servers_for_buffer(buffer.read(cx), cx)
11963 .any(
11964 |(_, server)| match server.capabilities().inlay_hint_provider {
11965 Some(lsp::OneOf::Left(enabled)) => enabled,
11966 Some(lsp::OneOf::Right(_)) => true,
11967 None => false,
11968 },
11969 )
11970 }
11971 });
11972 supports
11973 }
11974
11975 pub fn focus(&self, cx: &mut WindowContext) {
11976 cx.focus(&self.focus_handle)
11977 }
11978
11979 pub fn is_focused(&self, cx: &WindowContext) -> bool {
11980 self.focus_handle.is_focused(cx)
11981 }
11982
11983 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11984 cx.emit(EditorEvent::Focused);
11985
11986 if let Some(descendant) = self
11987 .last_focused_descendant
11988 .take()
11989 .and_then(|descendant| descendant.upgrade())
11990 {
11991 cx.focus(&descendant);
11992 } else {
11993 if let Some(blame) = self.blame.as_ref() {
11994 blame.update(cx, GitBlame::focus)
11995 }
11996
11997 self.blink_manager.update(cx, BlinkManager::enable);
11998 self.show_cursor_names(cx);
11999 self.buffer.update(cx, |buffer, cx| {
12000 buffer.finalize_last_transaction(cx);
12001 if self.leader_peer_id.is_none() {
12002 buffer.set_active_selections(
12003 &self.selections.disjoint_anchors(),
12004 self.selections.line_mode,
12005 self.cursor_shape,
12006 cx,
12007 );
12008 }
12009 });
12010 }
12011 }
12012
12013 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12014 cx.emit(EditorEvent::FocusedIn)
12015 }
12016
12017 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12018 if event.blurred != self.focus_handle {
12019 self.last_focused_descendant = Some(event.blurred);
12020 }
12021 }
12022
12023 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12024 self.blink_manager.update(cx, BlinkManager::disable);
12025 self.buffer
12026 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12027
12028 if let Some(blame) = self.blame.as_ref() {
12029 blame.update(cx, GitBlame::blur)
12030 }
12031 if !self.hover_state.focused(cx) {
12032 hide_hover(self, cx);
12033 }
12034
12035 self.hide_context_menu(cx);
12036 cx.emit(EditorEvent::Blurred);
12037 cx.notify();
12038 }
12039
12040 pub fn register_action<A: Action>(
12041 &mut self,
12042 listener: impl Fn(&A, &mut WindowContext) + 'static,
12043 ) -> Subscription {
12044 let id = self.next_editor_action_id.post_inc();
12045 let listener = Arc::new(listener);
12046 self.editor_actions.borrow_mut().insert(
12047 id,
12048 Box::new(move |cx| {
12049 let cx = cx.window_context();
12050 let listener = listener.clone();
12051 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12052 let action = action.downcast_ref().unwrap();
12053 if phase == DispatchPhase::Bubble {
12054 listener(action, cx)
12055 }
12056 })
12057 }),
12058 );
12059
12060 let editor_actions = self.editor_actions.clone();
12061 Subscription::new(move || {
12062 editor_actions.borrow_mut().remove(&id);
12063 })
12064 }
12065
12066 pub fn file_header_size(&self) -> u32 {
12067 self.file_header_size
12068 }
12069
12070 pub fn revert(
12071 &mut self,
12072 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12073 cx: &mut ViewContext<Self>,
12074 ) {
12075 self.buffer().update(cx, |multi_buffer, cx| {
12076 for (buffer_id, changes) in revert_changes {
12077 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12078 buffer.update(cx, |buffer, cx| {
12079 buffer.edit(
12080 changes.into_iter().map(|(range, text)| {
12081 (range, text.to_string().map(Arc::<str>::from))
12082 }),
12083 None,
12084 cx,
12085 );
12086 });
12087 }
12088 }
12089 });
12090 self.change_selections(None, cx, |selections| selections.refresh());
12091 }
12092
12093 pub fn to_pixel_point(
12094 &mut self,
12095 source: multi_buffer::Anchor,
12096 editor_snapshot: &EditorSnapshot,
12097 cx: &mut ViewContext<Self>,
12098 ) -> Option<gpui::Point<Pixels>> {
12099 let source_point = source.to_display_point(editor_snapshot);
12100 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12101 }
12102
12103 pub fn display_to_pixel_point(
12104 &mut self,
12105 source: DisplayPoint,
12106 editor_snapshot: &EditorSnapshot,
12107 cx: &mut ViewContext<Self>,
12108 ) -> Option<gpui::Point<Pixels>> {
12109 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12110 let text_layout_details = self.text_layout_details(cx);
12111 let scroll_top = text_layout_details
12112 .scroll_anchor
12113 .scroll_position(editor_snapshot)
12114 .y;
12115
12116 if source.row().as_f32() < scroll_top.floor() {
12117 return None;
12118 }
12119 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12120 let source_y = line_height * (source.row().as_f32() - scroll_top);
12121 Some(gpui::Point::new(source_x, source_y))
12122 }
12123
12124 fn gutter_bounds(&self) -> Option<Bounds<Pixels>> {
12125 let bounds = self.last_bounds?;
12126 Some(element::gutter_bounds(bounds, self.gutter_dimensions))
12127 }
12128
12129 pub fn has_active_completions_menu(&self) -> bool {
12130 self.context_menu.read().as_ref().map_or(false, |menu| {
12131 menu.visible() && matches!(menu, ContextMenu::Completions(_))
12132 })
12133 }
12134
12135 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12136 self.addons
12137 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12138 }
12139
12140 pub fn unregister_addon<T: Addon>(&mut self) {
12141 self.addons.remove(&std::any::TypeId::of::<T>());
12142 }
12143
12144 pub fn addon<T: Addon>(&self) -> Option<&T> {
12145 let type_id = std::any::TypeId::of::<T>();
12146 self.addons
12147 .get(&type_id)
12148 .and_then(|item| item.to_any().downcast_ref::<T>())
12149 }
12150}
12151
12152fn hunks_for_selections(
12153 multi_buffer_snapshot: &MultiBufferSnapshot,
12154 selections: &[Selection<Anchor>],
12155) -> Vec<DiffHunk<MultiBufferRow>> {
12156 let buffer_rows_for_selections = selections.iter().map(|selection| {
12157 let head = selection.head();
12158 let tail = selection.tail();
12159 let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
12160 let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
12161 if start > end {
12162 end..start
12163 } else {
12164 start..end
12165 }
12166 });
12167
12168 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12169}
12170
12171pub fn hunks_for_rows(
12172 rows: impl Iterator<Item = Range<MultiBufferRow>>,
12173 multi_buffer_snapshot: &MultiBufferSnapshot,
12174) -> Vec<DiffHunk<MultiBufferRow>> {
12175 let mut hunks = Vec::new();
12176 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12177 HashMap::default();
12178 for selected_multi_buffer_rows in rows {
12179 let query_rows =
12180 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12181 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12182 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12183 // when the caret is just above or just below the deleted hunk.
12184 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12185 let related_to_selection = if allow_adjacent {
12186 hunk.associated_range.overlaps(&query_rows)
12187 || hunk.associated_range.start == query_rows.end
12188 || hunk.associated_range.end == query_rows.start
12189 } else {
12190 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12191 // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12192 hunk.associated_range.overlaps(&selected_multi_buffer_rows)
12193 || selected_multi_buffer_rows.end == hunk.associated_range.start
12194 };
12195 if related_to_selection {
12196 if !processed_buffer_rows
12197 .entry(hunk.buffer_id)
12198 .or_default()
12199 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12200 {
12201 continue;
12202 }
12203 hunks.push(hunk);
12204 }
12205 }
12206 }
12207
12208 hunks
12209}
12210
12211pub trait CollaborationHub {
12212 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12213 fn user_participant_indices<'a>(
12214 &self,
12215 cx: &'a AppContext,
12216 ) -> &'a HashMap<u64, ParticipantIndex>;
12217 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12218}
12219
12220impl CollaborationHub for Model<Project> {
12221 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12222 self.read(cx).collaborators()
12223 }
12224
12225 fn user_participant_indices<'a>(
12226 &self,
12227 cx: &'a AppContext,
12228 ) -> &'a HashMap<u64, ParticipantIndex> {
12229 self.read(cx).user_store().read(cx).participant_indices()
12230 }
12231
12232 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12233 let this = self.read(cx);
12234 let user_ids = this.collaborators().values().map(|c| c.user_id);
12235 this.user_store().read_with(cx, |user_store, cx| {
12236 user_store.participant_names(user_ids, cx)
12237 })
12238 }
12239}
12240
12241pub trait CompletionProvider {
12242 fn completions(
12243 &self,
12244 buffer: &Model<Buffer>,
12245 buffer_position: text::Anchor,
12246 trigger: CompletionContext,
12247 cx: &mut ViewContext<Editor>,
12248 ) -> Task<Result<Vec<Completion>>>;
12249
12250 fn resolve_completions(
12251 &self,
12252 buffer: Model<Buffer>,
12253 completion_indices: Vec<usize>,
12254 completions: Arc<RwLock<Box<[Completion]>>>,
12255 cx: &mut ViewContext<Editor>,
12256 ) -> Task<Result<bool>>;
12257
12258 fn apply_additional_edits_for_completion(
12259 &self,
12260 buffer: Model<Buffer>,
12261 completion: Completion,
12262 push_to_history: bool,
12263 cx: &mut ViewContext<Editor>,
12264 ) -> Task<Result<Option<language::Transaction>>>;
12265
12266 fn is_completion_trigger(
12267 &self,
12268 buffer: &Model<Buffer>,
12269 position: language::Anchor,
12270 text: &str,
12271 trigger_in_words: bool,
12272 cx: &mut ViewContext<Editor>,
12273 ) -> bool;
12274
12275 fn sort_completions(&self) -> bool {
12276 true
12277 }
12278}
12279
12280fn snippet_completions(
12281 project: &Project,
12282 buffer: &Model<Buffer>,
12283 buffer_position: text::Anchor,
12284 cx: &mut AppContext,
12285) -> Vec<Completion> {
12286 let language = buffer.read(cx).language_at(buffer_position);
12287 let language_name = language.as_ref().map(|language| language.lsp_id());
12288 let snippet_store = project.snippets().read(cx);
12289 let snippets = snippet_store.snippets_for(language_name, cx);
12290
12291 if snippets.is_empty() {
12292 return vec![];
12293 }
12294 let snapshot = buffer.read(cx).text_snapshot();
12295 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12296
12297 let mut lines = chunks.lines();
12298 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12299 return vec![];
12300 };
12301
12302 let scope = language.map(|language| language.default_scope());
12303 let classifier = CharClassifier::new(scope).for_completion(true);
12304 let mut last_word = line_at
12305 .chars()
12306 .rev()
12307 .take_while(|c| classifier.is_word(*c))
12308 .collect::<String>();
12309 last_word = last_word.chars().rev().collect();
12310 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12311 let to_lsp = |point: &text::Anchor| {
12312 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12313 point_to_lsp(end)
12314 };
12315 let lsp_end = to_lsp(&buffer_position);
12316 snippets
12317 .into_iter()
12318 .filter_map(|snippet| {
12319 let matching_prefix = snippet
12320 .prefix
12321 .iter()
12322 .find(|prefix| prefix.starts_with(&last_word))?;
12323 let start = as_offset - last_word.len();
12324 let start = snapshot.anchor_before(start);
12325 let range = start..buffer_position;
12326 let lsp_start = to_lsp(&start);
12327 let lsp_range = lsp::Range {
12328 start: lsp_start,
12329 end: lsp_end,
12330 };
12331 Some(Completion {
12332 old_range: range,
12333 new_text: snippet.body.clone(),
12334 label: CodeLabel {
12335 text: matching_prefix.clone(),
12336 runs: vec![],
12337 filter_range: 0..matching_prefix.len(),
12338 },
12339 server_id: LanguageServerId(usize::MAX),
12340 documentation: snippet
12341 .description
12342 .clone()
12343 .map(|description| Documentation::SingleLine(description)),
12344 lsp_completion: lsp::CompletionItem {
12345 label: snippet.prefix.first().unwrap().clone(),
12346 kind: Some(CompletionItemKind::SNIPPET),
12347 label_details: snippet.description.as_ref().map(|description| {
12348 lsp::CompletionItemLabelDetails {
12349 detail: Some(description.clone()),
12350 description: None,
12351 }
12352 }),
12353 insert_text_format: Some(InsertTextFormat::SNIPPET),
12354 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12355 lsp::InsertReplaceEdit {
12356 new_text: snippet.body.clone(),
12357 insert: lsp_range,
12358 replace: lsp_range,
12359 },
12360 )),
12361 filter_text: Some(snippet.body.clone()),
12362 sort_text: Some(char::MAX.to_string()),
12363 ..Default::default()
12364 },
12365 confirm: None,
12366 })
12367 })
12368 .collect()
12369}
12370
12371impl CompletionProvider for Model<Project> {
12372 fn completions(
12373 &self,
12374 buffer: &Model<Buffer>,
12375 buffer_position: text::Anchor,
12376 options: CompletionContext,
12377 cx: &mut ViewContext<Editor>,
12378 ) -> Task<Result<Vec<Completion>>> {
12379 self.update(cx, |project, cx| {
12380 let snippets = snippet_completions(project, buffer, buffer_position, cx);
12381 let project_completions = project.completions(&buffer, buffer_position, options, cx);
12382 cx.background_executor().spawn(async move {
12383 let mut completions = project_completions.await?;
12384 //let snippets = snippets.into_iter().;
12385 completions.extend(snippets);
12386 Ok(completions)
12387 })
12388 })
12389 }
12390
12391 fn resolve_completions(
12392 &self,
12393 buffer: Model<Buffer>,
12394 completion_indices: Vec<usize>,
12395 completions: Arc<RwLock<Box<[Completion]>>>,
12396 cx: &mut ViewContext<Editor>,
12397 ) -> Task<Result<bool>> {
12398 self.update(cx, |project, cx| {
12399 project.resolve_completions(buffer, completion_indices, completions, cx)
12400 })
12401 }
12402
12403 fn apply_additional_edits_for_completion(
12404 &self,
12405 buffer: Model<Buffer>,
12406 completion: Completion,
12407 push_to_history: bool,
12408 cx: &mut ViewContext<Editor>,
12409 ) -> Task<Result<Option<language::Transaction>>> {
12410 self.update(cx, |project, cx| {
12411 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12412 })
12413 }
12414
12415 fn is_completion_trigger(
12416 &self,
12417 buffer: &Model<Buffer>,
12418 position: language::Anchor,
12419 text: &str,
12420 trigger_in_words: bool,
12421 cx: &mut ViewContext<Editor>,
12422 ) -> bool {
12423 if !EditorSettings::get_global(cx).show_completions_on_input {
12424 return false;
12425 }
12426
12427 let mut chars = text.chars();
12428 let char = if let Some(char) = chars.next() {
12429 char
12430 } else {
12431 return false;
12432 };
12433 if chars.next().is_some() {
12434 return false;
12435 }
12436
12437 let buffer = buffer.read(cx);
12438 let classifier = buffer
12439 .snapshot()
12440 .char_classifier_at(position)
12441 .for_completion(true);
12442 if trigger_in_words && classifier.is_word(char) {
12443 return true;
12444 }
12445
12446 buffer
12447 .completion_triggers()
12448 .iter()
12449 .any(|string| string == text)
12450 }
12451}
12452
12453fn inlay_hint_settings(
12454 location: Anchor,
12455 snapshot: &MultiBufferSnapshot,
12456 cx: &mut ViewContext<'_, Editor>,
12457) -> InlayHintSettings {
12458 let file = snapshot.file_at(location);
12459 let language = snapshot.language_at(location);
12460 let settings = all_language_settings(file, cx);
12461 settings
12462 .language(language.map(|l| l.name()).as_deref())
12463 .inlay_hints
12464}
12465
12466fn consume_contiguous_rows(
12467 contiguous_row_selections: &mut Vec<Selection<Point>>,
12468 selection: &Selection<Point>,
12469 display_map: &DisplaySnapshot,
12470 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12471) -> (MultiBufferRow, MultiBufferRow) {
12472 contiguous_row_selections.push(selection.clone());
12473 let start_row = MultiBufferRow(selection.start.row);
12474 let mut end_row = ending_row(selection, display_map);
12475
12476 while let Some(next_selection) = selections.peek() {
12477 if next_selection.start.row <= end_row.0 {
12478 end_row = ending_row(next_selection, display_map);
12479 contiguous_row_selections.push(selections.next().unwrap().clone());
12480 } else {
12481 break;
12482 }
12483 }
12484 (start_row, end_row)
12485}
12486
12487fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12488 if next_selection.end.column > 0 || next_selection.is_empty() {
12489 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12490 } else {
12491 MultiBufferRow(next_selection.end.row)
12492 }
12493}
12494
12495impl EditorSnapshot {
12496 pub fn remote_selections_in_range<'a>(
12497 &'a self,
12498 range: &'a Range<Anchor>,
12499 collaboration_hub: &dyn CollaborationHub,
12500 cx: &'a AppContext,
12501 ) -> impl 'a + Iterator<Item = RemoteSelection> {
12502 let participant_names = collaboration_hub.user_names(cx);
12503 let participant_indices = collaboration_hub.user_participant_indices(cx);
12504 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12505 let collaborators_by_replica_id = collaborators_by_peer_id
12506 .iter()
12507 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12508 .collect::<HashMap<_, _>>();
12509 self.buffer_snapshot
12510 .selections_in_range(range, false)
12511 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12512 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12513 let participant_index = participant_indices.get(&collaborator.user_id).copied();
12514 let user_name = participant_names.get(&collaborator.user_id).cloned();
12515 Some(RemoteSelection {
12516 replica_id,
12517 selection,
12518 cursor_shape,
12519 line_mode,
12520 participant_index,
12521 peer_id: collaborator.peer_id,
12522 user_name,
12523 })
12524 })
12525 }
12526
12527 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12528 self.display_snapshot.buffer_snapshot.language_at(position)
12529 }
12530
12531 pub fn is_focused(&self) -> bool {
12532 self.is_focused
12533 }
12534
12535 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12536 self.placeholder_text.as_ref()
12537 }
12538
12539 pub fn scroll_position(&self) -> gpui::Point<f32> {
12540 self.scroll_anchor.scroll_position(&self.display_snapshot)
12541 }
12542
12543 fn gutter_dimensions(
12544 &self,
12545 font_id: FontId,
12546 font_size: Pixels,
12547 em_width: Pixels,
12548 max_line_number_width: Pixels,
12549 cx: &AppContext,
12550 ) -> GutterDimensions {
12551 if !self.show_gutter {
12552 return GutterDimensions::default();
12553 }
12554 let descent = cx.text_system().descent(font_id, font_size);
12555
12556 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12557 matches!(
12558 ProjectSettings::get_global(cx).git.git_gutter,
12559 Some(GitGutterSetting::TrackedFiles)
12560 )
12561 });
12562 let gutter_settings = EditorSettings::get_global(cx).gutter;
12563 let show_line_numbers = self
12564 .show_line_numbers
12565 .unwrap_or(gutter_settings.line_numbers);
12566 let line_gutter_width = if show_line_numbers {
12567 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12568 let min_width_for_number_on_gutter = em_width * 4.0;
12569 max_line_number_width.max(min_width_for_number_on_gutter)
12570 } else {
12571 0.0.into()
12572 };
12573
12574 let show_code_actions = self
12575 .show_code_actions
12576 .unwrap_or(gutter_settings.code_actions);
12577
12578 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12579
12580 let git_blame_entries_width = self
12581 .render_git_blame_gutter
12582 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12583
12584 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12585 left_padding += if show_code_actions || show_runnables {
12586 em_width * 3.0
12587 } else if show_git_gutter && show_line_numbers {
12588 em_width * 2.0
12589 } else if show_git_gutter || show_line_numbers {
12590 em_width
12591 } else {
12592 px(0.)
12593 };
12594
12595 let right_padding = if gutter_settings.folds && show_line_numbers {
12596 em_width * 4.0
12597 } else if gutter_settings.folds {
12598 em_width * 3.0
12599 } else if show_line_numbers {
12600 em_width
12601 } else {
12602 px(0.)
12603 };
12604
12605 GutterDimensions {
12606 left_padding,
12607 right_padding,
12608 width: line_gutter_width + left_padding + right_padding,
12609 margin: -descent,
12610 git_blame_entries_width,
12611 }
12612 }
12613
12614 pub fn render_fold_toggle(
12615 &self,
12616 buffer_row: MultiBufferRow,
12617 row_contains_cursor: bool,
12618 editor: View<Editor>,
12619 cx: &mut WindowContext,
12620 ) -> Option<AnyElement> {
12621 let folded = self.is_line_folded(buffer_row);
12622
12623 if let Some(crease) = self
12624 .crease_snapshot
12625 .query_row(buffer_row, &self.buffer_snapshot)
12626 {
12627 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12628 if folded {
12629 editor.update(cx, |editor, cx| {
12630 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12631 });
12632 } else {
12633 editor.update(cx, |editor, cx| {
12634 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12635 });
12636 }
12637 });
12638
12639 Some((crease.render_toggle)(
12640 buffer_row,
12641 folded,
12642 toggle_callback,
12643 cx,
12644 ))
12645 } else if folded
12646 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12647 {
12648 Some(
12649 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12650 .selected(folded)
12651 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12652 if folded {
12653 this.unfold_at(&UnfoldAt { buffer_row }, cx);
12654 } else {
12655 this.fold_at(&FoldAt { buffer_row }, cx);
12656 }
12657 }))
12658 .into_any_element(),
12659 )
12660 } else {
12661 None
12662 }
12663 }
12664
12665 pub fn render_crease_trailer(
12666 &self,
12667 buffer_row: MultiBufferRow,
12668 cx: &mut WindowContext,
12669 ) -> Option<AnyElement> {
12670 let folded = self.is_line_folded(buffer_row);
12671 let crease = self
12672 .crease_snapshot
12673 .query_row(buffer_row, &self.buffer_snapshot)?;
12674 Some((crease.render_trailer)(buffer_row, folded, cx))
12675 }
12676}
12677
12678impl Deref for EditorSnapshot {
12679 type Target = DisplaySnapshot;
12680
12681 fn deref(&self) -> &Self::Target {
12682 &self.display_snapshot
12683 }
12684}
12685
12686#[derive(Clone, Debug, PartialEq, Eq)]
12687pub enum EditorEvent {
12688 InputIgnored {
12689 text: Arc<str>,
12690 },
12691 InputHandled {
12692 utf16_range_to_replace: Option<Range<isize>>,
12693 text: Arc<str>,
12694 },
12695 ExcerptsAdded {
12696 buffer: Model<Buffer>,
12697 predecessor: ExcerptId,
12698 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12699 },
12700 ExcerptsRemoved {
12701 ids: Vec<ExcerptId>,
12702 },
12703 ExcerptsEdited {
12704 ids: Vec<ExcerptId>,
12705 },
12706 ExcerptsExpanded {
12707 ids: Vec<ExcerptId>,
12708 },
12709 BufferEdited,
12710 Edited {
12711 transaction_id: clock::Lamport,
12712 },
12713 Reparsed(BufferId),
12714 Focused,
12715 FocusedIn,
12716 Blurred,
12717 DirtyChanged,
12718 Saved,
12719 TitleChanged,
12720 DiffBaseChanged,
12721 SelectionsChanged {
12722 local: bool,
12723 },
12724 ScrollPositionChanged {
12725 local: bool,
12726 autoscroll: bool,
12727 },
12728 Closed,
12729 TransactionUndone {
12730 transaction_id: clock::Lamport,
12731 },
12732 TransactionBegun {
12733 transaction_id: clock::Lamport,
12734 },
12735}
12736
12737impl EventEmitter<EditorEvent> for Editor {}
12738
12739impl FocusableView for Editor {
12740 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12741 self.focus_handle.clone()
12742 }
12743}
12744
12745impl Render for Editor {
12746 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12747 let settings = ThemeSettings::get_global(cx);
12748
12749 let text_style = match self.mode {
12750 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12751 color: cx.theme().colors().editor_foreground,
12752 font_family: settings.ui_font.family.clone(),
12753 font_features: settings.ui_font.features.clone(),
12754 font_fallbacks: settings.ui_font.fallbacks.clone(),
12755 font_size: rems(0.875).into(),
12756 font_weight: settings.ui_font.weight,
12757 line_height: relative(settings.buffer_line_height.value()),
12758 ..Default::default()
12759 },
12760 EditorMode::Full => TextStyle {
12761 color: cx.theme().colors().editor_foreground,
12762 font_family: settings.buffer_font.family.clone(),
12763 font_features: settings.buffer_font.features.clone(),
12764 font_fallbacks: settings.buffer_font.fallbacks.clone(),
12765 font_size: settings.buffer_font_size(cx).into(),
12766 font_weight: settings.buffer_font.weight,
12767 line_height: relative(settings.buffer_line_height.value()),
12768 ..Default::default()
12769 },
12770 };
12771
12772 let background = match self.mode {
12773 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12774 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12775 EditorMode::Full => cx.theme().colors().editor_background,
12776 };
12777
12778 EditorElement::new(
12779 cx.view(),
12780 EditorStyle {
12781 background,
12782 local_player: cx.theme().players().local(),
12783 text: text_style,
12784 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12785 syntax: cx.theme().syntax().clone(),
12786 status: cx.theme().status().clone(),
12787 inlay_hints_style: HighlightStyle {
12788 color: Some(cx.theme().status().hint),
12789 ..HighlightStyle::default()
12790 },
12791 suggestions_style: HighlightStyle {
12792 color: Some(cx.theme().status().predictive),
12793 ..HighlightStyle::default()
12794 },
12795 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
12796 },
12797 )
12798 }
12799}
12800
12801impl ViewInputHandler for Editor {
12802 fn text_for_range(
12803 &mut self,
12804 range_utf16: Range<usize>,
12805 cx: &mut ViewContext<Self>,
12806 ) -> Option<String> {
12807 Some(
12808 self.buffer
12809 .read(cx)
12810 .read(cx)
12811 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12812 .collect(),
12813 )
12814 }
12815
12816 fn selected_text_range(
12817 &mut self,
12818 ignore_disabled_input: bool,
12819 cx: &mut ViewContext<Self>,
12820 ) -> Option<UTF16Selection> {
12821 // Prevent the IME menu from appearing when holding down an alphabetic key
12822 // while input is disabled.
12823 if !ignore_disabled_input && !self.input_enabled {
12824 return None;
12825 }
12826
12827 let selection = self.selections.newest::<OffsetUtf16>(cx);
12828 let range = selection.range();
12829
12830 Some(UTF16Selection {
12831 range: range.start.0..range.end.0,
12832 reversed: selection.reversed,
12833 })
12834 }
12835
12836 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12837 let snapshot = self.buffer.read(cx).read(cx);
12838 let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
12839 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12840 }
12841
12842 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12843 self.clear_highlights::<InputComposition>(cx);
12844 self.ime_transaction.take();
12845 }
12846
12847 fn replace_text_in_range(
12848 &mut self,
12849 range_utf16: Option<Range<usize>>,
12850 text: &str,
12851 cx: &mut ViewContext<Self>,
12852 ) {
12853 if !self.input_enabled {
12854 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12855 return;
12856 }
12857
12858 self.transact(cx, |this, cx| {
12859 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12860 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12861 Some(this.selection_replacement_ranges(range_utf16, cx))
12862 } else {
12863 this.marked_text_ranges(cx)
12864 };
12865
12866 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12867 let newest_selection_id = this.selections.newest_anchor().id;
12868 this.selections
12869 .all::<OffsetUtf16>(cx)
12870 .iter()
12871 .zip(ranges_to_replace.iter())
12872 .find_map(|(selection, range)| {
12873 if selection.id == newest_selection_id {
12874 Some(
12875 (range.start.0 as isize - selection.head().0 as isize)
12876 ..(range.end.0 as isize - selection.head().0 as isize),
12877 )
12878 } else {
12879 None
12880 }
12881 })
12882 });
12883
12884 cx.emit(EditorEvent::InputHandled {
12885 utf16_range_to_replace: range_to_replace,
12886 text: text.into(),
12887 });
12888
12889 if let Some(new_selected_ranges) = new_selected_ranges {
12890 this.change_selections(None, cx, |selections| {
12891 selections.select_ranges(new_selected_ranges)
12892 });
12893 this.backspace(&Default::default(), cx);
12894 }
12895
12896 this.handle_input(text, cx);
12897 });
12898
12899 if let Some(transaction) = self.ime_transaction {
12900 self.buffer.update(cx, |buffer, cx| {
12901 buffer.group_until_transaction(transaction, cx);
12902 });
12903 }
12904
12905 self.unmark_text(cx);
12906 }
12907
12908 fn replace_and_mark_text_in_range(
12909 &mut self,
12910 range_utf16: Option<Range<usize>>,
12911 text: &str,
12912 new_selected_range_utf16: Option<Range<usize>>,
12913 cx: &mut ViewContext<Self>,
12914 ) {
12915 if !self.input_enabled {
12916 return;
12917 }
12918
12919 let transaction = self.transact(cx, |this, cx| {
12920 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12921 let snapshot = this.buffer.read(cx).read(cx);
12922 if let Some(relative_range_utf16) = range_utf16.as_ref() {
12923 for marked_range in &mut marked_ranges {
12924 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12925 marked_range.start.0 += relative_range_utf16.start;
12926 marked_range.start =
12927 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12928 marked_range.end =
12929 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12930 }
12931 }
12932 Some(marked_ranges)
12933 } else if let Some(range_utf16) = range_utf16 {
12934 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12935 Some(this.selection_replacement_ranges(range_utf16, cx))
12936 } else {
12937 None
12938 };
12939
12940 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12941 let newest_selection_id = this.selections.newest_anchor().id;
12942 this.selections
12943 .all::<OffsetUtf16>(cx)
12944 .iter()
12945 .zip(ranges_to_replace.iter())
12946 .find_map(|(selection, range)| {
12947 if selection.id == newest_selection_id {
12948 Some(
12949 (range.start.0 as isize - selection.head().0 as isize)
12950 ..(range.end.0 as isize - selection.head().0 as isize),
12951 )
12952 } else {
12953 None
12954 }
12955 })
12956 });
12957
12958 cx.emit(EditorEvent::InputHandled {
12959 utf16_range_to_replace: range_to_replace,
12960 text: text.into(),
12961 });
12962
12963 if let Some(ranges) = ranges_to_replace {
12964 this.change_selections(None, cx, |s| s.select_ranges(ranges));
12965 }
12966
12967 let marked_ranges = {
12968 let snapshot = this.buffer.read(cx).read(cx);
12969 this.selections
12970 .disjoint_anchors()
12971 .iter()
12972 .map(|selection| {
12973 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12974 })
12975 .collect::<Vec<_>>()
12976 };
12977
12978 if text.is_empty() {
12979 this.unmark_text(cx);
12980 } else {
12981 this.highlight_text::<InputComposition>(
12982 marked_ranges.clone(),
12983 HighlightStyle {
12984 underline: Some(UnderlineStyle {
12985 thickness: px(1.),
12986 color: None,
12987 wavy: false,
12988 }),
12989 ..Default::default()
12990 },
12991 cx,
12992 );
12993 }
12994
12995 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12996 let use_autoclose = this.use_autoclose;
12997 let use_auto_surround = this.use_auto_surround;
12998 this.set_use_autoclose(false);
12999 this.set_use_auto_surround(false);
13000 this.handle_input(text, cx);
13001 this.set_use_autoclose(use_autoclose);
13002 this.set_use_auto_surround(use_auto_surround);
13003
13004 if let Some(new_selected_range) = new_selected_range_utf16 {
13005 let snapshot = this.buffer.read(cx).read(cx);
13006 let new_selected_ranges = marked_ranges
13007 .into_iter()
13008 .map(|marked_range| {
13009 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13010 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13011 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13012 snapshot.clip_offset_utf16(new_start, Bias::Left)
13013 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13014 })
13015 .collect::<Vec<_>>();
13016
13017 drop(snapshot);
13018 this.change_selections(None, cx, |selections| {
13019 selections.select_ranges(new_selected_ranges)
13020 });
13021 }
13022 });
13023
13024 self.ime_transaction = self.ime_transaction.or(transaction);
13025 if let Some(transaction) = self.ime_transaction {
13026 self.buffer.update(cx, |buffer, cx| {
13027 buffer.group_until_transaction(transaction, cx);
13028 });
13029 }
13030
13031 if self.text_highlights::<InputComposition>(cx).is_none() {
13032 self.ime_transaction.take();
13033 }
13034 }
13035
13036 fn bounds_for_range(
13037 &mut self,
13038 range_utf16: Range<usize>,
13039 element_bounds: gpui::Bounds<Pixels>,
13040 cx: &mut ViewContext<Self>,
13041 ) -> Option<gpui::Bounds<Pixels>> {
13042 let text_layout_details = self.text_layout_details(cx);
13043 let style = &text_layout_details.editor_style;
13044 let font_id = cx.text_system().resolve_font(&style.text.font());
13045 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13046 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13047
13048 let em_width = cx
13049 .text_system()
13050 .typographic_bounds(font_id, font_size, 'm')
13051 .unwrap()
13052 .size
13053 .width;
13054
13055 let snapshot = self.snapshot(cx);
13056 let scroll_position = snapshot.scroll_position();
13057 let scroll_left = scroll_position.x * em_width;
13058
13059 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13060 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13061 + self.gutter_dimensions.width;
13062 let y = line_height * (start.row().as_f32() - scroll_position.y);
13063
13064 Some(Bounds {
13065 origin: element_bounds.origin + point(x, y),
13066 size: size(em_width, line_height),
13067 })
13068 }
13069}
13070
13071trait SelectionExt {
13072 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13073 fn spanned_rows(
13074 &self,
13075 include_end_if_at_line_start: bool,
13076 map: &DisplaySnapshot,
13077 ) -> Range<MultiBufferRow>;
13078}
13079
13080impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
13081 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
13082 let start = self
13083 .start
13084 .to_point(&map.buffer_snapshot)
13085 .to_display_point(map);
13086 let end = self
13087 .end
13088 .to_point(&map.buffer_snapshot)
13089 .to_display_point(map);
13090 if self.reversed {
13091 end..start
13092 } else {
13093 start..end
13094 }
13095 }
13096
13097 fn spanned_rows(
13098 &self,
13099 include_end_if_at_line_start: bool,
13100 map: &DisplaySnapshot,
13101 ) -> Range<MultiBufferRow> {
13102 let start = self.start.to_point(&map.buffer_snapshot);
13103 let mut end = self.end.to_point(&map.buffer_snapshot);
13104 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
13105 end.row -= 1;
13106 }
13107
13108 let buffer_start = map.prev_line_boundary(start).0;
13109 let buffer_end = map.next_line_boundary(end).0;
13110 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
13111 }
13112}
13113
13114impl<T: InvalidationRegion> InvalidationStack<T> {
13115 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
13116 where
13117 S: Clone + ToOffset,
13118 {
13119 while let Some(region) = self.last() {
13120 let all_selections_inside_invalidation_ranges =
13121 if selections.len() == region.ranges().len() {
13122 selections
13123 .iter()
13124 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
13125 .all(|(selection, invalidation_range)| {
13126 let head = selection.head().to_offset(buffer);
13127 invalidation_range.start <= head && invalidation_range.end >= head
13128 })
13129 } else {
13130 false
13131 };
13132
13133 if all_selections_inside_invalidation_ranges {
13134 break;
13135 } else {
13136 self.pop();
13137 }
13138 }
13139 }
13140}
13141
13142impl<T> Default for InvalidationStack<T> {
13143 fn default() -> Self {
13144 Self(Default::default())
13145 }
13146}
13147
13148impl<T> Deref for InvalidationStack<T> {
13149 type Target = Vec<T>;
13150
13151 fn deref(&self) -> &Self::Target {
13152 &self.0
13153 }
13154}
13155
13156impl<T> DerefMut for InvalidationStack<T> {
13157 fn deref_mut(&mut self) -> &mut Self::Target {
13158 &mut self.0
13159 }
13160}
13161
13162impl InvalidationRegion for SnippetState {
13163 fn ranges(&self) -> &[Range<Anchor>] {
13164 &self.ranges[self.active_index]
13165 }
13166}
13167
13168pub fn diagnostic_block_renderer(
13169 diagnostic: Diagnostic,
13170 max_message_rows: Option<u8>,
13171 allow_closing: bool,
13172 _is_valid: bool,
13173) -> RenderBlock {
13174 let (text_without_backticks, code_ranges) =
13175 highlight_diagnostic_message(&diagnostic, max_message_rows);
13176
13177 Box::new(move |cx: &mut BlockContext| {
13178 let group_id: SharedString = cx.block_id.to_string().into();
13179
13180 let mut text_style = cx.text_style().clone();
13181 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13182 let theme_settings = ThemeSettings::get_global(cx);
13183 text_style.font_family = theme_settings.buffer_font.family.clone();
13184 text_style.font_style = theme_settings.buffer_font.style;
13185 text_style.font_features = theme_settings.buffer_font.features.clone();
13186 text_style.font_weight = theme_settings.buffer_font.weight;
13187
13188 let multi_line_diagnostic = diagnostic.message.contains('\n');
13189
13190 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13191 if multi_line_diagnostic {
13192 v_flex()
13193 } else {
13194 h_flex()
13195 }
13196 .when(allow_closing, |div| {
13197 div.children(diagnostic.is_primary.then(|| {
13198 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13199 .icon_color(Color::Muted)
13200 .size(ButtonSize::Compact)
13201 .style(ButtonStyle::Transparent)
13202 .visible_on_hover(group_id.clone())
13203 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13204 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13205 }))
13206 })
13207 .child(
13208 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13209 .icon_color(Color::Muted)
13210 .size(ButtonSize::Compact)
13211 .style(ButtonStyle::Transparent)
13212 .visible_on_hover(group_id.clone())
13213 .on_click({
13214 let message = diagnostic.message.clone();
13215 move |_click, cx| {
13216 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13217 }
13218 })
13219 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13220 )
13221 };
13222
13223 let icon_size = buttons(&diagnostic, cx.block_id)
13224 .into_any_element()
13225 .layout_as_root(AvailableSpace::min_size(), cx);
13226
13227 h_flex()
13228 .id(cx.block_id)
13229 .group(group_id.clone())
13230 .relative()
13231 .size_full()
13232 .pl(cx.gutter_dimensions.width)
13233 .w(cx.max_width + cx.gutter_dimensions.width)
13234 .child(
13235 div()
13236 .flex()
13237 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13238 .flex_shrink(),
13239 )
13240 .child(buttons(&diagnostic, cx.block_id))
13241 .child(div().flex().flex_shrink_0().child(
13242 StyledText::new(text_without_backticks.clone()).with_highlights(
13243 &text_style,
13244 code_ranges.iter().map(|range| {
13245 (
13246 range.clone(),
13247 HighlightStyle {
13248 font_weight: Some(FontWeight::BOLD),
13249 ..Default::default()
13250 },
13251 )
13252 }),
13253 ),
13254 ))
13255 .into_any_element()
13256 })
13257}
13258
13259pub fn highlight_diagnostic_message(
13260 diagnostic: &Diagnostic,
13261 mut max_message_rows: Option<u8>,
13262) -> (SharedString, Vec<Range<usize>>) {
13263 let mut text_without_backticks = String::new();
13264 let mut code_ranges = Vec::new();
13265
13266 if let Some(source) = &diagnostic.source {
13267 text_without_backticks.push_str(&source);
13268 code_ranges.push(0..source.len());
13269 text_without_backticks.push_str(": ");
13270 }
13271
13272 let mut prev_offset = 0;
13273 let mut in_code_block = false;
13274 let has_row_limit = max_message_rows.is_some();
13275 let mut newline_indices = diagnostic
13276 .message
13277 .match_indices('\n')
13278 .filter(|_| has_row_limit)
13279 .map(|(ix, _)| ix)
13280 .fuse()
13281 .peekable();
13282
13283 for (quote_ix, _) in diagnostic
13284 .message
13285 .match_indices('`')
13286 .chain([(diagnostic.message.len(), "")])
13287 {
13288 let mut first_newline_ix = None;
13289 let mut last_newline_ix = None;
13290 while let Some(newline_ix) = newline_indices.peek() {
13291 if *newline_ix < quote_ix {
13292 if first_newline_ix.is_none() {
13293 first_newline_ix = Some(*newline_ix);
13294 }
13295 last_newline_ix = Some(*newline_ix);
13296
13297 if let Some(rows_left) = &mut max_message_rows {
13298 if *rows_left == 0 {
13299 break;
13300 } else {
13301 *rows_left -= 1;
13302 }
13303 }
13304 let _ = newline_indices.next();
13305 } else {
13306 break;
13307 }
13308 }
13309 let prev_len = text_without_backticks.len();
13310 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
13311 text_without_backticks.push_str(new_text);
13312 if in_code_block {
13313 code_ranges.push(prev_len..text_without_backticks.len());
13314 }
13315 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13316 in_code_block = !in_code_block;
13317 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13318 text_without_backticks.push_str("...");
13319 break;
13320 }
13321 }
13322
13323 (text_without_backticks.into(), code_ranges)
13324}
13325
13326fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13327 match severity {
13328 DiagnosticSeverity::ERROR => colors.error,
13329 DiagnosticSeverity::WARNING => colors.warning,
13330 DiagnosticSeverity::INFORMATION => colors.info,
13331 DiagnosticSeverity::HINT => colors.info,
13332 _ => colors.ignored,
13333 }
13334}
13335
13336pub fn styled_runs_for_code_label<'a>(
13337 label: &'a CodeLabel,
13338 syntax_theme: &'a theme::SyntaxTheme,
13339) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13340 let fade_out = HighlightStyle {
13341 fade_out: Some(0.35),
13342 ..Default::default()
13343 };
13344
13345 let mut prev_end = label.filter_range.end;
13346 label
13347 .runs
13348 .iter()
13349 .enumerate()
13350 .flat_map(move |(ix, (range, highlight_id))| {
13351 let style = if let Some(style) = highlight_id.style(syntax_theme) {
13352 style
13353 } else {
13354 return Default::default();
13355 };
13356 let mut muted_style = style;
13357 muted_style.highlight(fade_out);
13358
13359 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13360 if range.start >= label.filter_range.end {
13361 if range.start > prev_end {
13362 runs.push((prev_end..range.start, fade_out));
13363 }
13364 runs.push((range.clone(), muted_style));
13365 } else if range.end <= label.filter_range.end {
13366 runs.push((range.clone(), style));
13367 } else {
13368 runs.push((range.start..label.filter_range.end, style));
13369 runs.push((label.filter_range.end..range.end, muted_style));
13370 }
13371 prev_end = cmp::max(prev_end, range.end);
13372
13373 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13374 runs.push((prev_end..label.text.len(), fade_out));
13375 }
13376
13377 runs
13378 })
13379}
13380
13381pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13382 let mut prev_index = 0;
13383 let mut prev_codepoint: Option<char> = None;
13384 text.char_indices()
13385 .chain([(text.len(), '\0')])
13386 .filter_map(move |(index, codepoint)| {
13387 let prev_codepoint = prev_codepoint.replace(codepoint)?;
13388 let is_boundary = index == text.len()
13389 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13390 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13391 if is_boundary {
13392 let chunk = &text[prev_index..index];
13393 prev_index = index;
13394 Some(chunk)
13395 } else {
13396 None
13397 }
13398 })
13399}
13400
13401pub trait RangeToAnchorExt: Sized {
13402 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13403
13404 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13405 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13406 anchor_range.start.to_display_point(&snapshot)..anchor_range.end.to_display_point(&snapshot)
13407 }
13408}
13409
13410impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13411 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13412 let start_offset = self.start.to_offset(snapshot);
13413 let end_offset = self.end.to_offset(snapshot);
13414 if start_offset == end_offset {
13415 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13416 } else {
13417 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13418 }
13419 }
13420}
13421
13422pub trait RowExt {
13423 fn as_f32(&self) -> f32;
13424
13425 fn next_row(&self) -> Self;
13426
13427 fn previous_row(&self) -> Self;
13428
13429 fn minus(&self, other: Self) -> u32;
13430}
13431
13432impl RowExt for DisplayRow {
13433 fn as_f32(&self) -> f32 {
13434 self.0 as f32
13435 }
13436
13437 fn next_row(&self) -> Self {
13438 Self(self.0 + 1)
13439 }
13440
13441 fn previous_row(&self) -> Self {
13442 Self(self.0.saturating_sub(1))
13443 }
13444
13445 fn minus(&self, other: Self) -> u32 {
13446 self.0 - other.0
13447 }
13448}
13449
13450impl RowExt for MultiBufferRow {
13451 fn as_f32(&self) -> f32 {
13452 self.0 as f32
13453 }
13454
13455 fn next_row(&self) -> Self {
13456 Self(self.0 + 1)
13457 }
13458
13459 fn previous_row(&self) -> Self {
13460 Self(self.0.saturating_sub(1))
13461 }
13462
13463 fn minus(&self, other: Self) -> u32 {
13464 self.0 - other.0
13465 }
13466}
13467
13468trait RowRangeExt {
13469 type Row;
13470
13471 fn len(&self) -> usize;
13472
13473 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13474}
13475
13476impl RowRangeExt for Range<MultiBufferRow> {
13477 type Row = MultiBufferRow;
13478
13479 fn len(&self) -> usize {
13480 (self.end.0 - self.start.0) as usize
13481 }
13482
13483 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13484 (self.start.0..self.end.0).map(MultiBufferRow)
13485 }
13486}
13487
13488impl RowRangeExt for Range<DisplayRow> {
13489 type Row = DisplayRow;
13490
13491 fn len(&self) -> usize {
13492 (self.end.0 - self.start.0) as usize
13493 }
13494
13495 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13496 (self.start.0..self.end.0).map(DisplayRow)
13497 }
13498}
13499
13500fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13501 if hunk.diff_base_byte_range.is_empty() {
13502 DiffHunkStatus::Added
13503 } else if hunk.associated_range.is_empty() {
13504 DiffHunkStatus::Removed
13505 } else {
13506 DiffHunkStatus::Modified
13507 }
13508}
13509
13510/// If select range has more than one line, we
13511/// just point the cursor to range.start.
13512fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
13513 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
13514 range
13515 } else {
13516 range.start..range.start
13517 }
13518}