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 code_context_menus;
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;
31pub mod items;
32mod linked_editing_ranges;
33mod lsp_ext;
34mod mouse_context_menu;
35pub mod movement;
36mod persistence;
37mod proposed_changes_editor;
38mod rust_analyzer_ext;
39pub mod scroll;
40mod selections_collection;
41pub mod tasks;
42
43#[cfg(test)]
44mod editor_tests;
45#[cfg(test)]
46mod inline_completion_tests;
47mod signature_help;
48#[cfg(any(test, feature = "test-support"))]
49pub mod test;
50
51use ::git::diff::DiffHunkStatus;
52pub(crate) use actions::*;
53pub use actions::{OpenExcerpts, OpenExcerptsSplit};
54use aho_corasick::AhoCorasick;
55use anyhow::{anyhow, Context as _, Result};
56use blink_manager::BlinkManager;
57use client::{Collaborator, ParticipantIndex};
58use clock::ReplicaId;
59use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
60use convert_case::{Case, Casing};
61use display_map::*;
62pub use display_map::{DisplayPoint, FoldPlaceholder};
63pub use editor_settings::{
64 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
65};
66pub use editor_settings_controls::*;
67use element::LineWithInvisibles;
68pub use element::{
69 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
70};
71use futures::{future, FutureExt};
72use fuzzy::StringMatchCandidate;
73
74use code_context_menus::{
75 AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
76 CompletionsMenu, ContextMenuOrigin,
77};
78use git::blame::GitBlame;
79use gpui::{
80 div, impl_actions, point, prelude::*, px, relative, size, Action, AnyElement, AppContext,
81 AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context,
82 DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent, FocusableView, FontId,
83 FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Model, ModelContext,
84 MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText,
85 Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
86 UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
87 WeakView, WindowContext,
88};
89use highlight_matching_bracket::refresh_matching_bracket_highlights;
90use hover_popover::{hide_hover, HoverState};
91pub(crate) use hunk_diff::HoveredHunk;
92use hunk_diff::{diff_hunk_to_display, DiffMap, DiffMapSnapshot};
93use indent_guides::ActiveIndentGuidesState;
94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
95pub use inline_completion::Direction;
96use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
97pub use items::MAX_TAB_TITLE_LEN;
98use itertools::Itertools;
99use language::{
100 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
101 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
102 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
103 Point, Selection, SelectionGoal, TransactionId,
104};
105use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
106use linked_editing_ranges::refresh_linked_ranges;
107use mouse_context_menu::MouseContextMenu;
108pub use proposed_changes_editor::{
109 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
110};
111use similar::{ChangeTag, TextDiff};
112use std::iter::Peekable;
113use task::{ResolvedTask, TaskTemplate, TaskVariables};
114
115use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
116pub use lsp::CompletionContext;
117use lsp::{
118 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
119 LanguageServerId, LanguageServerName,
120};
121
122use movement::TextLayoutDetails;
123pub use multi_buffer::{
124 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
125 ToPoint,
126};
127use multi_buffer::{
128 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
129};
130use project::{
131 lsp_store::{FormatTarget, FormatTrigger, OpenLspBufferHandle},
132 project_settings::{GitGutterSetting, ProjectSettings},
133 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
134 LspStore, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
135};
136use rand::prelude::*;
137use rpc::{proto::*, ErrorExt};
138use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
139use selections_collection::{
140 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
141};
142use serde::{Deserialize, Serialize};
143use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
144use smallvec::SmallVec;
145use snippet::Snippet;
146use std::{
147 any::TypeId,
148 borrow::Cow,
149 cell::RefCell,
150 cmp::{self, Ordering, Reverse},
151 mem,
152 num::NonZeroU32,
153 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
154 path::{Path, PathBuf},
155 rc::Rc,
156 sync::Arc,
157 time::{Duration, Instant},
158};
159pub use sum_tree::Bias;
160use sum_tree::TreeMap;
161use text::{BufferId, OffsetUtf16, Rope};
162use theme::{
163 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
164 ThemeColors, ThemeSettings,
165};
166use ui::{
167 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
168 PopoverMenuHandle, Tooltip,
169};
170use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
171use workspace::item::{ItemHandle, PreviewTabsSettings};
172use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
173use workspace::{
174 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
175};
176use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
177
178use crate::hover_links::{find_url, find_url_from_range};
179use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
180
181pub const FILE_HEADER_HEIGHT: u32 = 2;
182pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
183pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
184pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
185const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
186const MAX_LINE_LEN: usize = 1024;
187const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
188const MAX_SELECTION_HISTORY_LEN: usize = 1024;
189pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
190#[doc(hidden)]
191pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
192
193pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
194pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
195
196pub fn render_parsed_markdown(
197 element_id: impl Into<ElementId>,
198 parsed: &language::ParsedMarkdown,
199 editor_style: &EditorStyle,
200 workspace: Option<WeakView<Workspace>>,
201 cx: &mut WindowContext,
202) -> InteractiveText {
203 let code_span_background_color = cx
204 .theme()
205 .colors()
206 .editor_document_highlight_read_background;
207
208 let highlights = gpui::combine_highlights(
209 parsed.highlights.iter().filter_map(|(range, highlight)| {
210 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
211 Some((range.clone(), highlight))
212 }),
213 parsed
214 .regions
215 .iter()
216 .zip(&parsed.region_ranges)
217 .filter_map(|(region, range)| {
218 if region.code {
219 Some((
220 range.clone(),
221 HighlightStyle {
222 background_color: Some(code_span_background_color),
223 ..Default::default()
224 },
225 ))
226 } else {
227 None
228 }
229 }),
230 );
231
232 let mut links = Vec::new();
233 let mut link_ranges = Vec::new();
234 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
235 if let Some(link) = region.link.clone() {
236 links.push(link);
237 link_ranges.push(range.clone());
238 }
239 }
240
241 InteractiveText::new(
242 element_id,
243 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
244 )
245 .on_click(link_ranges, move |clicked_range_ix, cx| {
246 match &links[clicked_range_ix] {
247 markdown::Link::Web { url } => cx.open_url(url),
248 markdown::Link::Path { path } => {
249 if let Some(workspace) = &workspace {
250 _ = workspace.update(cx, |workspace, cx| {
251 workspace.open_abs_path(path.clone(), false, cx).detach();
252 });
253 }
254 }
255 }
256 })
257}
258
259#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
260pub(crate) enum InlayId {
261 InlineCompletion(usize),
262 Hint(usize),
263}
264
265impl InlayId {
266 fn id(&self) -> usize {
267 match self {
268 Self::InlineCompletion(id) => *id,
269 Self::Hint(id) => *id,
270 }
271 }
272}
273
274enum DiffRowHighlight {}
275enum DocumentHighlightRead {}
276enum DocumentHighlightWrite {}
277enum InputComposition {}
278
279#[derive(Debug, Copy, Clone, PartialEq, Eq)]
280pub enum Navigated {
281 Yes,
282 No,
283}
284
285impl Navigated {
286 pub fn from_bool(yes: bool) -> Navigated {
287 if yes {
288 Navigated::Yes
289 } else {
290 Navigated::No
291 }
292 }
293}
294
295pub fn init_settings(cx: &mut AppContext) {
296 EditorSettings::register(cx);
297}
298
299pub fn init(cx: &mut AppContext) {
300 init_settings(cx);
301
302 workspace::register_project_item::<Editor>(cx);
303 workspace::FollowableViewRegistry::register::<Editor>(cx);
304 workspace::register_serializable_item::<Editor>(cx);
305
306 cx.observe_new_views(
307 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
308 workspace.register_action(Editor::new_file);
309 workspace.register_action(Editor::new_file_vertical);
310 workspace.register_action(Editor::new_file_horizontal);
311 },
312 )
313 .detach();
314
315 cx.on_action(move |_: &workspace::NewFile, 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 cx.on_action(move |_: &workspace::NewWindow, cx| {
325 let app_state = workspace::AppState::global(cx);
326 if let Some(app_state) = app_state.upgrade() {
327 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
328 Editor::new_file(workspace, &Default::default(), cx)
329 })
330 .detach();
331 }
332 });
333 git::project_diff::init(cx);
334}
335
336pub struct SearchWithinRange;
337
338trait InvalidationRegion {
339 fn ranges(&self) -> &[Range<Anchor>];
340}
341
342#[derive(Clone, Debug, PartialEq)]
343pub enum SelectPhase {
344 Begin {
345 position: DisplayPoint,
346 add: bool,
347 click_count: usize,
348 },
349 BeginColumnar {
350 position: DisplayPoint,
351 reset: bool,
352 goal_column: u32,
353 },
354 Extend {
355 position: DisplayPoint,
356 click_count: usize,
357 },
358 Update {
359 position: DisplayPoint,
360 goal_column: u32,
361 scroll_delta: gpui::Point<f32>,
362 },
363 End,
364}
365
366#[derive(Clone, Debug)]
367pub enum SelectMode {
368 Character,
369 Word(Range<Anchor>),
370 Line(Range<Anchor>),
371 All,
372}
373
374#[derive(Copy, Clone, PartialEq, Eq, Debug)]
375pub enum EditorMode {
376 SingleLine { auto_width: bool },
377 AutoHeight { max_lines: usize },
378 Full,
379}
380
381#[derive(Copy, Clone, Debug)]
382pub enum SoftWrap {
383 /// Prefer not to wrap at all.
384 ///
385 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
386 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
387 GitDiff,
388 /// Prefer a single line generally, unless an overly long line is encountered.
389 None,
390 /// Soft wrap lines that exceed the editor width.
391 EditorWidth,
392 /// Soft wrap lines at the preferred line length.
393 Column(u32),
394 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
395 Bounded(u32),
396}
397
398#[derive(Clone)]
399pub struct EditorStyle {
400 pub background: Hsla,
401 pub local_player: PlayerColor,
402 pub text: TextStyle,
403 pub scrollbar_width: Pixels,
404 pub syntax: Arc<SyntaxTheme>,
405 pub status: StatusColors,
406 pub inlay_hints_style: HighlightStyle,
407 pub inline_completion_styles: InlineCompletionStyles,
408 pub unnecessary_code_fade: f32,
409}
410
411impl Default for EditorStyle {
412 fn default() -> Self {
413 Self {
414 background: Hsla::default(),
415 local_player: PlayerColor::default(),
416 text: TextStyle::default(),
417 scrollbar_width: Pixels::default(),
418 syntax: Default::default(),
419 // HACK: Status colors don't have a real default.
420 // We should look into removing the status colors from the editor
421 // style and retrieve them directly from the theme.
422 status: StatusColors::dark(),
423 inlay_hints_style: HighlightStyle::default(),
424 inline_completion_styles: InlineCompletionStyles {
425 insertion: HighlightStyle::default(),
426 whitespace: HighlightStyle::default(),
427 },
428 unnecessary_code_fade: Default::default(),
429 }
430 }
431}
432
433pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
434 let show_background = language_settings::language_settings(None, None, cx)
435 .inlay_hints
436 .show_background;
437
438 HighlightStyle {
439 color: Some(cx.theme().status().hint),
440 background_color: show_background.then(|| cx.theme().status().hint_background),
441 ..HighlightStyle::default()
442 }
443}
444
445pub fn make_suggestion_styles(cx: &WindowContext) -> InlineCompletionStyles {
446 InlineCompletionStyles {
447 insertion: HighlightStyle {
448 color: Some(cx.theme().status().predictive),
449 ..HighlightStyle::default()
450 },
451 whitespace: HighlightStyle {
452 background_color: Some(cx.theme().status().created_background),
453 ..HighlightStyle::default()
454 },
455 }
456}
457
458type CompletionId = usize;
459
460enum InlineCompletion {
461 Edit(Vec<(Range<Anchor>, String)>),
462 Move(Anchor),
463}
464
465struct InlineCompletionState {
466 inlay_ids: Vec<InlayId>,
467 completion: InlineCompletion,
468 invalidation_range: Range<Anchor>,
469}
470
471enum InlineCompletionHighlight {}
472
473#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
474struct EditorActionId(usize);
475
476impl EditorActionId {
477 pub fn post_inc(&mut self) -> Self {
478 let answer = self.0;
479
480 *self = Self(answer + 1);
481
482 Self(answer)
483 }
484}
485
486// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
487// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
488
489type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
490type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
491
492#[derive(Default)]
493struct ScrollbarMarkerState {
494 scrollbar_size: Size<Pixels>,
495 dirty: bool,
496 markers: Arc<[PaintQuad]>,
497 pending_refresh: Option<Task<Result<()>>>,
498}
499
500impl ScrollbarMarkerState {
501 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
502 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
503 }
504}
505
506#[derive(Clone, Debug)]
507struct RunnableTasks {
508 templates: Vec<(TaskSourceKind, TaskTemplate)>,
509 offset: MultiBufferOffset,
510 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
511 column: u32,
512 // Values of all named captures, including those starting with '_'
513 extra_variables: HashMap<String, String>,
514 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
515 context_range: Range<BufferOffset>,
516}
517
518impl RunnableTasks {
519 fn resolve<'a>(
520 &'a self,
521 cx: &'a task::TaskContext,
522 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
523 self.templates.iter().filter_map(|(kind, template)| {
524 template
525 .resolve_task(&kind.to_id_base(), cx)
526 .map(|task| (kind.clone(), task))
527 })
528 }
529}
530
531#[derive(Clone)]
532struct ResolvedTasks {
533 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
534 position: Anchor,
535}
536#[derive(Copy, Clone, Debug)]
537struct MultiBufferOffset(usize);
538#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
539struct BufferOffset(usize);
540
541// Addons allow storing per-editor state in other crates (e.g. Vim)
542pub trait Addon: 'static {
543 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
544
545 fn to_any(&self) -> &dyn std::any::Any;
546}
547
548#[derive(Debug, Copy, Clone, PartialEq, Eq)]
549pub enum IsVimMode {
550 Yes,
551 No,
552}
553
554/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
555///
556/// See the [module level documentation](self) for more information.
557pub struct Editor {
558 focus_handle: FocusHandle,
559 last_focused_descendant: Option<WeakFocusHandle>,
560 /// The text buffer being edited
561 buffer: Model<MultiBuffer>,
562 /// Map of how text in the buffer should be displayed.
563 /// Handles soft wraps, folds, fake inlay text insertions, etc.
564 pub display_map: Model<DisplayMap>,
565 pub selections: SelectionsCollection,
566 pub scroll_manager: ScrollManager,
567 /// When inline assist editors are linked, they all render cursors because
568 /// typing enters text into each of them, even the ones that aren't focused.
569 pub(crate) show_cursor_when_unfocused: bool,
570 columnar_selection_tail: Option<Anchor>,
571 add_selections_state: Option<AddSelectionsState>,
572 select_next_state: Option<SelectNextState>,
573 select_prev_state: Option<SelectNextState>,
574 selection_history: SelectionHistory,
575 autoclose_regions: Vec<AutocloseRegion>,
576 snippet_stack: InvalidationStack<SnippetState>,
577 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
578 ime_transaction: Option<TransactionId>,
579 active_diagnostics: Option<ActiveDiagnosticGroup>,
580 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
581
582 project: Option<Model<Project>>,
583 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
584 completion_provider: Option<Box<dyn CompletionProvider>>,
585 collaboration_hub: Option<Box<dyn CollaborationHub>>,
586 blink_manager: Model<BlinkManager>,
587 show_cursor_names: bool,
588 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
589 pub show_local_selections: bool,
590 mode: EditorMode,
591 show_breadcrumbs: bool,
592 show_gutter: bool,
593 show_line_numbers: Option<bool>,
594 use_relative_line_numbers: Option<bool>,
595 show_git_diff_gutter: Option<bool>,
596 show_code_actions: Option<bool>,
597 show_runnables: Option<bool>,
598 show_wrap_guides: Option<bool>,
599 show_indent_guides: Option<bool>,
600 placeholder_text: Option<Arc<str>>,
601 highlight_order: usize,
602 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
603 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
604 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
605 scrollbar_marker_state: ScrollbarMarkerState,
606 active_indent_guides_state: ActiveIndentGuidesState,
607 nav_history: Option<ItemNavHistory>,
608 context_menu: RefCell<Option<CodeContextMenu>>,
609 mouse_context_menu: Option<MouseContextMenu>,
610 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
611 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
612 signature_help_state: SignatureHelpState,
613 auto_signature_help: Option<bool>,
614 find_all_references_task_sources: Vec<Anchor>,
615 next_completion_id: CompletionId,
616 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
617 code_actions_task: Option<Task<Result<()>>>,
618 document_highlights_task: Option<Task<()>>,
619 linked_editing_range_task: Option<Task<Option<()>>>,
620 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
621 pending_rename: Option<RenameState>,
622 searchable: bool,
623 cursor_shape: CursorShape,
624 current_line_highlight: Option<CurrentLineHighlight>,
625 collapse_matches: bool,
626 autoindent_mode: Option<AutoindentMode>,
627 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
628 input_enabled: bool,
629 use_modal_editing: bool,
630 read_only: bool,
631 leader_peer_id: Option<PeerId>,
632 remote_id: Option<ViewId>,
633 hover_state: HoverState,
634 gutter_hovered: bool,
635 hovered_link_state: Option<HoveredLinkState>,
636 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
637 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
638 active_inline_completion: Option<InlineCompletionState>,
639 // enable_inline_completions is a switch that Vim can use to disable
640 // inline completions based on its mode.
641 enable_inline_completions: bool,
642 show_inline_completions_override: Option<bool>,
643 inlay_hint_cache: InlayHintCache,
644 diff_map: DiffMap,
645 next_inlay_id: usize,
646 _subscriptions: Vec<Subscription>,
647 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
648 gutter_dimensions: GutterDimensions,
649 style: Option<EditorStyle>,
650 text_style_refinement: Option<TextStyleRefinement>,
651 next_editor_action_id: EditorActionId,
652 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
653 use_autoclose: bool,
654 use_auto_surround: bool,
655 auto_replace_emoji_shortcode: bool,
656 show_git_blame_gutter: bool,
657 show_git_blame_inline: bool,
658 show_git_blame_inline_delay_task: Option<Task<()>>,
659 git_blame_inline_enabled: bool,
660 serialize_dirty_buffers: bool,
661 show_selection_menu: Option<bool>,
662 blame: Option<Model<GitBlame>>,
663 blame_subscription: Option<Subscription>,
664 custom_context_menu: Option<
665 Box<
666 dyn 'static
667 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
668 >,
669 >,
670 last_bounds: Option<Bounds<Pixels>>,
671 expect_bounds_change: Option<Bounds<Pixels>>,
672 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
673 tasks_update_task: Option<Task<()>>,
674 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
675 breadcrumb_header: Option<String>,
676 focused_block: Option<FocusedBlock>,
677 next_scroll_position: NextScrollCursorCenterTopBottom,
678 addons: HashMap<TypeId, Box<dyn Addon>>,
679 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
680 toggle_fold_multiple_buffers: Task<()>,
681 _scroll_cursor_center_top_bottom_task: Task<()>,
682}
683
684#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
685enum NextScrollCursorCenterTopBottom {
686 #[default]
687 Center,
688 Top,
689 Bottom,
690}
691
692impl NextScrollCursorCenterTopBottom {
693 fn next(&self) -> Self {
694 match self {
695 Self::Center => Self::Top,
696 Self::Top => Self::Bottom,
697 Self::Bottom => Self::Center,
698 }
699 }
700}
701
702#[derive(Clone)]
703pub struct EditorSnapshot {
704 pub mode: EditorMode,
705 show_gutter: bool,
706 show_line_numbers: Option<bool>,
707 show_git_diff_gutter: Option<bool>,
708 show_code_actions: Option<bool>,
709 show_runnables: Option<bool>,
710 git_blame_gutter_max_author_length: Option<usize>,
711 pub display_snapshot: DisplaySnapshot,
712 pub placeholder_text: Option<Arc<str>>,
713 diff_map: DiffMapSnapshot,
714 is_focused: bool,
715 scroll_anchor: ScrollAnchor,
716 ongoing_scroll: OngoingScroll,
717 current_line_highlight: CurrentLineHighlight,
718 gutter_hovered: bool,
719}
720
721const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
722
723#[derive(Default, Debug, Clone, Copy)]
724pub struct GutterDimensions {
725 pub left_padding: Pixels,
726 pub right_padding: Pixels,
727 pub width: Pixels,
728 pub margin: Pixels,
729 pub git_blame_entries_width: Option<Pixels>,
730}
731
732impl GutterDimensions {
733 /// The full width of the space taken up by the gutter.
734 pub fn full_width(&self) -> Pixels {
735 self.margin + self.width
736 }
737
738 /// The width of the space reserved for the fold indicators,
739 /// use alongside 'justify_end' and `gutter_width` to
740 /// right align content with the line numbers
741 pub fn fold_area_width(&self) -> Pixels {
742 self.margin + self.right_padding
743 }
744}
745
746#[derive(Debug)]
747pub struct RemoteSelection {
748 pub replica_id: ReplicaId,
749 pub selection: Selection<Anchor>,
750 pub cursor_shape: CursorShape,
751 pub peer_id: PeerId,
752 pub line_mode: bool,
753 pub participant_index: Option<ParticipantIndex>,
754 pub user_name: Option<SharedString>,
755}
756
757#[derive(Clone, Debug)]
758struct SelectionHistoryEntry {
759 selections: Arc<[Selection<Anchor>]>,
760 select_next_state: Option<SelectNextState>,
761 select_prev_state: Option<SelectNextState>,
762 add_selections_state: Option<AddSelectionsState>,
763}
764
765enum SelectionHistoryMode {
766 Normal,
767 Undoing,
768 Redoing,
769}
770
771#[derive(Clone, PartialEq, Eq, Hash)]
772struct HoveredCursor {
773 replica_id: u16,
774 selection_id: usize,
775}
776
777impl Default for SelectionHistoryMode {
778 fn default() -> Self {
779 Self::Normal
780 }
781}
782
783#[derive(Default)]
784struct SelectionHistory {
785 #[allow(clippy::type_complexity)]
786 selections_by_transaction:
787 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
788 mode: SelectionHistoryMode,
789 undo_stack: VecDeque<SelectionHistoryEntry>,
790 redo_stack: VecDeque<SelectionHistoryEntry>,
791}
792
793impl SelectionHistory {
794 fn insert_transaction(
795 &mut self,
796 transaction_id: TransactionId,
797 selections: Arc<[Selection<Anchor>]>,
798 ) {
799 self.selections_by_transaction
800 .insert(transaction_id, (selections, None));
801 }
802
803 #[allow(clippy::type_complexity)]
804 fn transaction(
805 &self,
806 transaction_id: TransactionId,
807 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
808 self.selections_by_transaction.get(&transaction_id)
809 }
810
811 #[allow(clippy::type_complexity)]
812 fn transaction_mut(
813 &mut self,
814 transaction_id: TransactionId,
815 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
816 self.selections_by_transaction.get_mut(&transaction_id)
817 }
818
819 fn push(&mut self, entry: SelectionHistoryEntry) {
820 if !entry.selections.is_empty() {
821 match self.mode {
822 SelectionHistoryMode::Normal => {
823 self.push_undo(entry);
824 self.redo_stack.clear();
825 }
826 SelectionHistoryMode::Undoing => self.push_redo(entry),
827 SelectionHistoryMode::Redoing => self.push_undo(entry),
828 }
829 }
830 }
831
832 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
833 if self
834 .undo_stack
835 .back()
836 .map_or(true, |e| e.selections != entry.selections)
837 {
838 self.undo_stack.push_back(entry);
839 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
840 self.undo_stack.pop_front();
841 }
842 }
843 }
844
845 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
846 if self
847 .redo_stack
848 .back()
849 .map_or(true, |e| e.selections != entry.selections)
850 {
851 self.redo_stack.push_back(entry);
852 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
853 self.redo_stack.pop_front();
854 }
855 }
856 }
857}
858
859struct RowHighlight {
860 index: usize,
861 range: Range<Anchor>,
862 color: Hsla,
863 should_autoscroll: bool,
864}
865
866#[derive(Clone, Debug)]
867struct AddSelectionsState {
868 above: bool,
869 stack: Vec<usize>,
870}
871
872#[derive(Clone)]
873struct SelectNextState {
874 query: AhoCorasick,
875 wordwise: bool,
876 done: bool,
877}
878
879impl std::fmt::Debug for SelectNextState {
880 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
881 f.debug_struct(std::any::type_name::<Self>())
882 .field("wordwise", &self.wordwise)
883 .field("done", &self.done)
884 .finish()
885 }
886}
887
888#[derive(Debug)]
889struct AutocloseRegion {
890 selection_id: usize,
891 range: Range<Anchor>,
892 pair: BracketPair,
893}
894
895#[derive(Debug)]
896struct SnippetState {
897 ranges: Vec<Vec<Range<Anchor>>>,
898 active_index: usize,
899 choices: Vec<Option<Vec<String>>>,
900}
901
902#[doc(hidden)]
903pub struct RenameState {
904 pub range: Range<Anchor>,
905 pub old_name: Arc<str>,
906 pub editor: View<Editor>,
907 block_id: CustomBlockId,
908}
909
910struct InvalidationStack<T>(Vec<T>);
911
912struct RegisteredInlineCompletionProvider {
913 provider: Arc<dyn InlineCompletionProviderHandle>,
914 _subscription: Subscription,
915}
916
917#[derive(Debug)]
918struct ActiveDiagnosticGroup {
919 primary_range: Range<Anchor>,
920 primary_message: String,
921 group_id: usize,
922 blocks: HashMap<CustomBlockId, Diagnostic>,
923 is_valid: bool,
924}
925
926#[derive(Serialize, Deserialize, Clone, Debug)]
927pub struct ClipboardSelection {
928 pub len: usize,
929 pub is_entire_line: bool,
930 pub first_line_indent: u32,
931}
932
933#[derive(Debug)]
934pub(crate) struct NavigationData {
935 cursor_anchor: Anchor,
936 cursor_position: Point,
937 scroll_anchor: ScrollAnchor,
938 scroll_top_row: u32,
939}
940
941#[derive(Debug, Clone, Copy, PartialEq, Eq)]
942pub enum GotoDefinitionKind {
943 Symbol,
944 Declaration,
945 Type,
946 Implementation,
947}
948
949#[derive(Debug, Clone)]
950enum InlayHintRefreshReason {
951 Toggle(bool),
952 SettingsChange(InlayHintSettings),
953 NewLinesShown,
954 BufferEdited(HashSet<Arc<Language>>),
955 RefreshRequested,
956 ExcerptsRemoved(Vec<ExcerptId>),
957}
958
959impl InlayHintRefreshReason {
960 fn description(&self) -> &'static str {
961 match self {
962 Self::Toggle(_) => "toggle",
963 Self::SettingsChange(_) => "settings change",
964 Self::NewLinesShown => "new lines shown",
965 Self::BufferEdited(_) => "buffer edited",
966 Self::RefreshRequested => "refresh requested",
967 Self::ExcerptsRemoved(_) => "excerpts removed",
968 }
969 }
970}
971
972pub(crate) struct FocusedBlock {
973 id: BlockId,
974 focus_handle: WeakFocusHandle,
975}
976
977#[derive(Clone)]
978struct JumpData {
979 excerpt_id: ExcerptId,
980 position: Point,
981 anchor: text::Anchor,
982 path: Option<project::ProjectPath>,
983 line_offset_from_top: u32,
984}
985
986impl Editor {
987 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
988 let buffer = cx.new_model(|cx| Buffer::local("", cx));
989 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
990 Self::new(
991 EditorMode::SingleLine { auto_width: false },
992 buffer,
993 None,
994 false,
995 cx,
996 )
997 }
998
999 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1000 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1001 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1002 Self::new(EditorMode::Full, buffer, None, false, cx)
1003 }
1004
1005 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1006 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1007 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1008 Self::new(
1009 EditorMode::SingleLine { auto_width: true },
1010 buffer,
1011 None,
1012 false,
1013 cx,
1014 )
1015 }
1016
1017 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1018 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1019 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1020 Self::new(
1021 EditorMode::AutoHeight { max_lines },
1022 buffer,
1023 None,
1024 false,
1025 cx,
1026 )
1027 }
1028
1029 pub fn for_buffer(
1030 buffer: Model<Buffer>,
1031 project: Option<Model<Project>>,
1032 cx: &mut ViewContext<Self>,
1033 ) -> Self {
1034 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1035 Self::new(EditorMode::Full, buffer, project, false, cx)
1036 }
1037
1038 pub fn for_multibuffer(
1039 buffer: Model<MultiBuffer>,
1040 project: Option<Model<Project>>,
1041 show_excerpt_controls: bool,
1042 cx: &mut ViewContext<Self>,
1043 ) -> Self {
1044 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1045 }
1046
1047 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1048 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1049 let mut clone = Self::new(
1050 self.mode,
1051 self.buffer.clone(),
1052 self.project.clone(),
1053 show_excerpt_controls,
1054 cx,
1055 );
1056 self.display_map.update(cx, |display_map, cx| {
1057 let snapshot = display_map.snapshot(cx);
1058 clone.display_map.update(cx, |display_map, cx| {
1059 display_map.set_state(&snapshot, cx);
1060 });
1061 });
1062 clone.selections.clone_state(&self.selections);
1063 clone.scroll_manager.clone_state(&self.scroll_manager);
1064 clone.searchable = self.searchable;
1065 clone
1066 }
1067
1068 pub fn new(
1069 mode: EditorMode,
1070 buffer: Model<MultiBuffer>,
1071 project: Option<Model<Project>>,
1072 show_excerpt_controls: bool,
1073 cx: &mut ViewContext<Self>,
1074 ) -> Self {
1075 let style = cx.text_style();
1076 let font_size = style.font_size.to_pixels(cx.rem_size());
1077 let editor = cx.view().downgrade();
1078 let fold_placeholder = FoldPlaceholder {
1079 constrain_width: true,
1080 render: Arc::new(move |fold_id, fold_range, cx| {
1081 let editor = editor.clone();
1082 div()
1083 .id(fold_id)
1084 .bg(cx.theme().colors().ghost_element_background)
1085 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1086 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1087 .rounded_sm()
1088 .size_full()
1089 .cursor_pointer()
1090 .child("⋯")
1091 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1092 .on_click(move |_, cx| {
1093 editor
1094 .update(cx, |editor, cx| {
1095 editor.unfold_ranges(
1096 &[fold_range.start..fold_range.end],
1097 true,
1098 false,
1099 cx,
1100 );
1101 cx.stop_propagation();
1102 })
1103 .ok();
1104 })
1105 .into_any()
1106 }),
1107 merge_adjacent: true,
1108 ..Default::default()
1109 };
1110 let display_map = cx.new_model(|cx| {
1111 DisplayMap::new(
1112 buffer.clone(),
1113 style.font(),
1114 font_size,
1115 None,
1116 show_excerpt_controls,
1117 FILE_HEADER_HEIGHT,
1118 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1119 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1120 fold_placeholder,
1121 cx,
1122 )
1123 });
1124
1125 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1126
1127 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1128
1129 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1130 .then(|| language_settings::SoftWrap::None);
1131
1132 let mut project_subscriptions = Vec::new();
1133 if mode == EditorMode::Full {
1134 if let Some(project) = project.as_ref() {
1135 if buffer.read(cx).is_singleton() {
1136 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1137 cx.emit(EditorEvent::TitleChanged);
1138 }));
1139 }
1140 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1141 if let project::Event::RefreshInlayHints = event {
1142 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1143 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1144 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1145 let focus_handle = editor.focus_handle(cx);
1146 if focus_handle.is_focused(cx) {
1147 let snapshot = buffer.read(cx).snapshot();
1148 for (range, snippet) in snippet_edits {
1149 let editor_range =
1150 language::range_from_lsp(*range).to_offset(&snapshot);
1151 editor
1152 .insert_snippet(&[editor_range], snippet.clone(), cx)
1153 .ok();
1154 }
1155 }
1156 }
1157 }
1158 }));
1159 if let Some(task_inventory) = project
1160 .read(cx)
1161 .task_store()
1162 .read(cx)
1163 .task_inventory()
1164 .cloned()
1165 {
1166 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1167 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1168 }));
1169 }
1170 }
1171 }
1172
1173 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1174
1175 let inlay_hint_settings =
1176 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1177 let focus_handle = cx.focus_handle();
1178 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1179 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1180 .detach();
1181 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1182 .detach();
1183 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1184
1185 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1186 Some(false)
1187 } else {
1188 None
1189 };
1190
1191 let mut code_action_providers = Vec::new();
1192 if let Some(project) = project.clone() {
1193 get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
1194 code_action_providers.push(Rc::new(project) as Rc<_>);
1195 }
1196
1197 let mut this = Self {
1198 focus_handle,
1199 show_cursor_when_unfocused: false,
1200 last_focused_descendant: None,
1201 buffer: buffer.clone(),
1202 display_map: display_map.clone(),
1203 selections,
1204 scroll_manager: ScrollManager::new(cx),
1205 columnar_selection_tail: None,
1206 add_selections_state: None,
1207 select_next_state: None,
1208 select_prev_state: None,
1209 selection_history: Default::default(),
1210 autoclose_regions: Default::default(),
1211 snippet_stack: Default::default(),
1212 select_larger_syntax_node_stack: Vec::new(),
1213 ime_transaction: Default::default(),
1214 active_diagnostics: None,
1215 soft_wrap_mode_override,
1216 completion_provider: project.clone().map(|project| Box::new(project) as _),
1217 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1218 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1219 project,
1220 blink_manager: blink_manager.clone(),
1221 show_local_selections: true,
1222 mode,
1223 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1224 show_gutter: mode == EditorMode::Full,
1225 show_line_numbers: None,
1226 use_relative_line_numbers: None,
1227 show_git_diff_gutter: None,
1228 show_code_actions: None,
1229 show_runnables: None,
1230 show_wrap_guides: None,
1231 show_indent_guides,
1232 placeholder_text: None,
1233 highlight_order: 0,
1234 highlighted_rows: HashMap::default(),
1235 background_highlights: Default::default(),
1236 gutter_highlights: TreeMap::default(),
1237 scrollbar_marker_state: ScrollbarMarkerState::default(),
1238 active_indent_guides_state: ActiveIndentGuidesState::default(),
1239 nav_history: None,
1240 context_menu: RefCell::new(None),
1241 mouse_context_menu: None,
1242 hunk_controls_menu_handle: PopoverMenuHandle::default(),
1243 completion_tasks: Default::default(),
1244 signature_help_state: SignatureHelpState::default(),
1245 auto_signature_help: None,
1246 find_all_references_task_sources: Vec::new(),
1247 next_completion_id: 0,
1248 next_inlay_id: 0,
1249 code_action_providers,
1250 available_code_actions: Default::default(),
1251 code_actions_task: Default::default(),
1252 document_highlights_task: Default::default(),
1253 linked_editing_range_task: Default::default(),
1254 pending_rename: Default::default(),
1255 searchable: true,
1256 cursor_shape: EditorSettings::get_global(cx)
1257 .cursor_shape
1258 .unwrap_or_default(),
1259 current_line_highlight: None,
1260 autoindent_mode: Some(AutoindentMode::EachLine),
1261 collapse_matches: false,
1262 workspace: None,
1263 input_enabled: true,
1264 use_modal_editing: mode == EditorMode::Full,
1265 read_only: false,
1266 use_autoclose: true,
1267 use_auto_surround: true,
1268 auto_replace_emoji_shortcode: false,
1269 leader_peer_id: None,
1270 remote_id: None,
1271 hover_state: Default::default(),
1272 hovered_link_state: Default::default(),
1273 inline_completion_provider: None,
1274 active_inline_completion: None,
1275 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1276 diff_map: DiffMap::default(),
1277 gutter_hovered: false,
1278 pixel_position_of_newest_cursor: None,
1279 last_bounds: None,
1280 expect_bounds_change: None,
1281 gutter_dimensions: GutterDimensions::default(),
1282 style: None,
1283 show_cursor_names: false,
1284 hovered_cursors: Default::default(),
1285 next_editor_action_id: EditorActionId::default(),
1286 editor_actions: Rc::default(),
1287 show_inline_completions_override: None,
1288 enable_inline_completions: true,
1289 custom_context_menu: None,
1290 show_git_blame_gutter: false,
1291 show_git_blame_inline: false,
1292 show_selection_menu: None,
1293 show_git_blame_inline_delay_task: None,
1294 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1295 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1296 .session
1297 .restore_unsaved_buffers,
1298 blame: None,
1299 blame_subscription: None,
1300 tasks: Default::default(),
1301 _subscriptions: vec![
1302 cx.observe(&buffer, Self::on_buffer_changed),
1303 cx.subscribe(&buffer, Self::on_buffer_event),
1304 cx.observe(&display_map, Self::on_display_map_changed),
1305 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1306 cx.observe_global::<SettingsStore>(Self::settings_changed),
1307 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1308 cx.observe_window_activation(|editor, cx| {
1309 let active = cx.is_window_active();
1310 editor.blink_manager.update(cx, |blink_manager, cx| {
1311 if active {
1312 blink_manager.enable(cx);
1313 } else {
1314 blink_manager.disable(cx);
1315 }
1316 });
1317 }),
1318 ],
1319 tasks_update_task: None,
1320 linked_edit_ranges: Default::default(),
1321 previous_search_ranges: None,
1322 breadcrumb_header: None,
1323 focused_block: None,
1324 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1325 addons: HashMap::default(),
1326 registered_buffers: HashMap::default(),
1327 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1328 toggle_fold_multiple_buffers: Task::ready(()),
1329 text_style_refinement: None,
1330 };
1331 this.tasks_update_task = Some(this.refresh_runnables(cx));
1332 this._subscriptions.extend(project_subscriptions);
1333
1334 this.end_selection(cx);
1335 this.scroll_manager.show_scrollbar(cx);
1336
1337 if mode == EditorMode::Full {
1338 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1339 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1340
1341 if this.git_blame_inline_enabled {
1342 this.git_blame_inline_enabled = true;
1343 this.start_git_blame_inline(false, cx);
1344 }
1345
1346 if let Some(buffer) = buffer.read(cx).as_singleton() {
1347 if let Some(project) = this.project.as_ref() {
1348 let lsp_store = project.read(cx).lsp_store();
1349 let handle = lsp_store.update(cx, |lsp_store, cx| {
1350 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1351 });
1352 this.registered_buffers
1353 .insert(buffer.read(cx).remote_id(), handle);
1354 }
1355 }
1356 }
1357
1358 this.report_editor_event("open", None, cx);
1359 this
1360 }
1361
1362 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
1363 self.mouse_context_menu
1364 .as_ref()
1365 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1366 }
1367
1368 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
1369 let mut key_context = KeyContext::new_with_defaults();
1370 key_context.add("Editor");
1371 let mode = match self.mode {
1372 EditorMode::SingleLine { .. } => "single_line",
1373 EditorMode::AutoHeight { .. } => "auto_height",
1374 EditorMode::Full => "full",
1375 };
1376
1377 if EditorSettings::jupyter_enabled(cx) {
1378 key_context.add("jupyter");
1379 }
1380
1381 key_context.set("mode", mode);
1382 if self.pending_rename.is_some() {
1383 key_context.add("renaming");
1384 }
1385 if self.context_menu_visible() {
1386 match self.context_menu.borrow().as_ref() {
1387 Some(CodeContextMenu::Completions(_)) => {
1388 key_context.add("menu");
1389 key_context.add("showing_completions")
1390 }
1391 Some(CodeContextMenu::CodeActions(_)) => {
1392 key_context.add("menu");
1393 key_context.add("showing_code_actions")
1394 }
1395 None => {}
1396 }
1397 }
1398
1399 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1400 if !self.focus_handle(cx).contains_focused(cx)
1401 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
1402 {
1403 for addon in self.addons.values() {
1404 addon.extend_key_context(&mut key_context, cx)
1405 }
1406 }
1407
1408 if let Some(extension) = self
1409 .buffer
1410 .read(cx)
1411 .as_singleton()
1412 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1413 {
1414 key_context.set("extension", extension.to_string());
1415 }
1416
1417 if self.has_active_inline_completion() {
1418 key_context.add("copilot_suggestion");
1419 key_context.add("inline_completion");
1420 }
1421
1422 if !self
1423 .selections
1424 .disjoint
1425 .iter()
1426 .all(|selection| selection.start == selection.end)
1427 {
1428 key_context.add("selection");
1429 }
1430
1431 key_context
1432 }
1433
1434 pub fn new_file(
1435 workspace: &mut Workspace,
1436 _: &workspace::NewFile,
1437 cx: &mut ViewContext<Workspace>,
1438 ) {
1439 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
1440 "Failed to create buffer",
1441 cx,
1442 |e, _| match e.error_code() {
1443 ErrorCode::RemoteUpgradeRequired => Some(format!(
1444 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1445 e.error_tag("required").unwrap_or("the latest version")
1446 )),
1447 _ => None,
1448 },
1449 );
1450 }
1451
1452 pub fn new_in_workspace(
1453 workspace: &mut Workspace,
1454 cx: &mut ViewContext<Workspace>,
1455 ) -> Task<Result<View<Editor>>> {
1456 let project = workspace.project().clone();
1457 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1458
1459 cx.spawn(|workspace, mut cx| async move {
1460 let buffer = create.await?;
1461 workspace.update(&mut cx, |workspace, cx| {
1462 let editor =
1463 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
1464 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
1465 editor
1466 })
1467 })
1468 }
1469
1470 fn new_file_vertical(
1471 workspace: &mut Workspace,
1472 _: &workspace::NewFileSplitVertical,
1473 cx: &mut ViewContext<Workspace>,
1474 ) {
1475 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
1476 }
1477
1478 fn new_file_horizontal(
1479 workspace: &mut Workspace,
1480 _: &workspace::NewFileSplitHorizontal,
1481 cx: &mut ViewContext<Workspace>,
1482 ) {
1483 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
1484 }
1485
1486 fn new_file_in_direction(
1487 workspace: &mut Workspace,
1488 direction: SplitDirection,
1489 cx: &mut ViewContext<Workspace>,
1490 ) {
1491 let project = workspace.project().clone();
1492 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1493
1494 cx.spawn(|workspace, mut cx| async move {
1495 let buffer = create.await?;
1496 workspace.update(&mut cx, move |workspace, cx| {
1497 workspace.split_item(
1498 direction,
1499 Box::new(
1500 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
1501 ),
1502 cx,
1503 )
1504 })?;
1505 anyhow::Ok(())
1506 })
1507 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
1508 ErrorCode::RemoteUpgradeRequired => Some(format!(
1509 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1510 e.error_tag("required").unwrap_or("the latest version")
1511 )),
1512 _ => None,
1513 });
1514 }
1515
1516 pub fn leader_peer_id(&self) -> Option<PeerId> {
1517 self.leader_peer_id
1518 }
1519
1520 pub fn buffer(&self) -> &Model<MultiBuffer> {
1521 &self.buffer
1522 }
1523
1524 pub fn workspace(&self) -> Option<View<Workspace>> {
1525 self.workspace.as_ref()?.0.upgrade()
1526 }
1527
1528 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
1529 self.buffer().read(cx).title(cx)
1530 }
1531
1532 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
1533 let git_blame_gutter_max_author_length = self
1534 .render_git_blame_gutter(cx)
1535 .then(|| {
1536 if let Some(blame) = self.blame.as_ref() {
1537 let max_author_length =
1538 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1539 Some(max_author_length)
1540 } else {
1541 None
1542 }
1543 })
1544 .flatten();
1545
1546 EditorSnapshot {
1547 mode: self.mode,
1548 show_gutter: self.show_gutter,
1549 show_line_numbers: self.show_line_numbers,
1550 show_git_diff_gutter: self.show_git_diff_gutter,
1551 show_code_actions: self.show_code_actions,
1552 show_runnables: self.show_runnables,
1553 git_blame_gutter_max_author_length,
1554 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1555 scroll_anchor: self.scroll_manager.anchor(),
1556 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1557 placeholder_text: self.placeholder_text.clone(),
1558 diff_map: self.diff_map.snapshot(),
1559 is_focused: self.focus_handle.is_focused(cx),
1560 current_line_highlight: self
1561 .current_line_highlight
1562 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1563 gutter_hovered: self.gutter_hovered,
1564 }
1565 }
1566
1567 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
1568 self.buffer.read(cx).language_at(point, cx)
1569 }
1570
1571 pub fn file_at<T: ToOffset>(
1572 &self,
1573 point: T,
1574 cx: &AppContext,
1575 ) -> Option<Arc<dyn language::File>> {
1576 self.buffer.read(cx).read(cx).file_at(point).cloned()
1577 }
1578
1579 pub fn active_excerpt(
1580 &self,
1581 cx: &AppContext,
1582 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
1583 self.buffer
1584 .read(cx)
1585 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1586 }
1587
1588 pub fn mode(&self) -> EditorMode {
1589 self.mode
1590 }
1591
1592 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1593 self.collaboration_hub.as_deref()
1594 }
1595
1596 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1597 self.collaboration_hub = Some(hub);
1598 }
1599
1600 pub fn set_custom_context_menu(
1601 &mut self,
1602 f: impl 'static
1603 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
1604 ) {
1605 self.custom_context_menu = Some(Box::new(f))
1606 }
1607
1608 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1609 self.completion_provider = provider;
1610 }
1611
1612 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1613 self.semantics_provider.clone()
1614 }
1615
1616 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1617 self.semantics_provider = provider;
1618 }
1619
1620 pub fn set_inline_completion_provider<T>(
1621 &mut self,
1622 provider: Option<Model<T>>,
1623 cx: &mut ViewContext<Self>,
1624 ) where
1625 T: InlineCompletionProvider,
1626 {
1627 self.inline_completion_provider =
1628 provider.map(|provider| RegisteredInlineCompletionProvider {
1629 _subscription: cx.observe(&provider, |this, _, cx| {
1630 if this.focus_handle.is_focused(cx) {
1631 this.update_visible_inline_completion(cx);
1632 }
1633 }),
1634 provider: Arc::new(provider),
1635 });
1636 self.refresh_inline_completion(false, false, cx);
1637 }
1638
1639 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
1640 self.placeholder_text.as_deref()
1641 }
1642
1643 pub fn set_placeholder_text(
1644 &mut self,
1645 placeholder_text: impl Into<Arc<str>>,
1646 cx: &mut ViewContext<Self>,
1647 ) {
1648 let placeholder_text = Some(placeholder_text.into());
1649 if self.placeholder_text != placeholder_text {
1650 self.placeholder_text = placeholder_text;
1651 cx.notify();
1652 }
1653 }
1654
1655 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
1656 self.cursor_shape = cursor_shape;
1657
1658 // Disrupt blink for immediate user feedback that the cursor shape has changed
1659 self.blink_manager.update(cx, BlinkManager::show_cursor);
1660
1661 cx.notify();
1662 }
1663
1664 pub fn set_current_line_highlight(
1665 &mut self,
1666 current_line_highlight: Option<CurrentLineHighlight>,
1667 ) {
1668 self.current_line_highlight = current_line_highlight;
1669 }
1670
1671 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1672 self.collapse_matches = collapse_matches;
1673 }
1674
1675 pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
1676 let buffers = self.buffer.read(cx).all_buffers();
1677 let Some(lsp_store) = self.lsp_store(cx) else {
1678 return;
1679 };
1680 lsp_store.update(cx, |lsp_store, cx| {
1681 for buffer in buffers {
1682 self.registered_buffers
1683 .entry(buffer.read(cx).remote_id())
1684 .or_insert_with(|| {
1685 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1686 });
1687 }
1688 })
1689 }
1690
1691 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1692 if self.collapse_matches {
1693 return range.start..range.start;
1694 }
1695 range.clone()
1696 }
1697
1698 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
1699 if self.display_map.read(cx).clip_at_line_ends != clip {
1700 self.display_map
1701 .update(cx, |map, _| map.clip_at_line_ends = clip);
1702 }
1703 }
1704
1705 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1706 self.input_enabled = input_enabled;
1707 }
1708
1709 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
1710 self.enable_inline_completions = enabled;
1711 }
1712
1713 pub fn set_autoindent(&mut self, autoindent: bool) {
1714 if autoindent {
1715 self.autoindent_mode = Some(AutoindentMode::EachLine);
1716 } else {
1717 self.autoindent_mode = None;
1718 }
1719 }
1720
1721 pub fn read_only(&self, cx: &AppContext) -> bool {
1722 self.read_only || self.buffer.read(cx).read_only()
1723 }
1724
1725 pub fn set_read_only(&mut self, read_only: bool) {
1726 self.read_only = read_only;
1727 }
1728
1729 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1730 self.use_autoclose = autoclose;
1731 }
1732
1733 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1734 self.use_auto_surround = auto_surround;
1735 }
1736
1737 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1738 self.auto_replace_emoji_shortcode = auto_replace;
1739 }
1740
1741 pub fn toggle_inline_completions(
1742 &mut self,
1743 _: &ToggleInlineCompletions,
1744 cx: &mut ViewContext<Self>,
1745 ) {
1746 if self.show_inline_completions_override.is_some() {
1747 self.set_show_inline_completions(None, cx);
1748 } else {
1749 let cursor = self.selections.newest_anchor().head();
1750 if let Some((buffer, cursor_buffer_position)) =
1751 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1752 {
1753 let show_inline_completions =
1754 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
1755 self.set_show_inline_completions(Some(show_inline_completions), cx);
1756 }
1757 }
1758 }
1759
1760 pub fn set_show_inline_completions(
1761 &mut self,
1762 show_inline_completions: Option<bool>,
1763 cx: &mut ViewContext<Self>,
1764 ) {
1765 self.show_inline_completions_override = show_inline_completions;
1766 self.refresh_inline_completion(false, true, cx);
1767 }
1768
1769 fn should_show_inline_completions(
1770 &self,
1771 buffer: &Model<Buffer>,
1772 buffer_position: language::Anchor,
1773 cx: &AppContext,
1774 ) -> bool {
1775 if !self.snippet_stack.is_empty() {
1776 return false;
1777 }
1778
1779 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
1780 return false;
1781 }
1782
1783 if let Some(provider) = self.inline_completion_provider() {
1784 if let Some(show_inline_completions) = self.show_inline_completions_override {
1785 show_inline_completions
1786 } else {
1787 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
1788 }
1789 } else {
1790 false
1791 }
1792 }
1793
1794 fn inline_completions_disabled_in_scope(
1795 &self,
1796 buffer: &Model<Buffer>,
1797 buffer_position: language::Anchor,
1798 cx: &AppContext,
1799 ) -> bool {
1800 let snapshot = buffer.read(cx).snapshot();
1801 let settings = snapshot.settings_at(buffer_position, cx);
1802
1803 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1804 return false;
1805 };
1806
1807 scope.override_name().map_or(false, |scope_name| {
1808 settings
1809 .inline_completions_disabled_in
1810 .iter()
1811 .any(|s| s == scope_name)
1812 })
1813 }
1814
1815 pub fn set_use_modal_editing(&mut self, to: bool) {
1816 self.use_modal_editing = to;
1817 }
1818
1819 pub fn use_modal_editing(&self) -> bool {
1820 self.use_modal_editing
1821 }
1822
1823 fn selections_did_change(
1824 &mut self,
1825 local: bool,
1826 old_cursor_position: &Anchor,
1827 show_completions: bool,
1828 cx: &mut ViewContext<Self>,
1829 ) {
1830 cx.invalidate_character_coordinates();
1831
1832 // Copy selections to primary selection buffer
1833 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1834 if local {
1835 let selections = self.selections.all::<usize>(cx);
1836 let buffer_handle = self.buffer.read(cx).read(cx);
1837
1838 let mut text = String::new();
1839 for (index, selection) in selections.iter().enumerate() {
1840 let text_for_selection = buffer_handle
1841 .text_for_range(selection.start..selection.end)
1842 .collect::<String>();
1843
1844 text.push_str(&text_for_selection);
1845 if index != selections.len() - 1 {
1846 text.push('\n');
1847 }
1848 }
1849
1850 if !text.is_empty() {
1851 cx.write_to_primary(ClipboardItem::new_string(text));
1852 }
1853 }
1854
1855 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
1856 self.buffer.update(cx, |buffer, cx| {
1857 buffer.set_active_selections(
1858 &self.selections.disjoint_anchors(),
1859 self.selections.line_mode,
1860 self.cursor_shape,
1861 cx,
1862 )
1863 });
1864 }
1865 let display_map = self
1866 .display_map
1867 .update(cx, |display_map, cx| display_map.snapshot(cx));
1868 let buffer = &display_map.buffer_snapshot;
1869 self.add_selections_state = None;
1870 self.select_next_state = None;
1871 self.select_prev_state = None;
1872 self.select_larger_syntax_node_stack.clear();
1873 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
1874 self.snippet_stack
1875 .invalidate(&self.selections.disjoint_anchors(), buffer);
1876 self.take_rename(false, cx);
1877
1878 let new_cursor_position = self.selections.newest_anchor().head();
1879
1880 self.push_to_nav_history(
1881 *old_cursor_position,
1882 Some(new_cursor_position.to_point(buffer)),
1883 cx,
1884 );
1885
1886 if local {
1887 let new_cursor_position = self.selections.newest_anchor().head();
1888 let mut context_menu = self.context_menu.borrow_mut();
1889 let completion_menu = match context_menu.as_ref() {
1890 Some(CodeContextMenu::Completions(menu)) => Some(menu),
1891 _ => {
1892 *context_menu = None;
1893 None
1894 }
1895 };
1896
1897 if let Some(completion_menu) = completion_menu {
1898 let cursor_position = new_cursor_position.to_offset(buffer);
1899 let (word_range, kind) =
1900 buffer.surrounding_word(completion_menu.initial_position, true);
1901 if kind == Some(CharKind::Word)
1902 && word_range.to_inclusive().contains(&cursor_position)
1903 {
1904 let mut completion_menu = completion_menu.clone();
1905 drop(context_menu);
1906
1907 let query = Self::completion_query(buffer, cursor_position);
1908 cx.spawn(move |this, mut cx| async move {
1909 completion_menu
1910 .filter(query.as_deref(), cx.background_executor().clone())
1911 .await;
1912
1913 this.update(&mut cx, |this, cx| {
1914 let mut context_menu = this.context_menu.borrow_mut();
1915 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
1916 else {
1917 return;
1918 };
1919
1920 if menu.id > completion_menu.id {
1921 return;
1922 }
1923
1924 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
1925 drop(context_menu);
1926 cx.notify();
1927 })
1928 })
1929 .detach();
1930
1931 if show_completions {
1932 self.show_completions(&ShowCompletions { trigger: None }, cx);
1933 }
1934 } else {
1935 drop(context_menu);
1936 self.hide_context_menu(cx);
1937 }
1938 } else {
1939 drop(context_menu);
1940 }
1941
1942 hide_hover(self, cx);
1943
1944 if old_cursor_position.to_display_point(&display_map).row()
1945 != new_cursor_position.to_display_point(&display_map).row()
1946 {
1947 self.available_code_actions.take();
1948 }
1949 self.refresh_code_actions(cx);
1950 self.refresh_document_highlights(cx);
1951 refresh_matching_bracket_highlights(self, cx);
1952 self.update_visible_inline_completion(cx);
1953 linked_editing_ranges::refresh_linked_ranges(self, cx);
1954 if self.git_blame_inline_enabled {
1955 self.start_inline_blame_timer(cx);
1956 }
1957 }
1958
1959 self.blink_manager.update(cx, BlinkManager::pause_blinking);
1960 cx.emit(EditorEvent::SelectionsChanged { local });
1961
1962 if self.selections.disjoint_anchors().len() == 1 {
1963 cx.emit(SearchEvent::ActiveMatchChanged)
1964 }
1965 cx.notify();
1966 }
1967
1968 pub fn change_selections<R>(
1969 &mut self,
1970 autoscroll: Option<Autoscroll>,
1971 cx: &mut ViewContext<Self>,
1972 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
1973 ) -> R {
1974 self.change_selections_inner(autoscroll, true, cx, change)
1975 }
1976
1977 pub fn change_selections_inner<R>(
1978 &mut self,
1979 autoscroll: Option<Autoscroll>,
1980 request_completions: bool,
1981 cx: &mut ViewContext<Self>,
1982 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
1983 ) -> R {
1984 let old_cursor_position = self.selections.newest_anchor().head();
1985 self.push_to_selection_history();
1986
1987 let (changed, result) = self.selections.change_with(cx, change);
1988
1989 if changed {
1990 if let Some(autoscroll) = autoscroll {
1991 self.request_autoscroll(autoscroll, cx);
1992 }
1993 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
1994
1995 if self.should_open_signature_help_automatically(
1996 &old_cursor_position,
1997 self.signature_help_state.backspace_pressed(),
1998 cx,
1999 ) {
2000 self.show_signature_help(&ShowSignatureHelp, cx);
2001 }
2002 self.signature_help_state.set_backspace_pressed(false);
2003 }
2004
2005 result
2006 }
2007
2008 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2009 where
2010 I: IntoIterator<Item = (Range<S>, T)>,
2011 S: ToOffset,
2012 T: Into<Arc<str>>,
2013 {
2014 if self.read_only(cx) {
2015 return;
2016 }
2017
2018 self.buffer
2019 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2020 }
2021
2022 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2023 where
2024 I: IntoIterator<Item = (Range<S>, T)>,
2025 S: ToOffset,
2026 T: Into<Arc<str>>,
2027 {
2028 if self.read_only(cx) {
2029 return;
2030 }
2031
2032 self.buffer.update(cx, |buffer, cx| {
2033 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2034 });
2035 }
2036
2037 pub fn edit_with_block_indent<I, S, T>(
2038 &mut self,
2039 edits: I,
2040 original_indent_columns: Vec<u32>,
2041 cx: &mut ViewContext<Self>,
2042 ) where
2043 I: IntoIterator<Item = (Range<S>, T)>,
2044 S: ToOffset,
2045 T: Into<Arc<str>>,
2046 {
2047 if self.read_only(cx) {
2048 return;
2049 }
2050
2051 self.buffer.update(cx, |buffer, cx| {
2052 buffer.edit(
2053 edits,
2054 Some(AutoindentMode::Block {
2055 original_indent_columns,
2056 }),
2057 cx,
2058 )
2059 });
2060 }
2061
2062 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2063 self.hide_context_menu(cx);
2064
2065 match phase {
2066 SelectPhase::Begin {
2067 position,
2068 add,
2069 click_count,
2070 } => self.begin_selection(position, add, click_count, cx),
2071 SelectPhase::BeginColumnar {
2072 position,
2073 goal_column,
2074 reset,
2075 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2076 SelectPhase::Extend {
2077 position,
2078 click_count,
2079 } => self.extend_selection(position, click_count, cx),
2080 SelectPhase::Update {
2081 position,
2082 goal_column,
2083 scroll_delta,
2084 } => self.update_selection(position, goal_column, scroll_delta, cx),
2085 SelectPhase::End => self.end_selection(cx),
2086 }
2087 }
2088
2089 fn extend_selection(
2090 &mut self,
2091 position: DisplayPoint,
2092 click_count: usize,
2093 cx: &mut ViewContext<Self>,
2094 ) {
2095 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2096 let tail = self.selections.newest::<usize>(cx).tail();
2097 self.begin_selection(position, false, click_count, cx);
2098
2099 let position = position.to_offset(&display_map, Bias::Left);
2100 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2101
2102 let mut pending_selection = self
2103 .selections
2104 .pending_anchor()
2105 .expect("extend_selection not called with pending selection");
2106 if position >= tail {
2107 pending_selection.start = tail_anchor;
2108 } else {
2109 pending_selection.end = tail_anchor;
2110 pending_selection.reversed = true;
2111 }
2112
2113 let mut pending_mode = self.selections.pending_mode().unwrap();
2114 match &mut pending_mode {
2115 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2116 _ => {}
2117 }
2118
2119 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2120 s.set_pending(pending_selection, pending_mode)
2121 });
2122 }
2123
2124 fn begin_selection(
2125 &mut self,
2126 position: DisplayPoint,
2127 add: bool,
2128 click_count: usize,
2129 cx: &mut ViewContext<Self>,
2130 ) {
2131 if !self.focus_handle.is_focused(cx) {
2132 self.last_focused_descendant = None;
2133 cx.focus(&self.focus_handle);
2134 }
2135
2136 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2137 let buffer = &display_map.buffer_snapshot;
2138 let newest_selection = self.selections.newest_anchor().clone();
2139 let position = display_map.clip_point(position, Bias::Left);
2140
2141 let start;
2142 let end;
2143 let mode;
2144 let mut auto_scroll;
2145 match click_count {
2146 1 => {
2147 start = buffer.anchor_before(position.to_point(&display_map));
2148 end = start;
2149 mode = SelectMode::Character;
2150 auto_scroll = true;
2151 }
2152 2 => {
2153 let range = movement::surrounding_word(&display_map, position);
2154 start = buffer.anchor_before(range.start.to_point(&display_map));
2155 end = buffer.anchor_before(range.end.to_point(&display_map));
2156 mode = SelectMode::Word(start..end);
2157 auto_scroll = true;
2158 }
2159 3 => {
2160 let position = display_map
2161 .clip_point(position, Bias::Left)
2162 .to_point(&display_map);
2163 let line_start = display_map.prev_line_boundary(position).0;
2164 let next_line_start = buffer.clip_point(
2165 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2166 Bias::Left,
2167 );
2168 start = buffer.anchor_before(line_start);
2169 end = buffer.anchor_before(next_line_start);
2170 mode = SelectMode::Line(start..end);
2171 auto_scroll = true;
2172 }
2173 _ => {
2174 start = buffer.anchor_before(0);
2175 end = buffer.anchor_before(buffer.len());
2176 mode = SelectMode::All;
2177 auto_scroll = false;
2178 }
2179 }
2180 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2181
2182 let point_to_delete: Option<usize> = {
2183 let selected_points: Vec<Selection<Point>> =
2184 self.selections.disjoint_in_range(start..end, cx);
2185
2186 if !add || click_count > 1 {
2187 None
2188 } else if !selected_points.is_empty() {
2189 Some(selected_points[0].id)
2190 } else {
2191 let clicked_point_already_selected =
2192 self.selections.disjoint.iter().find(|selection| {
2193 selection.start.to_point(buffer) == start.to_point(buffer)
2194 || selection.end.to_point(buffer) == end.to_point(buffer)
2195 });
2196
2197 clicked_point_already_selected.map(|selection| selection.id)
2198 }
2199 };
2200
2201 let selections_count = self.selections.count();
2202
2203 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2204 if let Some(point_to_delete) = point_to_delete {
2205 s.delete(point_to_delete);
2206
2207 if selections_count == 1 {
2208 s.set_pending_anchor_range(start..end, mode);
2209 }
2210 } else {
2211 if !add {
2212 s.clear_disjoint();
2213 } else if click_count > 1 {
2214 s.delete(newest_selection.id)
2215 }
2216
2217 s.set_pending_anchor_range(start..end, mode);
2218 }
2219 });
2220 }
2221
2222 fn begin_columnar_selection(
2223 &mut self,
2224 position: DisplayPoint,
2225 goal_column: u32,
2226 reset: bool,
2227 cx: &mut ViewContext<Self>,
2228 ) {
2229 if !self.focus_handle.is_focused(cx) {
2230 self.last_focused_descendant = None;
2231 cx.focus(&self.focus_handle);
2232 }
2233
2234 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2235
2236 if reset {
2237 let pointer_position = display_map
2238 .buffer_snapshot
2239 .anchor_before(position.to_point(&display_map));
2240
2241 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2242 s.clear_disjoint();
2243 s.set_pending_anchor_range(
2244 pointer_position..pointer_position,
2245 SelectMode::Character,
2246 );
2247 });
2248 }
2249
2250 let tail = self.selections.newest::<Point>(cx).tail();
2251 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2252
2253 if !reset {
2254 self.select_columns(
2255 tail.to_display_point(&display_map),
2256 position,
2257 goal_column,
2258 &display_map,
2259 cx,
2260 );
2261 }
2262 }
2263
2264 fn update_selection(
2265 &mut self,
2266 position: DisplayPoint,
2267 goal_column: u32,
2268 scroll_delta: gpui::Point<f32>,
2269 cx: &mut ViewContext<Self>,
2270 ) {
2271 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2272
2273 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2274 let tail = tail.to_display_point(&display_map);
2275 self.select_columns(tail, position, goal_column, &display_map, cx);
2276 } else if let Some(mut pending) = self.selections.pending_anchor() {
2277 let buffer = self.buffer.read(cx).snapshot(cx);
2278 let head;
2279 let tail;
2280 let mode = self.selections.pending_mode().unwrap();
2281 match &mode {
2282 SelectMode::Character => {
2283 head = position.to_point(&display_map);
2284 tail = pending.tail().to_point(&buffer);
2285 }
2286 SelectMode::Word(original_range) => {
2287 let original_display_range = original_range.start.to_display_point(&display_map)
2288 ..original_range.end.to_display_point(&display_map);
2289 let original_buffer_range = original_display_range.start.to_point(&display_map)
2290 ..original_display_range.end.to_point(&display_map);
2291 if movement::is_inside_word(&display_map, position)
2292 || original_display_range.contains(&position)
2293 {
2294 let word_range = movement::surrounding_word(&display_map, position);
2295 if word_range.start < original_display_range.start {
2296 head = word_range.start.to_point(&display_map);
2297 } else {
2298 head = word_range.end.to_point(&display_map);
2299 }
2300 } else {
2301 head = position.to_point(&display_map);
2302 }
2303
2304 if head <= original_buffer_range.start {
2305 tail = original_buffer_range.end;
2306 } else {
2307 tail = original_buffer_range.start;
2308 }
2309 }
2310 SelectMode::Line(original_range) => {
2311 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2312
2313 let position = display_map
2314 .clip_point(position, Bias::Left)
2315 .to_point(&display_map);
2316 let line_start = display_map.prev_line_boundary(position).0;
2317 let next_line_start = buffer.clip_point(
2318 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2319 Bias::Left,
2320 );
2321
2322 if line_start < original_range.start {
2323 head = line_start
2324 } else {
2325 head = next_line_start
2326 }
2327
2328 if head <= original_range.start {
2329 tail = original_range.end;
2330 } else {
2331 tail = original_range.start;
2332 }
2333 }
2334 SelectMode::All => {
2335 return;
2336 }
2337 };
2338
2339 if head < tail {
2340 pending.start = buffer.anchor_before(head);
2341 pending.end = buffer.anchor_before(tail);
2342 pending.reversed = true;
2343 } else {
2344 pending.start = buffer.anchor_before(tail);
2345 pending.end = buffer.anchor_before(head);
2346 pending.reversed = false;
2347 }
2348
2349 self.change_selections(None, cx, |s| {
2350 s.set_pending(pending, mode);
2351 });
2352 } else {
2353 log::error!("update_selection dispatched with no pending selection");
2354 return;
2355 }
2356
2357 self.apply_scroll_delta(scroll_delta, cx);
2358 cx.notify();
2359 }
2360
2361 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2362 self.columnar_selection_tail.take();
2363 if self.selections.pending_anchor().is_some() {
2364 let selections = self.selections.all::<usize>(cx);
2365 self.change_selections(None, cx, |s| {
2366 s.select(selections);
2367 s.clear_pending();
2368 });
2369 }
2370 }
2371
2372 fn select_columns(
2373 &mut self,
2374 tail: DisplayPoint,
2375 head: DisplayPoint,
2376 goal_column: u32,
2377 display_map: &DisplaySnapshot,
2378 cx: &mut ViewContext<Self>,
2379 ) {
2380 let start_row = cmp::min(tail.row(), head.row());
2381 let end_row = cmp::max(tail.row(), head.row());
2382 let start_column = cmp::min(tail.column(), goal_column);
2383 let end_column = cmp::max(tail.column(), goal_column);
2384 let reversed = start_column < tail.column();
2385
2386 let selection_ranges = (start_row.0..=end_row.0)
2387 .map(DisplayRow)
2388 .filter_map(|row| {
2389 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2390 let start = display_map
2391 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2392 .to_point(display_map);
2393 let end = display_map
2394 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2395 .to_point(display_map);
2396 if reversed {
2397 Some(end..start)
2398 } else {
2399 Some(start..end)
2400 }
2401 } else {
2402 None
2403 }
2404 })
2405 .collect::<Vec<_>>();
2406
2407 self.change_selections(None, cx, |s| {
2408 s.select_ranges(selection_ranges);
2409 });
2410 cx.notify();
2411 }
2412
2413 pub fn has_pending_nonempty_selection(&self) -> bool {
2414 let pending_nonempty_selection = match self.selections.pending_anchor() {
2415 Some(Selection { start, end, .. }) => start != end,
2416 None => false,
2417 };
2418
2419 pending_nonempty_selection
2420 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2421 }
2422
2423 pub fn has_pending_selection(&self) -> bool {
2424 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2425 }
2426
2427 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2428 if self.clear_expanded_diff_hunks(cx) {
2429 cx.notify();
2430 return;
2431 }
2432 if self.dismiss_menus_and_popups(false, true, cx) {
2433 return;
2434 }
2435
2436 if self.mode == EditorMode::Full
2437 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
2438 {
2439 return;
2440 }
2441
2442 cx.propagate();
2443 }
2444
2445 pub fn dismiss_menus_and_popups(
2446 &mut self,
2447 keep_inline_completion: bool,
2448 should_report_inline_completion_event: bool,
2449 cx: &mut ViewContext<Self>,
2450 ) -> bool {
2451 if self.take_rename(false, cx).is_some() {
2452 return true;
2453 }
2454
2455 if hide_hover(self, cx) {
2456 return true;
2457 }
2458
2459 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2460 return true;
2461 }
2462
2463 if self.hide_context_menu(cx).is_some() {
2464 return true;
2465 }
2466
2467 if self.mouse_context_menu.take().is_some() {
2468 return true;
2469 }
2470
2471 if !keep_inline_completion
2472 && self.discard_inline_completion(should_report_inline_completion_event, cx)
2473 {
2474 return true;
2475 }
2476
2477 if self.snippet_stack.pop().is_some() {
2478 return true;
2479 }
2480
2481 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2482 self.dismiss_diagnostics(cx);
2483 return true;
2484 }
2485
2486 false
2487 }
2488
2489 fn linked_editing_ranges_for(
2490 &self,
2491 selection: Range<text::Anchor>,
2492 cx: &AppContext,
2493 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2494 if self.linked_edit_ranges.is_empty() {
2495 return None;
2496 }
2497 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2498 selection.end.buffer_id.and_then(|end_buffer_id| {
2499 if selection.start.buffer_id != Some(end_buffer_id) {
2500 return None;
2501 }
2502 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2503 let snapshot = buffer.read(cx).snapshot();
2504 self.linked_edit_ranges
2505 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2506 .map(|ranges| (ranges, snapshot, buffer))
2507 })?;
2508 use text::ToOffset as TO;
2509 // find offset from the start of current range to current cursor position
2510 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2511
2512 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2513 let start_difference = start_offset - start_byte_offset;
2514 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2515 let end_difference = end_offset - start_byte_offset;
2516 // Current range has associated linked ranges.
2517 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2518 for range in linked_ranges.iter() {
2519 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2520 let end_offset = start_offset + end_difference;
2521 let start_offset = start_offset + start_difference;
2522 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2523 continue;
2524 }
2525 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
2526 if s.start.buffer_id != selection.start.buffer_id
2527 || s.end.buffer_id != selection.end.buffer_id
2528 {
2529 return false;
2530 }
2531 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2532 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2533 }) {
2534 continue;
2535 }
2536 let start = buffer_snapshot.anchor_after(start_offset);
2537 let end = buffer_snapshot.anchor_after(end_offset);
2538 linked_edits
2539 .entry(buffer.clone())
2540 .or_default()
2541 .push(start..end);
2542 }
2543 Some(linked_edits)
2544 }
2545
2546 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2547 let text: Arc<str> = text.into();
2548
2549 if self.read_only(cx) {
2550 return;
2551 }
2552
2553 let selections = self.selections.all_adjusted(cx);
2554 let mut bracket_inserted = false;
2555 let mut edits = Vec::new();
2556 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2557 let mut new_selections = Vec::with_capacity(selections.len());
2558 let mut new_autoclose_regions = Vec::new();
2559 let snapshot = self.buffer.read(cx).read(cx);
2560
2561 for (selection, autoclose_region) in
2562 self.selections_with_autoclose_regions(selections, &snapshot)
2563 {
2564 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2565 // Determine if the inserted text matches the opening or closing
2566 // bracket of any of this language's bracket pairs.
2567 let mut bracket_pair = None;
2568 let mut is_bracket_pair_start = false;
2569 let mut is_bracket_pair_end = false;
2570 if !text.is_empty() {
2571 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2572 // and they are removing the character that triggered IME popup.
2573 for (pair, enabled) in scope.brackets() {
2574 if !pair.close && !pair.surround {
2575 continue;
2576 }
2577
2578 if enabled && pair.start.ends_with(text.as_ref()) {
2579 let prefix_len = pair.start.len() - text.len();
2580 let preceding_text_matches_prefix = prefix_len == 0
2581 || (selection.start.column >= (prefix_len as u32)
2582 && snapshot.contains_str_at(
2583 Point::new(
2584 selection.start.row,
2585 selection.start.column - (prefix_len as u32),
2586 ),
2587 &pair.start[..prefix_len],
2588 ));
2589 if preceding_text_matches_prefix {
2590 bracket_pair = Some(pair.clone());
2591 is_bracket_pair_start = true;
2592 break;
2593 }
2594 }
2595 if pair.end.as_str() == text.as_ref() {
2596 bracket_pair = Some(pair.clone());
2597 is_bracket_pair_end = true;
2598 break;
2599 }
2600 }
2601 }
2602
2603 if let Some(bracket_pair) = bracket_pair {
2604 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2605 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2606 let auto_surround =
2607 self.use_auto_surround && snapshot_settings.use_auto_surround;
2608 if selection.is_empty() {
2609 if is_bracket_pair_start {
2610 // If the inserted text is a suffix of an opening bracket and the
2611 // selection is preceded by the rest of the opening bracket, then
2612 // insert the closing bracket.
2613 let following_text_allows_autoclose = snapshot
2614 .chars_at(selection.start)
2615 .next()
2616 .map_or(true, |c| scope.should_autoclose_before(c));
2617
2618 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2619 && bracket_pair.start.len() == 1
2620 {
2621 let target = bracket_pair.start.chars().next().unwrap();
2622 let current_line_count = snapshot
2623 .reversed_chars_at(selection.start)
2624 .take_while(|&c| c != '\n')
2625 .filter(|&c| c == target)
2626 .count();
2627 current_line_count % 2 == 1
2628 } else {
2629 false
2630 };
2631
2632 if autoclose
2633 && bracket_pair.close
2634 && following_text_allows_autoclose
2635 && !is_closing_quote
2636 {
2637 let anchor = snapshot.anchor_before(selection.end);
2638 new_selections.push((selection.map(|_| anchor), text.len()));
2639 new_autoclose_regions.push((
2640 anchor,
2641 text.len(),
2642 selection.id,
2643 bracket_pair.clone(),
2644 ));
2645 edits.push((
2646 selection.range(),
2647 format!("{}{}", text, bracket_pair.end).into(),
2648 ));
2649 bracket_inserted = true;
2650 continue;
2651 }
2652 }
2653
2654 if let Some(region) = autoclose_region {
2655 // If the selection is followed by an auto-inserted closing bracket,
2656 // then don't insert that closing bracket again; just move the selection
2657 // past the closing bracket.
2658 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2659 && text.as_ref() == region.pair.end.as_str();
2660 if should_skip {
2661 let anchor = snapshot.anchor_after(selection.end);
2662 new_selections
2663 .push((selection.map(|_| anchor), region.pair.end.len()));
2664 continue;
2665 }
2666 }
2667
2668 let always_treat_brackets_as_autoclosed = snapshot
2669 .settings_at(selection.start, cx)
2670 .always_treat_brackets_as_autoclosed;
2671 if always_treat_brackets_as_autoclosed
2672 && is_bracket_pair_end
2673 && snapshot.contains_str_at(selection.end, text.as_ref())
2674 {
2675 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2676 // and the inserted text is a closing bracket and the selection is followed
2677 // by the closing bracket then move the selection past the closing bracket.
2678 let anchor = snapshot.anchor_after(selection.end);
2679 new_selections.push((selection.map(|_| anchor), text.len()));
2680 continue;
2681 }
2682 }
2683 // If an opening bracket is 1 character long and is typed while
2684 // text is selected, then surround that text with the bracket pair.
2685 else if auto_surround
2686 && bracket_pair.surround
2687 && is_bracket_pair_start
2688 && bracket_pair.start.chars().count() == 1
2689 {
2690 edits.push((selection.start..selection.start, text.clone()));
2691 edits.push((
2692 selection.end..selection.end,
2693 bracket_pair.end.as_str().into(),
2694 ));
2695 bracket_inserted = true;
2696 new_selections.push((
2697 Selection {
2698 id: selection.id,
2699 start: snapshot.anchor_after(selection.start),
2700 end: snapshot.anchor_before(selection.end),
2701 reversed: selection.reversed,
2702 goal: selection.goal,
2703 },
2704 0,
2705 ));
2706 continue;
2707 }
2708 }
2709 }
2710
2711 if self.auto_replace_emoji_shortcode
2712 && selection.is_empty()
2713 && text.as_ref().ends_with(':')
2714 {
2715 if let Some(possible_emoji_short_code) =
2716 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2717 {
2718 if !possible_emoji_short_code.is_empty() {
2719 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2720 let emoji_shortcode_start = Point::new(
2721 selection.start.row,
2722 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2723 );
2724
2725 // Remove shortcode from buffer
2726 edits.push((
2727 emoji_shortcode_start..selection.start,
2728 "".to_string().into(),
2729 ));
2730 new_selections.push((
2731 Selection {
2732 id: selection.id,
2733 start: snapshot.anchor_after(emoji_shortcode_start),
2734 end: snapshot.anchor_before(selection.start),
2735 reversed: selection.reversed,
2736 goal: selection.goal,
2737 },
2738 0,
2739 ));
2740
2741 // Insert emoji
2742 let selection_start_anchor = snapshot.anchor_after(selection.start);
2743 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2744 edits.push((selection.start..selection.end, emoji.to_string().into()));
2745
2746 continue;
2747 }
2748 }
2749 }
2750 }
2751
2752 // If not handling any auto-close operation, then just replace the selected
2753 // text with the given input and move the selection to the end of the
2754 // newly inserted text.
2755 let anchor = snapshot.anchor_after(selection.end);
2756 if !self.linked_edit_ranges.is_empty() {
2757 let start_anchor = snapshot.anchor_before(selection.start);
2758
2759 let is_word_char = text.chars().next().map_or(true, |char| {
2760 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2761 classifier.is_word(char)
2762 });
2763
2764 if is_word_char {
2765 if let Some(ranges) = self
2766 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2767 {
2768 for (buffer, edits) in ranges {
2769 linked_edits
2770 .entry(buffer.clone())
2771 .or_default()
2772 .extend(edits.into_iter().map(|range| (range, text.clone())));
2773 }
2774 }
2775 }
2776 }
2777
2778 new_selections.push((selection.map(|_| anchor), 0));
2779 edits.push((selection.start..selection.end, text.clone()));
2780 }
2781
2782 drop(snapshot);
2783
2784 self.transact(cx, |this, cx| {
2785 this.buffer.update(cx, |buffer, cx| {
2786 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2787 });
2788 for (buffer, edits) in linked_edits {
2789 buffer.update(cx, |buffer, cx| {
2790 let snapshot = buffer.snapshot();
2791 let edits = edits
2792 .into_iter()
2793 .map(|(range, text)| {
2794 use text::ToPoint as TP;
2795 let end_point = TP::to_point(&range.end, &snapshot);
2796 let start_point = TP::to_point(&range.start, &snapshot);
2797 (start_point..end_point, text)
2798 })
2799 .sorted_by_key(|(range, _)| range.start)
2800 .collect::<Vec<_>>();
2801 buffer.edit(edits, None, cx);
2802 })
2803 }
2804 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2805 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2806 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2807 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2808 .zip(new_selection_deltas)
2809 .map(|(selection, delta)| Selection {
2810 id: selection.id,
2811 start: selection.start + delta,
2812 end: selection.end + delta,
2813 reversed: selection.reversed,
2814 goal: SelectionGoal::None,
2815 })
2816 .collect::<Vec<_>>();
2817
2818 let mut i = 0;
2819 for (position, delta, selection_id, pair) in new_autoclose_regions {
2820 let position = position.to_offset(&map.buffer_snapshot) + delta;
2821 let start = map.buffer_snapshot.anchor_before(position);
2822 let end = map.buffer_snapshot.anchor_after(position);
2823 while let Some(existing_state) = this.autoclose_regions.get(i) {
2824 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2825 Ordering::Less => i += 1,
2826 Ordering::Greater => break,
2827 Ordering::Equal => {
2828 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2829 Ordering::Less => i += 1,
2830 Ordering::Equal => break,
2831 Ordering::Greater => break,
2832 }
2833 }
2834 }
2835 }
2836 this.autoclose_regions.insert(
2837 i,
2838 AutocloseRegion {
2839 selection_id,
2840 range: start..end,
2841 pair,
2842 },
2843 );
2844 }
2845
2846 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
2847 s.select(new_selections)
2848 });
2849
2850 if !bracket_inserted {
2851 if let Some(on_type_format_task) =
2852 this.trigger_on_type_formatting(text.to_string(), cx)
2853 {
2854 on_type_format_task.detach_and_log_err(cx);
2855 }
2856 }
2857
2858 let editor_settings = EditorSettings::get_global(cx);
2859 if bracket_inserted
2860 && (editor_settings.auto_signature_help
2861 || editor_settings.show_signature_help_after_edits)
2862 {
2863 this.show_signature_help(&ShowSignatureHelp, cx);
2864 }
2865
2866 this.trigger_completion_on_input(&text, true, cx);
2867 linked_editing_ranges::refresh_linked_ranges(this, cx);
2868 this.refresh_inline_completion(true, false, cx);
2869 });
2870 }
2871
2872 fn find_possible_emoji_shortcode_at_position(
2873 snapshot: &MultiBufferSnapshot,
2874 position: Point,
2875 ) -> Option<String> {
2876 let mut chars = Vec::new();
2877 let mut found_colon = false;
2878 for char in snapshot.reversed_chars_at(position).take(100) {
2879 // Found a possible emoji shortcode in the middle of the buffer
2880 if found_colon {
2881 if char.is_whitespace() {
2882 chars.reverse();
2883 return Some(chars.iter().collect());
2884 }
2885 // If the previous character is not a whitespace, we are in the middle of a word
2886 // and we only want to complete the shortcode if the word is made up of other emojis
2887 let mut containing_word = String::new();
2888 for ch in snapshot
2889 .reversed_chars_at(position)
2890 .skip(chars.len() + 1)
2891 .take(100)
2892 {
2893 if ch.is_whitespace() {
2894 break;
2895 }
2896 containing_word.push(ch);
2897 }
2898 let containing_word = containing_word.chars().rev().collect::<String>();
2899 if util::word_consists_of_emojis(containing_word.as_str()) {
2900 chars.reverse();
2901 return Some(chars.iter().collect());
2902 }
2903 }
2904
2905 if char.is_whitespace() || !char.is_ascii() {
2906 return None;
2907 }
2908 if char == ':' {
2909 found_colon = true;
2910 } else {
2911 chars.push(char);
2912 }
2913 }
2914 // Found a possible emoji shortcode at the beginning of the buffer
2915 chars.reverse();
2916 Some(chars.iter().collect())
2917 }
2918
2919 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
2920 self.transact(cx, |this, cx| {
2921 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
2922 let selections = this.selections.all::<usize>(cx);
2923 let multi_buffer = this.buffer.read(cx);
2924 let buffer = multi_buffer.snapshot(cx);
2925 selections
2926 .iter()
2927 .map(|selection| {
2928 let start_point = selection.start.to_point(&buffer);
2929 let mut indent =
2930 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
2931 indent.len = cmp::min(indent.len, start_point.column);
2932 let start = selection.start;
2933 let end = selection.end;
2934 let selection_is_empty = start == end;
2935 let language_scope = buffer.language_scope_at(start);
2936 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
2937 &language_scope
2938 {
2939 let leading_whitespace_len = buffer
2940 .reversed_chars_at(start)
2941 .take_while(|c| c.is_whitespace() && *c != '\n')
2942 .map(|c| c.len_utf8())
2943 .sum::<usize>();
2944
2945 let trailing_whitespace_len = buffer
2946 .chars_at(end)
2947 .take_while(|c| c.is_whitespace() && *c != '\n')
2948 .map(|c| c.len_utf8())
2949 .sum::<usize>();
2950
2951 let insert_extra_newline =
2952 language.brackets().any(|(pair, enabled)| {
2953 let pair_start = pair.start.trim_end();
2954 let pair_end = pair.end.trim_start();
2955
2956 enabled
2957 && pair.newline
2958 && buffer.contains_str_at(
2959 end + trailing_whitespace_len,
2960 pair_end,
2961 )
2962 && buffer.contains_str_at(
2963 (start - leading_whitespace_len)
2964 .saturating_sub(pair_start.len()),
2965 pair_start,
2966 )
2967 });
2968
2969 // Comment extension on newline is allowed only for cursor selections
2970 let comment_delimiter = maybe!({
2971 if !selection_is_empty {
2972 return None;
2973 }
2974
2975 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
2976 return None;
2977 }
2978
2979 let delimiters = language.line_comment_prefixes();
2980 let max_len_of_delimiter =
2981 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
2982 let (snapshot, range) =
2983 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
2984
2985 let mut index_of_first_non_whitespace = 0;
2986 let comment_candidate = snapshot
2987 .chars_for_range(range)
2988 .skip_while(|c| {
2989 let should_skip = c.is_whitespace();
2990 if should_skip {
2991 index_of_first_non_whitespace += 1;
2992 }
2993 should_skip
2994 })
2995 .take(max_len_of_delimiter)
2996 .collect::<String>();
2997 let comment_prefix = delimiters.iter().find(|comment_prefix| {
2998 comment_candidate.starts_with(comment_prefix.as_ref())
2999 })?;
3000 let cursor_is_placed_after_comment_marker =
3001 index_of_first_non_whitespace + comment_prefix.len()
3002 <= start_point.column as usize;
3003 if cursor_is_placed_after_comment_marker {
3004 Some(comment_prefix.clone())
3005 } else {
3006 None
3007 }
3008 });
3009 (comment_delimiter, insert_extra_newline)
3010 } else {
3011 (None, false)
3012 };
3013
3014 let capacity_for_delimiter = comment_delimiter
3015 .as_deref()
3016 .map(str::len)
3017 .unwrap_or_default();
3018 let mut new_text =
3019 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3020 new_text.push('\n');
3021 new_text.extend(indent.chars());
3022 if let Some(delimiter) = &comment_delimiter {
3023 new_text.push_str(delimiter);
3024 }
3025 if insert_extra_newline {
3026 new_text = new_text.repeat(2);
3027 }
3028
3029 let anchor = buffer.anchor_after(end);
3030 let new_selection = selection.map(|_| anchor);
3031 (
3032 (start..end, new_text),
3033 (insert_extra_newline, new_selection),
3034 )
3035 })
3036 .unzip()
3037 };
3038
3039 this.edit_with_autoindent(edits, cx);
3040 let buffer = this.buffer.read(cx).snapshot(cx);
3041 let new_selections = selection_fixup_info
3042 .into_iter()
3043 .map(|(extra_newline_inserted, new_selection)| {
3044 let mut cursor = new_selection.end.to_point(&buffer);
3045 if extra_newline_inserted {
3046 cursor.row -= 1;
3047 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3048 }
3049 new_selection.map(|_| cursor)
3050 })
3051 .collect();
3052
3053 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3054 this.refresh_inline_completion(true, false, cx);
3055 });
3056 }
3057
3058 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3059 let buffer = self.buffer.read(cx);
3060 let snapshot = buffer.snapshot(cx);
3061
3062 let mut edits = Vec::new();
3063 let mut rows = Vec::new();
3064
3065 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3066 let cursor = selection.head();
3067 let row = cursor.row;
3068
3069 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3070
3071 let newline = "\n".to_string();
3072 edits.push((start_of_line..start_of_line, newline));
3073
3074 rows.push(row + rows_inserted as u32);
3075 }
3076
3077 self.transact(cx, |editor, cx| {
3078 editor.edit(edits, cx);
3079
3080 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3081 let mut index = 0;
3082 s.move_cursors_with(|map, _, _| {
3083 let row = rows[index];
3084 index += 1;
3085
3086 let point = Point::new(row, 0);
3087 let boundary = map.next_line_boundary(point).1;
3088 let clipped = map.clip_point(boundary, Bias::Left);
3089
3090 (clipped, SelectionGoal::None)
3091 });
3092 });
3093
3094 let mut indent_edits = Vec::new();
3095 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3096 for row in rows {
3097 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3098 for (row, indent) in indents {
3099 if indent.len == 0 {
3100 continue;
3101 }
3102
3103 let text = match indent.kind {
3104 IndentKind::Space => " ".repeat(indent.len as usize),
3105 IndentKind::Tab => "\t".repeat(indent.len as usize),
3106 };
3107 let point = Point::new(row.0, 0);
3108 indent_edits.push((point..point, text));
3109 }
3110 }
3111 editor.edit(indent_edits, cx);
3112 });
3113 }
3114
3115 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3116 let buffer = self.buffer.read(cx);
3117 let snapshot = buffer.snapshot(cx);
3118
3119 let mut edits = Vec::new();
3120 let mut rows = Vec::new();
3121 let mut rows_inserted = 0;
3122
3123 for selection in self.selections.all_adjusted(cx) {
3124 let cursor = selection.head();
3125 let row = cursor.row;
3126
3127 let point = Point::new(row + 1, 0);
3128 let start_of_line = snapshot.clip_point(point, Bias::Left);
3129
3130 let newline = "\n".to_string();
3131 edits.push((start_of_line..start_of_line, newline));
3132
3133 rows_inserted += 1;
3134 rows.push(row + rows_inserted);
3135 }
3136
3137 self.transact(cx, |editor, cx| {
3138 editor.edit(edits, cx);
3139
3140 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3141 let mut index = 0;
3142 s.move_cursors_with(|map, _, _| {
3143 let row = rows[index];
3144 index += 1;
3145
3146 let point = Point::new(row, 0);
3147 let boundary = map.next_line_boundary(point).1;
3148 let clipped = map.clip_point(boundary, Bias::Left);
3149
3150 (clipped, SelectionGoal::None)
3151 });
3152 });
3153
3154 let mut indent_edits = Vec::new();
3155 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3156 for row in rows {
3157 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3158 for (row, indent) in indents {
3159 if indent.len == 0 {
3160 continue;
3161 }
3162
3163 let text = match indent.kind {
3164 IndentKind::Space => " ".repeat(indent.len as usize),
3165 IndentKind::Tab => "\t".repeat(indent.len as usize),
3166 };
3167 let point = Point::new(row.0, 0);
3168 indent_edits.push((point..point, text));
3169 }
3170 }
3171 editor.edit(indent_edits, cx);
3172 });
3173 }
3174
3175 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3176 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3177 original_indent_columns: Vec::new(),
3178 });
3179 self.insert_with_autoindent_mode(text, autoindent, cx);
3180 }
3181
3182 fn insert_with_autoindent_mode(
3183 &mut self,
3184 text: &str,
3185 autoindent_mode: Option<AutoindentMode>,
3186 cx: &mut ViewContext<Self>,
3187 ) {
3188 if self.read_only(cx) {
3189 return;
3190 }
3191
3192 let text: Arc<str> = text.into();
3193 self.transact(cx, |this, cx| {
3194 let old_selections = this.selections.all_adjusted(cx);
3195 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3196 let anchors = {
3197 let snapshot = buffer.read(cx);
3198 old_selections
3199 .iter()
3200 .map(|s| {
3201 let anchor = snapshot.anchor_after(s.head());
3202 s.map(|_| anchor)
3203 })
3204 .collect::<Vec<_>>()
3205 };
3206 buffer.edit(
3207 old_selections
3208 .iter()
3209 .map(|s| (s.start..s.end, text.clone())),
3210 autoindent_mode,
3211 cx,
3212 );
3213 anchors
3214 });
3215
3216 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3217 s.select_anchors(selection_anchors);
3218 })
3219 });
3220 }
3221
3222 fn trigger_completion_on_input(
3223 &mut self,
3224 text: &str,
3225 trigger_in_words: bool,
3226 cx: &mut ViewContext<Self>,
3227 ) {
3228 if self.is_completion_trigger(text, trigger_in_words, cx) {
3229 self.show_completions(
3230 &ShowCompletions {
3231 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3232 },
3233 cx,
3234 );
3235 } else {
3236 self.hide_context_menu(cx);
3237 }
3238 }
3239
3240 fn is_completion_trigger(
3241 &self,
3242 text: &str,
3243 trigger_in_words: bool,
3244 cx: &mut ViewContext<Self>,
3245 ) -> bool {
3246 let position = self.selections.newest_anchor().head();
3247 let multibuffer = self.buffer.read(cx);
3248 let Some(buffer) = position
3249 .buffer_id
3250 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3251 else {
3252 return false;
3253 };
3254
3255 if let Some(completion_provider) = &self.completion_provider {
3256 completion_provider.is_completion_trigger(
3257 &buffer,
3258 position.text_anchor,
3259 text,
3260 trigger_in_words,
3261 cx,
3262 )
3263 } else {
3264 false
3265 }
3266 }
3267
3268 /// If any empty selections is touching the start of its innermost containing autoclose
3269 /// region, expand it to select the brackets.
3270 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3271 let selections = self.selections.all::<usize>(cx);
3272 let buffer = self.buffer.read(cx).read(cx);
3273 let new_selections = self
3274 .selections_with_autoclose_regions(selections, &buffer)
3275 .map(|(mut selection, region)| {
3276 if !selection.is_empty() {
3277 return selection;
3278 }
3279
3280 if let Some(region) = region {
3281 let mut range = region.range.to_offset(&buffer);
3282 if selection.start == range.start && range.start >= region.pair.start.len() {
3283 range.start -= region.pair.start.len();
3284 if buffer.contains_str_at(range.start, ®ion.pair.start)
3285 && buffer.contains_str_at(range.end, ®ion.pair.end)
3286 {
3287 range.end += region.pair.end.len();
3288 selection.start = range.start;
3289 selection.end = range.end;
3290
3291 return selection;
3292 }
3293 }
3294 }
3295
3296 let always_treat_brackets_as_autoclosed = buffer
3297 .settings_at(selection.start, cx)
3298 .always_treat_brackets_as_autoclosed;
3299
3300 if !always_treat_brackets_as_autoclosed {
3301 return selection;
3302 }
3303
3304 if let Some(scope) = buffer.language_scope_at(selection.start) {
3305 for (pair, enabled) in scope.brackets() {
3306 if !enabled || !pair.close {
3307 continue;
3308 }
3309
3310 if buffer.contains_str_at(selection.start, &pair.end) {
3311 let pair_start_len = pair.start.len();
3312 if buffer.contains_str_at(
3313 selection.start.saturating_sub(pair_start_len),
3314 &pair.start,
3315 ) {
3316 selection.start -= pair_start_len;
3317 selection.end += pair.end.len();
3318
3319 return selection;
3320 }
3321 }
3322 }
3323 }
3324
3325 selection
3326 })
3327 .collect();
3328
3329 drop(buffer);
3330 self.change_selections(None, cx, |selections| selections.select(new_selections));
3331 }
3332
3333 /// Iterate the given selections, and for each one, find the smallest surrounding
3334 /// autoclose region. This uses the ordering of the selections and the autoclose
3335 /// regions to avoid repeated comparisons.
3336 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3337 &'a self,
3338 selections: impl IntoIterator<Item = Selection<D>>,
3339 buffer: &'a MultiBufferSnapshot,
3340 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3341 let mut i = 0;
3342 let mut regions = self.autoclose_regions.as_slice();
3343 selections.into_iter().map(move |selection| {
3344 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3345
3346 let mut enclosing = None;
3347 while let Some(pair_state) = regions.get(i) {
3348 if pair_state.range.end.to_offset(buffer) < range.start {
3349 regions = ®ions[i + 1..];
3350 i = 0;
3351 } else if pair_state.range.start.to_offset(buffer) > range.end {
3352 break;
3353 } else {
3354 if pair_state.selection_id == selection.id {
3355 enclosing = Some(pair_state);
3356 }
3357 i += 1;
3358 }
3359 }
3360
3361 (selection, enclosing)
3362 })
3363 }
3364
3365 /// Remove any autoclose regions that no longer contain their selection.
3366 fn invalidate_autoclose_regions(
3367 &mut self,
3368 mut selections: &[Selection<Anchor>],
3369 buffer: &MultiBufferSnapshot,
3370 ) {
3371 self.autoclose_regions.retain(|state| {
3372 let mut i = 0;
3373 while let Some(selection) = selections.get(i) {
3374 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3375 selections = &selections[1..];
3376 continue;
3377 }
3378 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3379 break;
3380 }
3381 if selection.id == state.selection_id {
3382 return true;
3383 } else {
3384 i += 1;
3385 }
3386 }
3387 false
3388 });
3389 }
3390
3391 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3392 let offset = position.to_offset(buffer);
3393 let (word_range, kind) = buffer.surrounding_word(offset, true);
3394 if offset > word_range.start && kind == Some(CharKind::Word) {
3395 Some(
3396 buffer
3397 .text_for_range(word_range.start..offset)
3398 .collect::<String>(),
3399 )
3400 } else {
3401 None
3402 }
3403 }
3404
3405 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3406 self.refresh_inlay_hints(
3407 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3408 cx,
3409 );
3410 }
3411
3412 pub fn inlay_hints_enabled(&self) -> bool {
3413 self.inlay_hint_cache.enabled
3414 }
3415
3416 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3417 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3418 return;
3419 }
3420
3421 let reason_description = reason.description();
3422 let ignore_debounce = matches!(
3423 reason,
3424 InlayHintRefreshReason::SettingsChange(_)
3425 | InlayHintRefreshReason::Toggle(_)
3426 | InlayHintRefreshReason::ExcerptsRemoved(_)
3427 );
3428 let (invalidate_cache, required_languages) = match reason {
3429 InlayHintRefreshReason::Toggle(enabled) => {
3430 self.inlay_hint_cache.enabled = enabled;
3431 if enabled {
3432 (InvalidationStrategy::RefreshRequested, None)
3433 } else {
3434 self.inlay_hint_cache.clear();
3435 self.splice_inlays(
3436 self.visible_inlay_hints(cx)
3437 .iter()
3438 .map(|inlay| inlay.id)
3439 .collect(),
3440 Vec::new(),
3441 cx,
3442 );
3443 return;
3444 }
3445 }
3446 InlayHintRefreshReason::SettingsChange(new_settings) => {
3447 match self.inlay_hint_cache.update_settings(
3448 &self.buffer,
3449 new_settings,
3450 self.visible_inlay_hints(cx),
3451 cx,
3452 ) {
3453 ControlFlow::Break(Some(InlaySplice {
3454 to_remove,
3455 to_insert,
3456 })) => {
3457 self.splice_inlays(to_remove, to_insert, cx);
3458 return;
3459 }
3460 ControlFlow::Break(None) => return,
3461 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3462 }
3463 }
3464 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3465 if let Some(InlaySplice {
3466 to_remove,
3467 to_insert,
3468 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3469 {
3470 self.splice_inlays(to_remove, to_insert, cx);
3471 }
3472 return;
3473 }
3474 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3475 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3476 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3477 }
3478 InlayHintRefreshReason::RefreshRequested => {
3479 (InvalidationStrategy::RefreshRequested, None)
3480 }
3481 };
3482
3483 if let Some(InlaySplice {
3484 to_remove,
3485 to_insert,
3486 }) = self.inlay_hint_cache.spawn_hint_refresh(
3487 reason_description,
3488 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3489 invalidate_cache,
3490 ignore_debounce,
3491 cx,
3492 ) {
3493 self.splice_inlays(to_remove, to_insert, cx);
3494 }
3495 }
3496
3497 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
3498 self.display_map
3499 .read(cx)
3500 .current_inlays()
3501 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3502 .cloned()
3503 .collect()
3504 }
3505
3506 pub fn excerpts_for_inlay_hints_query(
3507 &self,
3508 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3509 cx: &mut ViewContext<Editor>,
3510 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3511 let Some(project) = self.project.as_ref() else {
3512 return HashMap::default();
3513 };
3514 let project = project.read(cx);
3515 let multi_buffer = self.buffer().read(cx);
3516 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3517 let multi_buffer_visible_start = self
3518 .scroll_manager
3519 .anchor()
3520 .anchor
3521 .to_point(&multi_buffer_snapshot);
3522 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3523 multi_buffer_visible_start
3524 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3525 Bias::Left,
3526 );
3527 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3528 multi_buffer
3529 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
3530 .into_iter()
3531 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3532 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
3533 let buffer = buffer_handle.read(cx);
3534 let buffer_file = project::File::from_dyn(buffer.file())?;
3535 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3536 let worktree_entry = buffer_worktree
3537 .read(cx)
3538 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3539 if worktree_entry.is_ignored {
3540 return None;
3541 }
3542
3543 let language = buffer.language()?;
3544 if let Some(restrict_to_languages) = restrict_to_languages {
3545 if !restrict_to_languages.contains(language) {
3546 return None;
3547 }
3548 }
3549 Some((
3550 excerpt_id,
3551 (
3552 buffer_handle,
3553 buffer.version().clone(),
3554 excerpt_visible_range,
3555 ),
3556 ))
3557 })
3558 .collect()
3559 }
3560
3561 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3562 TextLayoutDetails {
3563 text_system: cx.text_system().clone(),
3564 editor_style: self.style.clone().unwrap(),
3565 rem_size: cx.rem_size(),
3566 scroll_anchor: self.scroll_manager.anchor(),
3567 visible_rows: self.visible_line_count(),
3568 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3569 }
3570 }
3571
3572 fn splice_inlays(
3573 &self,
3574 to_remove: Vec<InlayId>,
3575 to_insert: Vec<Inlay>,
3576 cx: &mut ViewContext<Self>,
3577 ) {
3578 self.display_map.update(cx, |display_map, cx| {
3579 display_map.splice_inlays(to_remove, to_insert, cx)
3580 });
3581 cx.notify();
3582 }
3583
3584 fn trigger_on_type_formatting(
3585 &self,
3586 input: String,
3587 cx: &mut ViewContext<Self>,
3588 ) -> Option<Task<Result<()>>> {
3589 if input.len() != 1 {
3590 return None;
3591 }
3592
3593 let project = self.project.as_ref()?;
3594 let position = self.selections.newest_anchor().head();
3595 let (buffer, buffer_position) = self
3596 .buffer
3597 .read(cx)
3598 .text_anchor_for_position(position, cx)?;
3599
3600 let settings = language_settings::language_settings(
3601 buffer
3602 .read(cx)
3603 .language_at(buffer_position)
3604 .map(|l| l.name()),
3605 buffer.read(cx).file(),
3606 cx,
3607 );
3608 if !settings.use_on_type_format {
3609 return None;
3610 }
3611
3612 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3613 // hence we do LSP request & edit on host side only — add formats to host's history.
3614 let push_to_lsp_host_history = true;
3615 // If this is not the host, append its history with new edits.
3616 let push_to_client_history = project.read(cx).is_via_collab();
3617
3618 let on_type_formatting = project.update(cx, |project, cx| {
3619 project.on_type_format(
3620 buffer.clone(),
3621 buffer_position,
3622 input,
3623 push_to_lsp_host_history,
3624 cx,
3625 )
3626 });
3627 Some(cx.spawn(|editor, mut cx| async move {
3628 if let Some(transaction) = on_type_formatting.await? {
3629 if push_to_client_history {
3630 buffer
3631 .update(&mut cx, |buffer, _| {
3632 buffer.push_transaction(transaction, Instant::now());
3633 })
3634 .ok();
3635 }
3636 editor.update(&mut cx, |editor, cx| {
3637 editor.refresh_document_highlights(cx);
3638 })?;
3639 }
3640 Ok(())
3641 }))
3642 }
3643
3644 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
3645 if self.pending_rename.is_some() {
3646 return;
3647 }
3648
3649 let Some(provider) = self.completion_provider.as_ref() else {
3650 return;
3651 };
3652
3653 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3654 return;
3655 }
3656
3657 let position = self.selections.newest_anchor().head();
3658 let (buffer, buffer_position) =
3659 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3660 output
3661 } else {
3662 return;
3663 };
3664 let show_completion_documentation = buffer
3665 .read(cx)
3666 .snapshot()
3667 .settings_at(buffer_position, cx)
3668 .show_completion_documentation;
3669
3670 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3671
3672 let aside_was_displayed = match self.context_menu.borrow().deref() {
3673 Some(CodeContextMenu::Completions(menu)) => menu.aside_was_displayed.get(),
3674 _ => false,
3675 };
3676 let trigger_kind = match &options.trigger {
3677 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3678 CompletionTriggerKind::TRIGGER_CHARACTER
3679 }
3680 _ => CompletionTriggerKind::INVOKED,
3681 };
3682 let completion_context = CompletionContext {
3683 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3684 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3685 Some(String::from(trigger))
3686 } else {
3687 None
3688 }
3689 }),
3690 trigger_kind,
3691 };
3692 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
3693 let sort_completions = provider.sort_completions();
3694
3695 let id = post_inc(&mut self.next_completion_id);
3696 let task = cx.spawn(|editor, mut cx| {
3697 async move {
3698 editor.update(&mut cx, |this, _| {
3699 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3700 })?;
3701 let completions = completions.await.log_err();
3702 let menu = if let Some(completions) = completions {
3703 let mut menu = CompletionsMenu::new(
3704 id,
3705 sort_completions,
3706 show_completion_documentation,
3707 position,
3708 buffer.clone(),
3709 completions.into(),
3710 aside_was_displayed,
3711 );
3712 menu.filter(query.as_deref(), cx.background_executor().clone())
3713 .await;
3714
3715 if menu.matches.is_empty() {
3716 None
3717 } else {
3718 Some(menu)
3719 }
3720 } else {
3721 None
3722 };
3723
3724 editor.update(&mut cx, |editor, cx| {
3725 let mut context_menu = editor.context_menu.borrow_mut();
3726 match context_menu.as_ref() {
3727 None => {}
3728 Some(CodeContextMenu::Completions(prev_menu)) => {
3729 if prev_menu.id > id {
3730 return;
3731 }
3732 }
3733 _ => return,
3734 }
3735
3736 if editor.focus_handle.is_focused(cx) && menu.is_some() {
3737 let mut menu = menu.unwrap();
3738 menu.resolve_selected_completion(editor.completion_provider.as_deref(), cx);
3739 *context_menu = Some(CodeContextMenu::Completions(menu));
3740 drop(context_menu);
3741 cx.notify();
3742 } else if editor.completion_tasks.len() <= 1 {
3743 // If there are no more completion tasks and the last menu was
3744 // empty, we should hide it. If it was already hidden, we should
3745 // also show the copilot completion when available.
3746 drop(context_menu);
3747 editor.hide_context_menu(cx);
3748 }
3749 })?;
3750
3751 Ok::<_, anyhow::Error>(())
3752 }
3753 .log_err()
3754 });
3755
3756 self.completion_tasks.push((id, task));
3757 }
3758
3759 pub fn confirm_completion(
3760 &mut self,
3761 action: &ConfirmCompletion,
3762 cx: &mut ViewContext<Self>,
3763 ) -> Option<Task<Result<()>>> {
3764 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
3765 }
3766
3767 pub fn compose_completion(
3768 &mut self,
3769 action: &ComposeCompletion,
3770 cx: &mut ViewContext<Self>,
3771 ) -> Option<Task<Result<()>>> {
3772 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
3773 }
3774
3775 fn do_completion(
3776 &mut self,
3777 item_ix: Option<usize>,
3778 intent: CompletionIntent,
3779 cx: &mut ViewContext<Editor>,
3780 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3781 use language::ToOffset as _;
3782
3783 self.discard_inline_completion(true, cx);
3784 let completions_menu =
3785 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3786 menu
3787 } else {
3788 return None;
3789 };
3790
3791 let mat = completions_menu
3792 .matches
3793 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
3794 let buffer_handle = completions_menu.buffer;
3795 let completions = completions_menu.completions.borrow_mut();
3796 let completion = completions.get(mat.candidate_id)?;
3797 cx.stop_propagation();
3798
3799 let snippet;
3800 let text;
3801
3802 if completion.is_snippet() {
3803 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3804 text = snippet.as_ref().unwrap().text.clone();
3805 } else {
3806 snippet = None;
3807 text = completion.new_text.clone();
3808 };
3809 let selections = self.selections.all::<usize>(cx);
3810 let buffer = buffer_handle.read(cx);
3811 let old_range = completion.old_range.to_offset(buffer);
3812 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3813
3814 let newest_selection = self.selections.newest_anchor();
3815 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3816 return None;
3817 }
3818
3819 let lookbehind = newest_selection
3820 .start
3821 .text_anchor
3822 .to_offset(buffer)
3823 .saturating_sub(old_range.start);
3824 let lookahead = old_range
3825 .end
3826 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3827 let mut common_prefix_len = old_text
3828 .bytes()
3829 .zip(text.bytes())
3830 .take_while(|(a, b)| a == b)
3831 .count();
3832
3833 let snapshot = self.buffer.read(cx).snapshot(cx);
3834 let mut range_to_replace: Option<Range<isize>> = None;
3835 let mut ranges = Vec::new();
3836 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3837 for selection in &selections {
3838 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3839 let start = selection.start.saturating_sub(lookbehind);
3840 let end = selection.end + lookahead;
3841 if selection.id == newest_selection.id {
3842 range_to_replace = Some(
3843 ((start + common_prefix_len) as isize - selection.start as isize)
3844 ..(end as isize - selection.start as isize),
3845 );
3846 }
3847 ranges.push(start + common_prefix_len..end);
3848 } else {
3849 common_prefix_len = 0;
3850 ranges.clear();
3851 ranges.extend(selections.iter().map(|s| {
3852 if s.id == newest_selection.id {
3853 range_to_replace = Some(
3854 old_range.start.to_offset_utf16(&snapshot).0 as isize
3855 - selection.start as isize
3856 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3857 - selection.start as isize,
3858 );
3859 old_range.clone()
3860 } else {
3861 s.start..s.end
3862 }
3863 }));
3864 break;
3865 }
3866 if !self.linked_edit_ranges.is_empty() {
3867 let start_anchor = snapshot.anchor_before(selection.head());
3868 let end_anchor = snapshot.anchor_after(selection.tail());
3869 if let Some(ranges) = self
3870 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
3871 {
3872 for (buffer, edits) in ranges {
3873 linked_edits.entry(buffer.clone()).or_default().extend(
3874 edits
3875 .into_iter()
3876 .map(|range| (range, text[common_prefix_len..].to_owned())),
3877 );
3878 }
3879 }
3880 }
3881 }
3882 let text = &text[common_prefix_len..];
3883
3884 cx.emit(EditorEvent::InputHandled {
3885 utf16_range_to_replace: range_to_replace,
3886 text: text.into(),
3887 });
3888
3889 self.transact(cx, |this, cx| {
3890 if let Some(mut snippet) = snippet {
3891 snippet.text = text.to_string();
3892 for tabstop in snippet
3893 .tabstops
3894 .iter_mut()
3895 .flat_map(|tabstop| tabstop.ranges.iter_mut())
3896 {
3897 tabstop.start -= common_prefix_len as isize;
3898 tabstop.end -= common_prefix_len as isize;
3899 }
3900
3901 this.insert_snippet(&ranges, snippet, cx).log_err();
3902 } else {
3903 this.buffer.update(cx, |buffer, cx| {
3904 buffer.edit(
3905 ranges.iter().map(|range| (range.clone(), text)),
3906 this.autoindent_mode.clone(),
3907 cx,
3908 );
3909 });
3910 }
3911 for (buffer, edits) in linked_edits {
3912 buffer.update(cx, |buffer, cx| {
3913 let snapshot = buffer.snapshot();
3914 let edits = edits
3915 .into_iter()
3916 .map(|(range, text)| {
3917 use text::ToPoint as TP;
3918 let end_point = TP::to_point(&range.end, &snapshot);
3919 let start_point = TP::to_point(&range.start, &snapshot);
3920 (start_point..end_point, text)
3921 })
3922 .sorted_by_key(|(range, _)| range.start)
3923 .collect::<Vec<_>>();
3924 buffer.edit(edits, None, cx);
3925 })
3926 }
3927
3928 this.refresh_inline_completion(true, false, cx);
3929 });
3930
3931 let show_new_completions_on_confirm = completion
3932 .confirm
3933 .as_ref()
3934 .map_or(false, |confirm| confirm(intent, cx));
3935 if show_new_completions_on_confirm {
3936 self.show_completions(&ShowCompletions { trigger: None }, cx);
3937 }
3938
3939 let provider = self.completion_provider.as_ref()?;
3940 let apply_edits = provider.apply_additional_edits_for_completion(
3941 buffer_handle,
3942 completion.clone(),
3943 true,
3944 cx,
3945 );
3946
3947 let editor_settings = EditorSettings::get_global(cx);
3948 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
3949 // After the code completion is finished, users often want to know what signatures are needed.
3950 // so we should automatically call signature_help
3951 self.show_signature_help(&ShowSignatureHelp, cx);
3952 }
3953
3954 Some(cx.foreground_executor().spawn(async move {
3955 apply_edits.await?;
3956 Ok(())
3957 }))
3958 }
3959
3960 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
3961 let mut context_menu = self.context_menu.borrow_mut();
3962 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
3963 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
3964 // Toggle if we're selecting the same one
3965 *context_menu = None;
3966 cx.notify();
3967 return;
3968 } else {
3969 // Otherwise, clear it and start a new one
3970 *context_menu = None;
3971 cx.notify();
3972 }
3973 }
3974 drop(context_menu);
3975 let snapshot = self.snapshot(cx);
3976 let deployed_from_indicator = action.deployed_from_indicator;
3977 let mut task = self.code_actions_task.take();
3978 let action = action.clone();
3979 cx.spawn(|editor, mut cx| async move {
3980 while let Some(prev_task) = task {
3981 prev_task.await.log_err();
3982 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
3983 }
3984
3985 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
3986 if editor.focus_handle.is_focused(cx) {
3987 let multibuffer_point = action
3988 .deployed_from_indicator
3989 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
3990 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
3991 let (buffer, buffer_row) = snapshot
3992 .buffer_snapshot
3993 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
3994 .and_then(|(buffer_snapshot, range)| {
3995 editor
3996 .buffer
3997 .read(cx)
3998 .buffer(buffer_snapshot.remote_id())
3999 .map(|buffer| (buffer, range.start.row))
4000 })?;
4001 let (_, code_actions) = editor
4002 .available_code_actions
4003 .clone()
4004 .and_then(|(location, code_actions)| {
4005 let snapshot = location.buffer.read(cx).snapshot();
4006 let point_range = location.range.to_point(&snapshot);
4007 let point_range = point_range.start.row..=point_range.end.row;
4008 if point_range.contains(&buffer_row) {
4009 Some((location, code_actions))
4010 } else {
4011 None
4012 }
4013 })
4014 .unzip();
4015 let buffer_id = buffer.read(cx).remote_id();
4016 let tasks = editor
4017 .tasks
4018 .get(&(buffer_id, buffer_row))
4019 .map(|t| Arc::new(t.to_owned()));
4020 if tasks.is_none() && code_actions.is_none() {
4021 return None;
4022 }
4023
4024 editor.completion_tasks.clear();
4025 editor.discard_inline_completion(false, cx);
4026 let task_context =
4027 tasks
4028 .as_ref()
4029 .zip(editor.project.clone())
4030 .map(|(tasks, project)| {
4031 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4032 });
4033
4034 Some(cx.spawn(|editor, mut cx| async move {
4035 let task_context = match task_context {
4036 Some(task_context) => task_context.await,
4037 None => None,
4038 };
4039 let resolved_tasks =
4040 tasks.zip(task_context).map(|(tasks, task_context)| {
4041 Rc::new(ResolvedTasks {
4042 templates: tasks.resolve(&task_context).collect(),
4043 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4044 multibuffer_point.row,
4045 tasks.column,
4046 )),
4047 })
4048 });
4049 let spawn_straight_away = resolved_tasks
4050 .as_ref()
4051 .map_or(false, |tasks| tasks.templates.len() == 1)
4052 && code_actions
4053 .as_ref()
4054 .map_or(true, |actions| actions.is_empty());
4055 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4056 *editor.context_menu.borrow_mut() =
4057 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4058 buffer,
4059 actions: CodeActionContents {
4060 tasks: resolved_tasks,
4061 actions: code_actions,
4062 },
4063 selected_item: Default::default(),
4064 scroll_handle: UniformListScrollHandle::default(),
4065 deployed_from_indicator,
4066 }));
4067 if spawn_straight_away {
4068 if let Some(task) = editor.confirm_code_action(
4069 &ConfirmCodeAction { item_ix: Some(0) },
4070 cx,
4071 ) {
4072 cx.notify();
4073 return task;
4074 }
4075 }
4076 cx.notify();
4077 Task::ready(Ok(()))
4078 }) {
4079 task.await
4080 } else {
4081 Ok(())
4082 }
4083 }))
4084 } else {
4085 Some(Task::ready(Ok(())))
4086 }
4087 })?;
4088 if let Some(task) = spawned_test_task {
4089 task.await?;
4090 }
4091
4092 Ok::<_, anyhow::Error>(())
4093 })
4094 .detach_and_log_err(cx);
4095 }
4096
4097 pub fn confirm_code_action(
4098 &mut self,
4099 action: &ConfirmCodeAction,
4100 cx: &mut ViewContext<Self>,
4101 ) -> Option<Task<Result<()>>> {
4102 let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4103 menu
4104 } else {
4105 return None;
4106 };
4107 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4108 let action = actions_menu.actions.get(action_ix)?;
4109 let title = action.label();
4110 let buffer = actions_menu.buffer;
4111 let workspace = self.workspace()?;
4112
4113 match action {
4114 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4115 workspace.update(cx, |workspace, cx| {
4116 workspace::tasks::schedule_resolved_task(
4117 workspace,
4118 task_source_kind,
4119 resolved_task,
4120 false,
4121 cx,
4122 );
4123
4124 Some(Task::ready(Ok(())))
4125 })
4126 }
4127 CodeActionsItem::CodeAction {
4128 excerpt_id,
4129 action,
4130 provider,
4131 } => {
4132 let apply_code_action =
4133 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4134 let workspace = workspace.downgrade();
4135 Some(cx.spawn(|editor, cx| async move {
4136 let project_transaction = apply_code_action.await?;
4137 Self::open_project_transaction(
4138 &editor,
4139 workspace,
4140 project_transaction,
4141 title,
4142 cx,
4143 )
4144 .await
4145 }))
4146 }
4147 }
4148 }
4149
4150 pub async fn open_project_transaction(
4151 this: &WeakView<Editor>,
4152 workspace: WeakView<Workspace>,
4153 transaction: ProjectTransaction,
4154 title: String,
4155 mut cx: AsyncWindowContext,
4156 ) -> Result<()> {
4157 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4158 cx.update(|cx| {
4159 entries.sort_unstable_by_key(|(buffer, _)| {
4160 buffer.read(cx).file().map(|f| f.path().clone())
4161 });
4162 })?;
4163
4164 // If the project transaction's edits are all contained within this editor, then
4165 // avoid opening a new editor to display them.
4166
4167 if let Some((buffer, transaction)) = entries.first() {
4168 if entries.len() == 1 {
4169 let excerpt = this.update(&mut cx, |editor, cx| {
4170 editor
4171 .buffer()
4172 .read(cx)
4173 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4174 })?;
4175 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4176 if excerpted_buffer == *buffer {
4177 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4178 let excerpt_range = excerpt_range.to_offset(buffer);
4179 buffer
4180 .edited_ranges_for_transaction::<usize>(transaction)
4181 .all(|range| {
4182 excerpt_range.start <= range.start
4183 && excerpt_range.end >= range.end
4184 })
4185 })?;
4186
4187 if all_edits_within_excerpt {
4188 return Ok(());
4189 }
4190 }
4191 }
4192 }
4193 } else {
4194 return Ok(());
4195 }
4196
4197 let mut ranges_to_highlight = Vec::new();
4198 let excerpt_buffer = cx.new_model(|cx| {
4199 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4200 for (buffer_handle, transaction) in &entries {
4201 let buffer = buffer_handle.read(cx);
4202 ranges_to_highlight.extend(
4203 multibuffer.push_excerpts_with_context_lines(
4204 buffer_handle.clone(),
4205 buffer
4206 .edited_ranges_for_transaction::<usize>(transaction)
4207 .collect(),
4208 DEFAULT_MULTIBUFFER_CONTEXT,
4209 cx,
4210 ),
4211 );
4212 }
4213 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4214 multibuffer
4215 })?;
4216
4217 workspace.update(&mut cx, |workspace, cx| {
4218 let project = workspace.project().clone();
4219 let editor =
4220 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4221 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4222 editor.update(cx, |editor, cx| {
4223 editor.highlight_background::<Self>(
4224 &ranges_to_highlight,
4225 |theme| theme.editor_highlighted_line_background,
4226 cx,
4227 );
4228 });
4229 })?;
4230
4231 Ok(())
4232 }
4233
4234 pub fn clear_code_action_providers(&mut self) {
4235 self.code_action_providers.clear();
4236 self.available_code_actions.take();
4237 }
4238
4239 pub fn push_code_action_provider(
4240 &mut self,
4241 provider: Rc<dyn CodeActionProvider>,
4242 cx: &mut ViewContext<Self>,
4243 ) {
4244 self.code_action_providers.push(provider);
4245 self.refresh_code_actions(cx);
4246 }
4247
4248 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4249 let buffer = self.buffer.read(cx);
4250 let newest_selection = self.selections.newest_anchor().clone();
4251 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4252 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4253 if start_buffer != end_buffer {
4254 return None;
4255 }
4256
4257 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4258 cx.background_executor()
4259 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4260 .await;
4261
4262 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4263 let providers = this.code_action_providers.clone();
4264 let tasks = this
4265 .code_action_providers
4266 .iter()
4267 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4268 .collect::<Vec<_>>();
4269 (providers, tasks)
4270 })?;
4271
4272 let mut actions = Vec::new();
4273 for (provider, provider_actions) in
4274 providers.into_iter().zip(future::join_all(tasks).await)
4275 {
4276 if let Some(provider_actions) = provider_actions.log_err() {
4277 actions.extend(provider_actions.into_iter().map(|action| {
4278 AvailableCodeAction {
4279 excerpt_id: newest_selection.start.excerpt_id,
4280 action,
4281 provider: provider.clone(),
4282 }
4283 }));
4284 }
4285 }
4286
4287 this.update(&mut cx, |this, cx| {
4288 this.available_code_actions = if actions.is_empty() {
4289 None
4290 } else {
4291 Some((
4292 Location {
4293 buffer: start_buffer,
4294 range: start..end,
4295 },
4296 actions.into(),
4297 ))
4298 };
4299 cx.notify();
4300 })
4301 }));
4302 None
4303 }
4304
4305 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4306 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4307 self.show_git_blame_inline = false;
4308
4309 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4310 cx.background_executor().timer(delay).await;
4311
4312 this.update(&mut cx, |this, cx| {
4313 this.show_git_blame_inline = true;
4314 cx.notify();
4315 })
4316 .log_err();
4317 }));
4318 }
4319 }
4320
4321 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4322 if self.pending_rename.is_some() {
4323 return None;
4324 }
4325
4326 let provider = self.semantics_provider.clone()?;
4327 let buffer = self.buffer.read(cx);
4328 let newest_selection = self.selections.newest_anchor().clone();
4329 let cursor_position = newest_selection.head();
4330 let (cursor_buffer, cursor_buffer_position) =
4331 buffer.text_anchor_for_position(cursor_position, cx)?;
4332 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4333 if cursor_buffer != tail_buffer {
4334 return None;
4335 }
4336 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4337 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4338 cx.background_executor()
4339 .timer(Duration::from_millis(debounce))
4340 .await;
4341
4342 let highlights = if let Some(highlights) = cx
4343 .update(|cx| {
4344 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4345 })
4346 .ok()
4347 .flatten()
4348 {
4349 highlights.await.log_err()
4350 } else {
4351 None
4352 };
4353
4354 if let Some(highlights) = highlights {
4355 this.update(&mut cx, |this, cx| {
4356 if this.pending_rename.is_some() {
4357 return;
4358 }
4359
4360 let buffer_id = cursor_position.buffer_id;
4361 let buffer = this.buffer.read(cx);
4362 if !buffer
4363 .text_anchor_for_position(cursor_position, cx)
4364 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4365 {
4366 return;
4367 }
4368
4369 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4370 let mut write_ranges = Vec::new();
4371 let mut read_ranges = Vec::new();
4372 for highlight in highlights {
4373 for (excerpt_id, excerpt_range) in
4374 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4375 {
4376 let start = highlight
4377 .range
4378 .start
4379 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4380 let end = highlight
4381 .range
4382 .end
4383 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4384 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4385 continue;
4386 }
4387
4388 let range = Anchor {
4389 buffer_id,
4390 excerpt_id,
4391 text_anchor: start,
4392 }..Anchor {
4393 buffer_id,
4394 excerpt_id,
4395 text_anchor: end,
4396 };
4397 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4398 write_ranges.push(range);
4399 } else {
4400 read_ranges.push(range);
4401 }
4402 }
4403 }
4404
4405 this.highlight_background::<DocumentHighlightRead>(
4406 &read_ranges,
4407 |theme| theme.editor_document_highlight_read_background,
4408 cx,
4409 );
4410 this.highlight_background::<DocumentHighlightWrite>(
4411 &write_ranges,
4412 |theme| theme.editor_document_highlight_write_background,
4413 cx,
4414 );
4415 cx.notify();
4416 })
4417 .log_err();
4418 }
4419 }));
4420 None
4421 }
4422
4423 pub fn refresh_inline_completion(
4424 &mut self,
4425 debounce: bool,
4426 user_requested: bool,
4427 cx: &mut ViewContext<Self>,
4428 ) -> Option<()> {
4429 let provider = self.inline_completion_provider()?;
4430 let cursor = self.selections.newest_anchor().head();
4431 let (buffer, cursor_buffer_position) =
4432 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4433
4434 if !user_requested
4435 && (!self.enable_inline_completions
4436 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4437 || !self.is_focused(cx))
4438 {
4439 self.discard_inline_completion(false, cx);
4440 return None;
4441 }
4442
4443 self.update_visible_inline_completion(cx);
4444 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4445 Some(())
4446 }
4447
4448 fn cycle_inline_completion(
4449 &mut self,
4450 direction: Direction,
4451 cx: &mut ViewContext<Self>,
4452 ) -> Option<()> {
4453 let provider = self.inline_completion_provider()?;
4454 let cursor = self.selections.newest_anchor().head();
4455 let (buffer, cursor_buffer_position) =
4456 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4457 if !self.enable_inline_completions
4458 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4459 {
4460 return None;
4461 }
4462
4463 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4464 self.update_visible_inline_completion(cx);
4465
4466 Some(())
4467 }
4468
4469 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4470 if !self.has_active_inline_completion() {
4471 self.refresh_inline_completion(false, true, cx);
4472 return;
4473 }
4474
4475 self.update_visible_inline_completion(cx);
4476 }
4477
4478 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4479 self.show_cursor_names(cx);
4480 }
4481
4482 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4483 self.show_cursor_names = true;
4484 cx.notify();
4485 cx.spawn(|this, mut cx| async move {
4486 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4487 this.update(&mut cx, |this, cx| {
4488 this.show_cursor_names = false;
4489 cx.notify()
4490 })
4491 .ok()
4492 })
4493 .detach();
4494 }
4495
4496 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4497 if self.has_active_inline_completion() {
4498 self.cycle_inline_completion(Direction::Next, cx);
4499 } else {
4500 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4501 if is_copilot_disabled {
4502 cx.propagate();
4503 }
4504 }
4505 }
4506
4507 pub fn previous_inline_completion(
4508 &mut self,
4509 _: &PreviousInlineCompletion,
4510 cx: &mut ViewContext<Self>,
4511 ) {
4512 if self.has_active_inline_completion() {
4513 self.cycle_inline_completion(Direction::Prev, cx);
4514 } else {
4515 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4516 if is_copilot_disabled {
4517 cx.propagate();
4518 }
4519 }
4520 }
4521
4522 pub fn accept_inline_completion(
4523 &mut self,
4524 _: &AcceptInlineCompletion,
4525 cx: &mut ViewContext<Self>,
4526 ) {
4527 self.hide_context_menu(cx);
4528
4529 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4530 return;
4531 };
4532
4533 self.report_inline_completion_event(true, cx);
4534
4535 match &active_inline_completion.completion {
4536 InlineCompletion::Move(position) => {
4537 let position = *position;
4538 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4539 selections.select_anchor_ranges([position..position]);
4540 });
4541 }
4542 InlineCompletion::Edit(edits) => {
4543 if let Some(provider) = self.inline_completion_provider() {
4544 provider.accept(cx);
4545 }
4546
4547 let snapshot = self.buffer.read(cx).snapshot(cx);
4548 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4549
4550 self.buffer.update(cx, |buffer, cx| {
4551 buffer.edit(edits.iter().cloned(), None, cx)
4552 });
4553
4554 self.change_selections(None, cx, |s| {
4555 s.select_anchor_ranges([last_edit_end..last_edit_end])
4556 });
4557
4558 self.update_visible_inline_completion(cx);
4559 if self.active_inline_completion.is_none() {
4560 self.refresh_inline_completion(true, true, cx);
4561 }
4562
4563 cx.notify();
4564 }
4565 }
4566 }
4567
4568 pub fn accept_partial_inline_completion(
4569 &mut self,
4570 _: &AcceptPartialInlineCompletion,
4571 cx: &mut ViewContext<Self>,
4572 ) {
4573 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4574 return;
4575 };
4576 if self.selections.count() != 1 {
4577 return;
4578 }
4579
4580 self.report_inline_completion_event(true, cx);
4581
4582 match &active_inline_completion.completion {
4583 InlineCompletion::Move(position) => {
4584 let position = *position;
4585 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4586 selections.select_anchor_ranges([position..position]);
4587 });
4588 }
4589 InlineCompletion::Edit(edits) => {
4590 if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
4591 let text = edits[0].1.as_str();
4592 let mut partial_completion = text
4593 .chars()
4594 .by_ref()
4595 .take_while(|c| c.is_alphabetic())
4596 .collect::<String>();
4597 if partial_completion.is_empty() {
4598 partial_completion = text
4599 .chars()
4600 .by_ref()
4601 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4602 .collect::<String>();
4603 }
4604
4605 cx.emit(EditorEvent::InputHandled {
4606 utf16_range_to_replace: None,
4607 text: partial_completion.clone().into(),
4608 });
4609
4610 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4611
4612 self.refresh_inline_completion(true, true, cx);
4613 cx.notify();
4614 }
4615 }
4616 }
4617 }
4618
4619 fn discard_inline_completion(
4620 &mut self,
4621 should_report_inline_completion_event: bool,
4622 cx: &mut ViewContext<Self>,
4623 ) -> bool {
4624 if should_report_inline_completion_event {
4625 self.report_inline_completion_event(false, cx);
4626 }
4627
4628 if let Some(provider) = self.inline_completion_provider() {
4629 provider.discard(cx);
4630 }
4631
4632 self.take_active_inline_completion(cx).is_some()
4633 }
4634
4635 fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
4636 let Some(provider) = self.inline_completion_provider() else {
4637 return;
4638 };
4639 let Some(project) = self.project.as_ref() else {
4640 return;
4641 };
4642 let Some((_, buffer, _)) = self
4643 .buffer
4644 .read(cx)
4645 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4646 else {
4647 return;
4648 };
4649
4650 let project = project.read(cx);
4651 let extension = buffer
4652 .read(cx)
4653 .file()
4654 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4655 project.client().telemetry().report_inline_completion_event(
4656 provider.name().into(),
4657 accepted,
4658 extension,
4659 );
4660 }
4661
4662 pub fn has_active_inline_completion(&self) -> bool {
4663 self.active_inline_completion.is_some()
4664 }
4665
4666 fn take_active_inline_completion(
4667 &mut self,
4668 cx: &mut ViewContext<Self>,
4669 ) -> Option<InlineCompletion> {
4670 let active_inline_completion = self.active_inline_completion.take()?;
4671 self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
4672 self.clear_highlights::<InlineCompletionHighlight>(cx);
4673 Some(active_inline_completion.completion)
4674 }
4675
4676 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4677 let selection = self.selections.newest_anchor();
4678 let cursor = selection.head();
4679 let multibuffer = self.buffer.read(cx).snapshot(cx);
4680 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
4681 let excerpt_id = cursor.excerpt_id;
4682
4683 if !offset_selection.is_empty()
4684 || self
4685 .active_inline_completion
4686 .as_ref()
4687 .map_or(false, |completion| {
4688 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
4689 let invalidation_range = invalidation_range.start..=invalidation_range.end;
4690 !invalidation_range.contains(&offset_selection.head())
4691 })
4692 {
4693 self.discard_inline_completion(false, cx);
4694 return None;
4695 }
4696
4697 self.take_active_inline_completion(cx);
4698 let provider = self.inline_completion_provider()?;
4699
4700 let (buffer, cursor_buffer_position) =
4701 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4702
4703 let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
4704 let edits = completion
4705 .edits
4706 .into_iter()
4707 .map(|(range, new_text)| {
4708 (
4709 multibuffer
4710 .anchor_in_excerpt(excerpt_id, range.start)
4711 .unwrap()
4712 ..multibuffer
4713 .anchor_in_excerpt(excerpt_id, range.end)
4714 .unwrap(),
4715 new_text,
4716 )
4717 })
4718 .collect::<Vec<_>>();
4719 if edits.is_empty() {
4720 return None;
4721 }
4722
4723 let first_edit_start = edits.first().unwrap().0.start;
4724 let edit_start_row = first_edit_start
4725 .to_point(&multibuffer)
4726 .row
4727 .saturating_sub(2);
4728
4729 let last_edit_end = edits.last().unwrap().0.end;
4730 let edit_end_row = cmp::min(
4731 multibuffer.max_point().row,
4732 last_edit_end.to_point(&multibuffer).row + 2,
4733 );
4734
4735 let cursor_row = cursor.to_point(&multibuffer).row;
4736
4737 let mut inlay_ids = Vec::new();
4738 let invalidation_row_range;
4739 let completion;
4740 if cursor_row < edit_start_row {
4741 invalidation_row_range = cursor_row..edit_end_row;
4742 completion = InlineCompletion::Move(first_edit_start);
4743 } else if cursor_row > edit_end_row {
4744 invalidation_row_range = edit_start_row..cursor_row;
4745 completion = InlineCompletion::Move(first_edit_start);
4746 } else {
4747 if edits
4748 .iter()
4749 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
4750 {
4751 let mut inlays = Vec::new();
4752 for (range, new_text) in &edits {
4753 let inlay = Inlay::inline_completion(
4754 post_inc(&mut self.next_inlay_id),
4755 range.start,
4756 new_text.as_str(),
4757 );
4758 inlay_ids.push(inlay.id);
4759 inlays.push(inlay);
4760 }
4761
4762 self.splice_inlays(vec![], inlays, cx);
4763 } else {
4764 let background_color = cx.theme().status().deleted_background;
4765 self.highlight_text::<InlineCompletionHighlight>(
4766 edits.iter().map(|(range, _)| range.clone()).collect(),
4767 HighlightStyle {
4768 background_color: Some(background_color),
4769 ..Default::default()
4770 },
4771 cx,
4772 );
4773 }
4774
4775 invalidation_row_range = edit_start_row..edit_end_row;
4776 completion = InlineCompletion::Edit(edits);
4777 };
4778
4779 let invalidation_range = multibuffer
4780 .anchor_before(Point::new(invalidation_row_range.start, 0))
4781 ..multibuffer.anchor_after(Point::new(
4782 invalidation_row_range.end,
4783 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
4784 ));
4785
4786 self.active_inline_completion = Some(InlineCompletionState {
4787 inlay_ids,
4788 completion,
4789 invalidation_range,
4790 });
4791 cx.notify();
4792
4793 Some(())
4794 }
4795
4796 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
4797 Some(self.inline_completion_provider.as_ref()?.provider.clone())
4798 }
4799
4800 fn render_code_actions_indicator(
4801 &self,
4802 _style: &EditorStyle,
4803 row: DisplayRow,
4804 is_active: bool,
4805 cx: &mut ViewContext<Self>,
4806 ) -> Option<IconButton> {
4807 if self.available_code_actions.is_some() {
4808 Some(
4809 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
4810 .shape(ui::IconButtonShape::Square)
4811 .icon_size(IconSize::XSmall)
4812 .icon_color(Color::Muted)
4813 .toggle_state(is_active)
4814 .tooltip({
4815 let focus_handle = self.focus_handle.clone();
4816 move |cx| {
4817 Tooltip::for_action_in(
4818 "Toggle Code Actions",
4819 &ToggleCodeActions {
4820 deployed_from_indicator: None,
4821 },
4822 &focus_handle,
4823 cx,
4824 )
4825 }
4826 })
4827 .on_click(cx.listener(move |editor, _e, cx| {
4828 editor.focus(cx);
4829 editor.toggle_code_actions(
4830 &ToggleCodeActions {
4831 deployed_from_indicator: Some(row),
4832 },
4833 cx,
4834 );
4835 })),
4836 )
4837 } else {
4838 None
4839 }
4840 }
4841
4842 fn clear_tasks(&mut self) {
4843 self.tasks.clear()
4844 }
4845
4846 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
4847 if self.tasks.insert(key, value).is_some() {
4848 // This case should hopefully be rare, but just in case...
4849 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
4850 }
4851 }
4852
4853 fn build_tasks_context(
4854 project: &Model<Project>,
4855 buffer: &Model<Buffer>,
4856 buffer_row: u32,
4857 tasks: &Arc<RunnableTasks>,
4858 cx: &mut ViewContext<Self>,
4859 ) -> Task<Option<task::TaskContext>> {
4860 let position = Point::new(buffer_row, tasks.column);
4861 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4862 let location = Location {
4863 buffer: buffer.clone(),
4864 range: range_start..range_start,
4865 };
4866 // Fill in the environmental variables from the tree-sitter captures
4867 let mut captured_task_variables = TaskVariables::default();
4868 for (capture_name, value) in tasks.extra_variables.clone() {
4869 captured_task_variables.insert(
4870 task::VariableName::Custom(capture_name.into()),
4871 value.clone(),
4872 );
4873 }
4874 project.update(cx, |project, cx| {
4875 project.task_store().update(cx, |task_store, cx| {
4876 task_store.task_context_for_location(captured_task_variables, location, cx)
4877 })
4878 })
4879 }
4880
4881 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
4882 let Some((workspace, _)) = self.workspace.clone() else {
4883 return;
4884 };
4885 let Some(project) = self.project.clone() else {
4886 return;
4887 };
4888
4889 // Try to find a closest, enclosing node using tree-sitter that has a
4890 // task
4891 let Some((buffer, buffer_row, tasks)) = self
4892 .find_enclosing_node_task(cx)
4893 // Or find the task that's closest in row-distance.
4894 .or_else(|| self.find_closest_task(cx))
4895 else {
4896 return;
4897 };
4898
4899 let reveal_strategy = action.reveal;
4900 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
4901 cx.spawn(|_, mut cx| async move {
4902 let context = task_context.await?;
4903 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
4904
4905 let resolved = resolved_task.resolved.as_mut()?;
4906 resolved.reveal = reveal_strategy;
4907
4908 workspace
4909 .update(&mut cx, |workspace, cx| {
4910 workspace::tasks::schedule_resolved_task(
4911 workspace,
4912 task_source_kind,
4913 resolved_task,
4914 false,
4915 cx,
4916 );
4917 })
4918 .ok()
4919 })
4920 .detach();
4921 }
4922
4923 fn find_closest_task(
4924 &mut self,
4925 cx: &mut ViewContext<Self>,
4926 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
4927 let cursor_row = self.selections.newest_adjusted(cx).head().row;
4928
4929 let ((buffer_id, row), tasks) = self
4930 .tasks
4931 .iter()
4932 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
4933
4934 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
4935 let tasks = Arc::new(tasks.to_owned());
4936 Some((buffer, *row, tasks))
4937 }
4938
4939 fn find_enclosing_node_task(
4940 &mut self,
4941 cx: &mut ViewContext<Self>,
4942 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
4943 let snapshot = self.buffer.read(cx).snapshot(cx);
4944 let offset = self.selections.newest::<usize>(cx).head();
4945 let excerpt = snapshot.excerpt_containing(offset..offset)?;
4946 let buffer_id = excerpt.buffer().remote_id();
4947
4948 let layer = excerpt.buffer().syntax_layer_at(offset)?;
4949 let mut cursor = layer.node().walk();
4950
4951 while cursor.goto_first_child_for_byte(offset).is_some() {
4952 if cursor.node().end_byte() == offset {
4953 cursor.goto_next_sibling();
4954 }
4955 }
4956
4957 // Ascend to the smallest ancestor that contains the range and has a task.
4958 loop {
4959 let node = cursor.node();
4960 let node_range = node.byte_range();
4961 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
4962
4963 // Check if this node contains our offset
4964 if node_range.start <= offset && node_range.end >= offset {
4965 // If it contains offset, check for task
4966 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
4967 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
4968 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
4969 }
4970 }
4971
4972 if !cursor.goto_parent() {
4973 break;
4974 }
4975 }
4976 None
4977 }
4978
4979 fn render_run_indicator(
4980 &self,
4981 _style: &EditorStyle,
4982 is_active: bool,
4983 row: DisplayRow,
4984 cx: &mut ViewContext<Self>,
4985 ) -> IconButton {
4986 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
4987 .shape(ui::IconButtonShape::Square)
4988 .icon_size(IconSize::XSmall)
4989 .icon_color(Color::Muted)
4990 .toggle_state(is_active)
4991 .on_click(cx.listener(move |editor, _e, cx| {
4992 editor.focus(cx);
4993 editor.toggle_code_actions(
4994 &ToggleCodeActions {
4995 deployed_from_indicator: Some(row),
4996 },
4997 cx,
4998 );
4999 }))
5000 }
5001
5002 pub fn context_menu_visible(&self) -> bool {
5003 self.context_menu
5004 .borrow()
5005 .as_ref()
5006 .map_or(false, |menu| menu.visible())
5007 }
5008
5009 fn render_context_menu(
5010 &self,
5011 cursor_position: DisplayPoint,
5012 style: &EditorStyle,
5013 max_height: Pixels,
5014 cx: &mut ViewContext<Editor>,
5015 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5016 self.context_menu.borrow().as_ref().map(|menu| {
5017 menu.render(
5018 cursor_position,
5019 style,
5020 max_height,
5021 self.workspace.as_ref().map(|(w, _)| w.clone()),
5022 cx,
5023 )
5024 })
5025 }
5026
5027 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
5028 cx.notify();
5029 self.completion_tasks.clear();
5030 self.context_menu.borrow_mut().take()
5031 }
5032
5033 fn show_snippet_choices(
5034 &mut self,
5035 choices: &Vec<String>,
5036 selection: Range<Anchor>,
5037 cx: &mut ViewContext<Self>,
5038 ) {
5039 if selection.start.buffer_id.is_none() {
5040 return;
5041 }
5042 let buffer_id = selection.start.buffer_id.unwrap();
5043 let buffer = self.buffer().read(cx).buffer(buffer_id);
5044 let id = post_inc(&mut self.next_completion_id);
5045
5046 if let Some(buffer) = buffer {
5047 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5048 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5049 ));
5050 }
5051 }
5052
5053 pub fn insert_snippet(
5054 &mut self,
5055 insertion_ranges: &[Range<usize>],
5056 snippet: Snippet,
5057 cx: &mut ViewContext<Self>,
5058 ) -> Result<()> {
5059 struct Tabstop<T> {
5060 is_end_tabstop: bool,
5061 ranges: Vec<Range<T>>,
5062 choices: Option<Vec<String>>,
5063 }
5064
5065 let tabstops = self.buffer.update(cx, |buffer, cx| {
5066 let snippet_text: Arc<str> = snippet.text.clone().into();
5067 buffer.edit(
5068 insertion_ranges
5069 .iter()
5070 .cloned()
5071 .map(|range| (range, snippet_text.clone())),
5072 Some(AutoindentMode::EachLine),
5073 cx,
5074 );
5075
5076 let snapshot = &*buffer.read(cx);
5077 let snippet = &snippet;
5078 snippet
5079 .tabstops
5080 .iter()
5081 .map(|tabstop| {
5082 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5083 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5084 });
5085 let mut tabstop_ranges = tabstop
5086 .ranges
5087 .iter()
5088 .flat_map(|tabstop_range| {
5089 let mut delta = 0_isize;
5090 insertion_ranges.iter().map(move |insertion_range| {
5091 let insertion_start = insertion_range.start as isize + delta;
5092 delta +=
5093 snippet.text.len() as isize - insertion_range.len() as isize;
5094
5095 let start = ((insertion_start + tabstop_range.start) as usize)
5096 .min(snapshot.len());
5097 let end = ((insertion_start + tabstop_range.end) as usize)
5098 .min(snapshot.len());
5099 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5100 })
5101 })
5102 .collect::<Vec<_>>();
5103 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5104
5105 Tabstop {
5106 is_end_tabstop,
5107 ranges: tabstop_ranges,
5108 choices: tabstop.choices.clone(),
5109 }
5110 })
5111 .collect::<Vec<_>>()
5112 });
5113 if let Some(tabstop) = tabstops.first() {
5114 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5115 s.select_ranges(tabstop.ranges.iter().cloned());
5116 });
5117
5118 if let Some(choices) = &tabstop.choices {
5119 if let Some(selection) = tabstop.ranges.first() {
5120 self.show_snippet_choices(choices, selection.clone(), cx)
5121 }
5122 }
5123
5124 // If we're already at the last tabstop and it's at the end of the snippet,
5125 // we're done, we don't need to keep the state around.
5126 if !tabstop.is_end_tabstop {
5127 let choices = tabstops
5128 .iter()
5129 .map(|tabstop| tabstop.choices.clone())
5130 .collect();
5131
5132 let ranges = tabstops
5133 .into_iter()
5134 .map(|tabstop| tabstop.ranges)
5135 .collect::<Vec<_>>();
5136
5137 self.snippet_stack.push(SnippetState {
5138 active_index: 0,
5139 ranges,
5140 choices,
5141 });
5142 }
5143
5144 // Check whether the just-entered snippet ends with an auto-closable bracket.
5145 if self.autoclose_regions.is_empty() {
5146 let snapshot = self.buffer.read(cx).snapshot(cx);
5147 for selection in &mut self.selections.all::<Point>(cx) {
5148 let selection_head = selection.head();
5149 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5150 continue;
5151 };
5152
5153 let mut bracket_pair = None;
5154 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5155 let prev_chars = snapshot
5156 .reversed_chars_at(selection_head)
5157 .collect::<String>();
5158 for (pair, enabled) in scope.brackets() {
5159 if enabled
5160 && pair.close
5161 && prev_chars.starts_with(pair.start.as_str())
5162 && next_chars.starts_with(pair.end.as_str())
5163 {
5164 bracket_pair = Some(pair.clone());
5165 break;
5166 }
5167 }
5168 if let Some(pair) = bracket_pair {
5169 let start = snapshot.anchor_after(selection_head);
5170 let end = snapshot.anchor_after(selection_head);
5171 self.autoclose_regions.push(AutocloseRegion {
5172 selection_id: selection.id,
5173 range: start..end,
5174 pair,
5175 });
5176 }
5177 }
5178 }
5179 }
5180 Ok(())
5181 }
5182
5183 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5184 self.move_to_snippet_tabstop(Bias::Right, cx)
5185 }
5186
5187 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5188 self.move_to_snippet_tabstop(Bias::Left, cx)
5189 }
5190
5191 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5192 if let Some(mut snippet) = self.snippet_stack.pop() {
5193 match bias {
5194 Bias::Left => {
5195 if snippet.active_index > 0 {
5196 snippet.active_index -= 1;
5197 } else {
5198 self.snippet_stack.push(snippet);
5199 return false;
5200 }
5201 }
5202 Bias::Right => {
5203 if snippet.active_index + 1 < snippet.ranges.len() {
5204 snippet.active_index += 1;
5205 } else {
5206 self.snippet_stack.push(snippet);
5207 return false;
5208 }
5209 }
5210 }
5211 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5212 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5213 s.select_anchor_ranges(current_ranges.iter().cloned())
5214 });
5215
5216 if let Some(choices) = &snippet.choices[snippet.active_index] {
5217 if let Some(selection) = current_ranges.first() {
5218 self.show_snippet_choices(&choices, selection.clone(), cx);
5219 }
5220 }
5221
5222 // If snippet state is not at the last tabstop, push it back on the stack
5223 if snippet.active_index + 1 < snippet.ranges.len() {
5224 self.snippet_stack.push(snippet);
5225 }
5226 return true;
5227 }
5228 }
5229
5230 false
5231 }
5232
5233 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5234 self.transact(cx, |this, cx| {
5235 this.select_all(&SelectAll, cx);
5236 this.insert("", cx);
5237 });
5238 }
5239
5240 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5241 self.transact(cx, |this, cx| {
5242 this.select_autoclose_pair(cx);
5243 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5244 if !this.linked_edit_ranges.is_empty() {
5245 let selections = this.selections.all::<MultiBufferPoint>(cx);
5246 let snapshot = this.buffer.read(cx).snapshot(cx);
5247
5248 for selection in selections.iter() {
5249 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5250 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5251 if selection_start.buffer_id != selection_end.buffer_id {
5252 continue;
5253 }
5254 if let Some(ranges) =
5255 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5256 {
5257 for (buffer, entries) in ranges {
5258 linked_ranges.entry(buffer).or_default().extend(entries);
5259 }
5260 }
5261 }
5262 }
5263
5264 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5265 if !this.selections.line_mode {
5266 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5267 for selection in &mut selections {
5268 if selection.is_empty() {
5269 let old_head = selection.head();
5270 let mut new_head =
5271 movement::left(&display_map, old_head.to_display_point(&display_map))
5272 .to_point(&display_map);
5273 if let Some((buffer, line_buffer_range)) = display_map
5274 .buffer_snapshot
5275 .buffer_line_for_row(MultiBufferRow(old_head.row))
5276 {
5277 let indent_size =
5278 buffer.indent_size_for_line(line_buffer_range.start.row);
5279 let indent_len = match indent_size.kind {
5280 IndentKind::Space => {
5281 buffer.settings_at(line_buffer_range.start, cx).tab_size
5282 }
5283 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5284 };
5285 if old_head.column <= indent_size.len && old_head.column > 0 {
5286 let indent_len = indent_len.get();
5287 new_head = cmp::min(
5288 new_head,
5289 MultiBufferPoint::new(
5290 old_head.row,
5291 ((old_head.column - 1) / indent_len) * indent_len,
5292 ),
5293 );
5294 }
5295 }
5296
5297 selection.set_head(new_head, SelectionGoal::None);
5298 }
5299 }
5300 }
5301
5302 this.signature_help_state.set_backspace_pressed(true);
5303 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5304 this.insert("", cx);
5305 let empty_str: Arc<str> = Arc::from("");
5306 for (buffer, edits) in linked_ranges {
5307 let snapshot = buffer.read(cx).snapshot();
5308 use text::ToPoint as TP;
5309
5310 let edits = edits
5311 .into_iter()
5312 .map(|range| {
5313 let end_point = TP::to_point(&range.end, &snapshot);
5314 let mut start_point = TP::to_point(&range.start, &snapshot);
5315
5316 if end_point == start_point {
5317 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5318 .saturating_sub(1);
5319 start_point = TP::to_point(&offset, &snapshot);
5320 };
5321
5322 (start_point..end_point, empty_str.clone())
5323 })
5324 .sorted_by_key(|(range, _)| range.start)
5325 .collect::<Vec<_>>();
5326 buffer.update(cx, |this, cx| {
5327 this.edit(edits, None, cx);
5328 })
5329 }
5330 this.refresh_inline_completion(true, false, cx);
5331 linked_editing_ranges::refresh_linked_ranges(this, cx);
5332 });
5333 }
5334
5335 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5336 self.transact(cx, |this, cx| {
5337 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5338 let line_mode = s.line_mode;
5339 s.move_with(|map, selection| {
5340 if selection.is_empty() && !line_mode {
5341 let cursor = movement::right(map, selection.head());
5342 selection.end = cursor;
5343 selection.reversed = true;
5344 selection.goal = SelectionGoal::None;
5345 }
5346 })
5347 });
5348 this.insert("", cx);
5349 this.refresh_inline_completion(true, false, cx);
5350 });
5351 }
5352
5353 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5354 if self.move_to_prev_snippet_tabstop(cx) {
5355 return;
5356 }
5357
5358 self.outdent(&Outdent, cx);
5359 }
5360
5361 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5362 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5363 return;
5364 }
5365
5366 let mut selections = self.selections.all_adjusted(cx);
5367 let buffer = self.buffer.read(cx);
5368 let snapshot = buffer.snapshot(cx);
5369 let rows_iter = selections.iter().map(|s| s.head().row);
5370 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5371
5372 let mut edits = Vec::new();
5373 let mut prev_edited_row = 0;
5374 let mut row_delta = 0;
5375 for selection in &mut selections {
5376 if selection.start.row != prev_edited_row {
5377 row_delta = 0;
5378 }
5379 prev_edited_row = selection.end.row;
5380
5381 // If the selection is non-empty, then increase the indentation of the selected lines.
5382 if !selection.is_empty() {
5383 row_delta =
5384 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5385 continue;
5386 }
5387
5388 // If the selection is empty and the cursor is in the leading whitespace before the
5389 // suggested indentation, then auto-indent the line.
5390 let cursor = selection.head();
5391 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5392 if let Some(suggested_indent) =
5393 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5394 {
5395 if cursor.column < suggested_indent.len
5396 && cursor.column <= current_indent.len
5397 && current_indent.len <= suggested_indent.len
5398 {
5399 selection.start = Point::new(cursor.row, suggested_indent.len);
5400 selection.end = selection.start;
5401 if row_delta == 0 {
5402 edits.extend(Buffer::edit_for_indent_size_adjustment(
5403 cursor.row,
5404 current_indent,
5405 suggested_indent,
5406 ));
5407 row_delta = suggested_indent.len - current_indent.len;
5408 }
5409 continue;
5410 }
5411 }
5412
5413 // Otherwise, insert a hard or soft tab.
5414 let settings = buffer.settings_at(cursor, cx);
5415 let tab_size = if settings.hard_tabs {
5416 IndentSize::tab()
5417 } else {
5418 let tab_size = settings.tab_size.get();
5419 let char_column = snapshot
5420 .text_for_range(Point::new(cursor.row, 0)..cursor)
5421 .flat_map(str::chars)
5422 .count()
5423 + row_delta as usize;
5424 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5425 IndentSize::spaces(chars_to_next_tab_stop)
5426 };
5427 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5428 selection.end = selection.start;
5429 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5430 row_delta += tab_size.len;
5431 }
5432
5433 self.transact(cx, |this, cx| {
5434 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5435 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5436 this.refresh_inline_completion(true, false, cx);
5437 });
5438 }
5439
5440 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5441 if self.read_only(cx) {
5442 return;
5443 }
5444 let mut selections = self.selections.all::<Point>(cx);
5445 let mut prev_edited_row = 0;
5446 let mut row_delta = 0;
5447 let mut edits = Vec::new();
5448 let buffer = self.buffer.read(cx);
5449 let snapshot = buffer.snapshot(cx);
5450 for selection in &mut selections {
5451 if selection.start.row != prev_edited_row {
5452 row_delta = 0;
5453 }
5454 prev_edited_row = selection.end.row;
5455
5456 row_delta =
5457 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5458 }
5459
5460 self.transact(cx, |this, cx| {
5461 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5462 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5463 });
5464 }
5465
5466 fn indent_selection(
5467 buffer: &MultiBuffer,
5468 snapshot: &MultiBufferSnapshot,
5469 selection: &mut Selection<Point>,
5470 edits: &mut Vec<(Range<Point>, String)>,
5471 delta_for_start_row: u32,
5472 cx: &AppContext,
5473 ) -> u32 {
5474 let settings = buffer.settings_at(selection.start, cx);
5475 let tab_size = settings.tab_size.get();
5476 let indent_kind = if settings.hard_tabs {
5477 IndentKind::Tab
5478 } else {
5479 IndentKind::Space
5480 };
5481 let mut start_row = selection.start.row;
5482 let mut end_row = selection.end.row + 1;
5483
5484 // If a selection ends at the beginning of a line, don't indent
5485 // that last line.
5486 if selection.end.column == 0 && selection.end.row > selection.start.row {
5487 end_row -= 1;
5488 }
5489
5490 // Avoid re-indenting a row that has already been indented by a
5491 // previous selection, but still update this selection's column
5492 // to reflect that indentation.
5493 if delta_for_start_row > 0 {
5494 start_row += 1;
5495 selection.start.column += delta_for_start_row;
5496 if selection.end.row == selection.start.row {
5497 selection.end.column += delta_for_start_row;
5498 }
5499 }
5500
5501 let mut delta_for_end_row = 0;
5502 let has_multiple_rows = start_row + 1 != end_row;
5503 for row in start_row..end_row {
5504 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5505 let indent_delta = match (current_indent.kind, indent_kind) {
5506 (IndentKind::Space, IndentKind::Space) => {
5507 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5508 IndentSize::spaces(columns_to_next_tab_stop)
5509 }
5510 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5511 (_, IndentKind::Tab) => IndentSize::tab(),
5512 };
5513
5514 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5515 0
5516 } else {
5517 selection.start.column
5518 };
5519 let row_start = Point::new(row, start);
5520 edits.push((
5521 row_start..row_start,
5522 indent_delta.chars().collect::<String>(),
5523 ));
5524
5525 // Update this selection's endpoints to reflect the indentation.
5526 if row == selection.start.row {
5527 selection.start.column += indent_delta.len;
5528 }
5529 if row == selection.end.row {
5530 selection.end.column += indent_delta.len;
5531 delta_for_end_row = indent_delta.len;
5532 }
5533 }
5534
5535 if selection.start.row == selection.end.row {
5536 delta_for_start_row + delta_for_end_row
5537 } else {
5538 delta_for_end_row
5539 }
5540 }
5541
5542 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5543 if self.read_only(cx) {
5544 return;
5545 }
5546 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5547 let selections = self.selections.all::<Point>(cx);
5548 let mut deletion_ranges = Vec::new();
5549 let mut last_outdent = None;
5550 {
5551 let buffer = self.buffer.read(cx);
5552 let snapshot = buffer.snapshot(cx);
5553 for selection in &selections {
5554 let settings = buffer.settings_at(selection.start, cx);
5555 let tab_size = settings.tab_size.get();
5556 let mut rows = selection.spanned_rows(false, &display_map);
5557
5558 // Avoid re-outdenting a row that has already been outdented by a
5559 // previous selection.
5560 if let Some(last_row) = last_outdent {
5561 if last_row == rows.start {
5562 rows.start = rows.start.next_row();
5563 }
5564 }
5565 let has_multiple_rows = rows.len() > 1;
5566 for row in rows.iter_rows() {
5567 let indent_size = snapshot.indent_size_for_line(row);
5568 if indent_size.len > 0 {
5569 let deletion_len = match indent_size.kind {
5570 IndentKind::Space => {
5571 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5572 if columns_to_prev_tab_stop == 0 {
5573 tab_size
5574 } else {
5575 columns_to_prev_tab_stop
5576 }
5577 }
5578 IndentKind::Tab => 1,
5579 };
5580 let start = if has_multiple_rows
5581 || deletion_len > selection.start.column
5582 || indent_size.len < selection.start.column
5583 {
5584 0
5585 } else {
5586 selection.start.column - deletion_len
5587 };
5588 deletion_ranges.push(
5589 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5590 );
5591 last_outdent = Some(row);
5592 }
5593 }
5594 }
5595 }
5596
5597 self.transact(cx, |this, cx| {
5598 this.buffer.update(cx, |buffer, cx| {
5599 let empty_str: Arc<str> = Arc::default();
5600 buffer.edit(
5601 deletion_ranges
5602 .into_iter()
5603 .map(|range| (range, empty_str.clone())),
5604 None,
5605 cx,
5606 );
5607 });
5608 let selections = this.selections.all::<usize>(cx);
5609 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5610 });
5611 }
5612
5613 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
5614 if self.read_only(cx) {
5615 return;
5616 }
5617 let selections = self
5618 .selections
5619 .all::<usize>(cx)
5620 .into_iter()
5621 .map(|s| s.range());
5622
5623 self.transact(cx, |this, cx| {
5624 this.buffer.update(cx, |buffer, cx| {
5625 buffer.autoindent_ranges(selections, cx);
5626 });
5627 let selections = this.selections.all::<usize>(cx);
5628 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5629 });
5630 }
5631
5632 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5633 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5634 let selections = self.selections.all::<Point>(cx);
5635
5636 let mut new_cursors = Vec::new();
5637 let mut edit_ranges = Vec::new();
5638 let mut selections = selections.iter().peekable();
5639 while let Some(selection) = selections.next() {
5640 let mut rows = selection.spanned_rows(false, &display_map);
5641 let goal_display_column = selection.head().to_display_point(&display_map).column();
5642
5643 // Accumulate contiguous regions of rows that we want to delete.
5644 while let Some(next_selection) = selections.peek() {
5645 let next_rows = next_selection.spanned_rows(false, &display_map);
5646 if next_rows.start <= rows.end {
5647 rows.end = next_rows.end;
5648 selections.next().unwrap();
5649 } else {
5650 break;
5651 }
5652 }
5653
5654 let buffer = &display_map.buffer_snapshot;
5655 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5656 let edit_end;
5657 let cursor_buffer_row;
5658 if buffer.max_point().row >= rows.end.0 {
5659 // If there's a line after the range, delete the \n from the end of the row range
5660 // and position the cursor on the next line.
5661 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5662 cursor_buffer_row = rows.end;
5663 } else {
5664 // If there isn't a line after the range, delete the \n from the line before the
5665 // start of the row range and position the cursor there.
5666 edit_start = edit_start.saturating_sub(1);
5667 edit_end = buffer.len();
5668 cursor_buffer_row = rows.start.previous_row();
5669 }
5670
5671 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5672 *cursor.column_mut() =
5673 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5674
5675 new_cursors.push((
5676 selection.id,
5677 buffer.anchor_after(cursor.to_point(&display_map)),
5678 ));
5679 edit_ranges.push(edit_start..edit_end);
5680 }
5681
5682 self.transact(cx, |this, cx| {
5683 let buffer = this.buffer.update(cx, |buffer, cx| {
5684 let empty_str: Arc<str> = Arc::default();
5685 buffer.edit(
5686 edit_ranges
5687 .into_iter()
5688 .map(|range| (range, empty_str.clone())),
5689 None,
5690 cx,
5691 );
5692 buffer.snapshot(cx)
5693 });
5694 let new_selections = new_cursors
5695 .into_iter()
5696 .map(|(id, cursor)| {
5697 let cursor = cursor.to_point(&buffer);
5698 Selection {
5699 id,
5700 start: cursor,
5701 end: cursor,
5702 reversed: false,
5703 goal: SelectionGoal::None,
5704 }
5705 })
5706 .collect();
5707
5708 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5709 s.select(new_selections);
5710 });
5711 });
5712 }
5713
5714 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5715 if self.read_only(cx) {
5716 return;
5717 }
5718 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5719 for selection in self.selections.all::<Point>(cx) {
5720 let start = MultiBufferRow(selection.start.row);
5721 // Treat single line selections as if they include the next line. Otherwise this action
5722 // would do nothing for single line selections individual cursors.
5723 let end = if selection.start.row == selection.end.row {
5724 MultiBufferRow(selection.start.row + 1)
5725 } else {
5726 MultiBufferRow(selection.end.row)
5727 };
5728
5729 if let Some(last_row_range) = row_ranges.last_mut() {
5730 if start <= last_row_range.end {
5731 last_row_range.end = end;
5732 continue;
5733 }
5734 }
5735 row_ranges.push(start..end);
5736 }
5737
5738 let snapshot = self.buffer.read(cx).snapshot(cx);
5739 let mut cursor_positions = Vec::new();
5740 for row_range in &row_ranges {
5741 let anchor = snapshot.anchor_before(Point::new(
5742 row_range.end.previous_row().0,
5743 snapshot.line_len(row_range.end.previous_row()),
5744 ));
5745 cursor_positions.push(anchor..anchor);
5746 }
5747
5748 self.transact(cx, |this, cx| {
5749 for row_range in row_ranges.into_iter().rev() {
5750 for row in row_range.iter_rows().rev() {
5751 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5752 let next_line_row = row.next_row();
5753 let indent = snapshot.indent_size_for_line(next_line_row);
5754 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5755
5756 let replace = if snapshot.line_len(next_line_row) > indent.len {
5757 " "
5758 } else {
5759 ""
5760 };
5761
5762 this.buffer.update(cx, |buffer, cx| {
5763 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5764 });
5765 }
5766 }
5767
5768 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5769 s.select_anchor_ranges(cursor_positions)
5770 });
5771 });
5772 }
5773
5774 pub fn sort_lines_case_sensitive(
5775 &mut self,
5776 _: &SortLinesCaseSensitive,
5777 cx: &mut ViewContext<Self>,
5778 ) {
5779 self.manipulate_lines(cx, |lines| lines.sort())
5780 }
5781
5782 pub fn sort_lines_case_insensitive(
5783 &mut self,
5784 _: &SortLinesCaseInsensitive,
5785 cx: &mut ViewContext<Self>,
5786 ) {
5787 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5788 }
5789
5790 pub fn unique_lines_case_insensitive(
5791 &mut self,
5792 _: &UniqueLinesCaseInsensitive,
5793 cx: &mut ViewContext<Self>,
5794 ) {
5795 self.manipulate_lines(cx, |lines| {
5796 let mut seen = HashSet::default();
5797 lines.retain(|line| seen.insert(line.to_lowercase()));
5798 })
5799 }
5800
5801 pub fn unique_lines_case_sensitive(
5802 &mut self,
5803 _: &UniqueLinesCaseSensitive,
5804 cx: &mut ViewContext<Self>,
5805 ) {
5806 self.manipulate_lines(cx, |lines| {
5807 let mut seen = HashSet::default();
5808 lines.retain(|line| seen.insert(*line));
5809 })
5810 }
5811
5812 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
5813 let mut revert_changes = HashMap::default();
5814 let snapshot = self.snapshot(cx);
5815 for hunk in hunks_for_ranges(
5816 Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
5817 &snapshot,
5818 ) {
5819 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
5820 }
5821 if !revert_changes.is_empty() {
5822 self.transact(cx, |editor, cx| {
5823 editor.revert(revert_changes, cx);
5824 });
5825 }
5826 }
5827
5828 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
5829 let Some(project) = self.project.clone() else {
5830 return;
5831 };
5832 self.reload(project, cx).detach_and_notify_err(cx);
5833 }
5834
5835 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
5836 let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
5837 if !revert_changes.is_empty() {
5838 self.transact(cx, |editor, cx| {
5839 editor.revert(revert_changes, cx);
5840 });
5841 }
5842 }
5843
5844 fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
5845 let snapshot = self.buffer.read(cx).read(cx);
5846 if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
5847 drop(snapshot);
5848 let mut revert_changes = HashMap::default();
5849 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
5850 if !revert_changes.is_empty() {
5851 self.revert(revert_changes, cx)
5852 }
5853 }
5854 }
5855
5856 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
5857 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
5858 let project_path = buffer.read(cx).project_path(cx)?;
5859 let project = self.project.as_ref()?.read(cx);
5860 let entry = project.entry_for_path(&project_path, cx)?;
5861 let parent = match &entry.canonical_path {
5862 Some(canonical_path) => canonical_path.to_path_buf(),
5863 None => project.absolute_path(&project_path, cx)?,
5864 }
5865 .parent()?
5866 .to_path_buf();
5867 Some(parent)
5868 }) {
5869 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
5870 }
5871 }
5872
5873 fn gather_revert_changes(
5874 &mut self,
5875 selections: &[Selection<Point>],
5876 cx: &mut ViewContext<'_, Editor>,
5877 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
5878 let mut revert_changes = HashMap::default();
5879 let snapshot = self.snapshot(cx);
5880 for hunk in hunks_for_selections(&snapshot, selections) {
5881 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
5882 }
5883 revert_changes
5884 }
5885
5886 pub fn prepare_revert_change(
5887 &mut self,
5888 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
5889 hunk: &MultiBufferDiffHunk,
5890 cx: &AppContext,
5891 ) -> Option<()> {
5892 let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
5893 let buffer = buffer.read(cx);
5894 let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
5895 let original_text = change_set
5896 .read(cx)
5897 .base_text
5898 .as_ref()?
5899 .read(cx)
5900 .as_rope()
5901 .slice(hunk.diff_base_byte_range.clone());
5902 let buffer_snapshot = buffer.snapshot();
5903 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
5904 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
5905 probe
5906 .0
5907 .start
5908 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
5909 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
5910 }) {
5911 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
5912 Some(())
5913 } else {
5914 None
5915 }
5916 }
5917
5918 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
5919 self.manipulate_lines(cx, |lines| lines.reverse())
5920 }
5921
5922 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
5923 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
5924 }
5925
5926 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
5927 where
5928 Fn: FnMut(&mut Vec<&str>),
5929 {
5930 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5931 let buffer = self.buffer.read(cx).snapshot(cx);
5932
5933 let mut edits = Vec::new();
5934
5935 let selections = self.selections.all::<Point>(cx);
5936 let mut selections = selections.iter().peekable();
5937 let mut contiguous_row_selections = Vec::new();
5938 let mut new_selections = Vec::new();
5939 let mut added_lines = 0;
5940 let mut removed_lines = 0;
5941
5942 while let Some(selection) = selections.next() {
5943 let (start_row, end_row) = consume_contiguous_rows(
5944 &mut contiguous_row_selections,
5945 selection,
5946 &display_map,
5947 &mut selections,
5948 );
5949
5950 let start_point = Point::new(start_row.0, 0);
5951 let end_point = Point::new(
5952 end_row.previous_row().0,
5953 buffer.line_len(end_row.previous_row()),
5954 );
5955 let text = buffer
5956 .text_for_range(start_point..end_point)
5957 .collect::<String>();
5958
5959 let mut lines = text.split('\n').collect_vec();
5960
5961 let lines_before = lines.len();
5962 callback(&mut lines);
5963 let lines_after = lines.len();
5964
5965 edits.push((start_point..end_point, lines.join("\n")));
5966
5967 // Selections must change based on added and removed line count
5968 let start_row =
5969 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
5970 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
5971 new_selections.push(Selection {
5972 id: selection.id,
5973 start: start_row,
5974 end: end_row,
5975 goal: SelectionGoal::None,
5976 reversed: selection.reversed,
5977 });
5978
5979 if lines_after > lines_before {
5980 added_lines += lines_after - lines_before;
5981 } else if lines_before > lines_after {
5982 removed_lines += lines_before - lines_after;
5983 }
5984 }
5985
5986 self.transact(cx, |this, cx| {
5987 let buffer = this.buffer.update(cx, |buffer, cx| {
5988 buffer.edit(edits, None, cx);
5989 buffer.snapshot(cx)
5990 });
5991
5992 // Recalculate offsets on newly edited buffer
5993 let new_selections = new_selections
5994 .iter()
5995 .map(|s| {
5996 let start_point = Point::new(s.start.0, 0);
5997 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
5998 Selection {
5999 id: s.id,
6000 start: buffer.point_to_offset(start_point),
6001 end: buffer.point_to_offset(end_point),
6002 goal: s.goal,
6003 reversed: s.reversed,
6004 }
6005 })
6006 .collect();
6007
6008 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6009 s.select(new_selections);
6010 });
6011
6012 this.request_autoscroll(Autoscroll::fit(), cx);
6013 });
6014 }
6015
6016 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6017 self.manipulate_text(cx, |text| text.to_uppercase())
6018 }
6019
6020 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6021 self.manipulate_text(cx, |text| text.to_lowercase())
6022 }
6023
6024 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6025 self.manipulate_text(cx, |text| {
6026 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6027 // https://github.com/rutrum/convert-case/issues/16
6028 text.split('\n')
6029 .map(|line| line.to_case(Case::Title))
6030 .join("\n")
6031 })
6032 }
6033
6034 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6035 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6036 }
6037
6038 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6039 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6040 }
6041
6042 pub fn convert_to_upper_camel_case(
6043 &mut self,
6044 _: &ConvertToUpperCamelCase,
6045 cx: &mut ViewContext<Self>,
6046 ) {
6047 self.manipulate_text(cx, |text| {
6048 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6049 // https://github.com/rutrum/convert-case/issues/16
6050 text.split('\n')
6051 .map(|line| line.to_case(Case::UpperCamel))
6052 .join("\n")
6053 })
6054 }
6055
6056 pub fn convert_to_lower_camel_case(
6057 &mut self,
6058 _: &ConvertToLowerCamelCase,
6059 cx: &mut ViewContext<Self>,
6060 ) {
6061 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6062 }
6063
6064 pub fn convert_to_opposite_case(
6065 &mut self,
6066 _: &ConvertToOppositeCase,
6067 cx: &mut ViewContext<Self>,
6068 ) {
6069 self.manipulate_text(cx, |text| {
6070 text.chars()
6071 .fold(String::with_capacity(text.len()), |mut t, c| {
6072 if c.is_uppercase() {
6073 t.extend(c.to_lowercase());
6074 } else {
6075 t.extend(c.to_uppercase());
6076 }
6077 t
6078 })
6079 })
6080 }
6081
6082 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6083 where
6084 Fn: FnMut(&str) -> String,
6085 {
6086 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6087 let buffer = self.buffer.read(cx).snapshot(cx);
6088
6089 let mut new_selections = Vec::new();
6090 let mut edits = Vec::new();
6091 let mut selection_adjustment = 0i32;
6092
6093 for selection in self.selections.all::<usize>(cx) {
6094 let selection_is_empty = selection.is_empty();
6095
6096 let (start, end) = if selection_is_empty {
6097 let word_range = movement::surrounding_word(
6098 &display_map,
6099 selection.start.to_display_point(&display_map),
6100 );
6101 let start = word_range.start.to_offset(&display_map, Bias::Left);
6102 let end = word_range.end.to_offset(&display_map, Bias::Left);
6103 (start, end)
6104 } else {
6105 (selection.start, selection.end)
6106 };
6107
6108 let text = buffer.text_for_range(start..end).collect::<String>();
6109 let old_length = text.len() as i32;
6110 let text = callback(&text);
6111
6112 new_selections.push(Selection {
6113 start: (start as i32 - selection_adjustment) as usize,
6114 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6115 goal: SelectionGoal::None,
6116 ..selection
6117 });
6118
6119 selection_adjustment += old_length - text.len() as i32;
6120
6121 edits.push((start..end, text));
6122 }
6123
6124 self.transact(cx, |this, cx| {
6125 this.buffer.update(cx, |buffer, cx| {
6126 buffer.edit(edits, None, cx);
6127 });
6128
6129 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6130 s.select(new_selections);
6131 });
6132
6133 this.request_autoscroll(Autoscroll::fit(), cx);
6134 });
6135 }
6136
6137 pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
6138 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6139 let buffer = &display_map.buffer_snapshot;
6140 let selections = self.selections.all::<Point>(cx);
6141
6142 let mut edits = Vec::new();
6143 let mut selections_iter = selections.iter().peekable();
6144 while let Some(selection) = selections_iter.next() {
6145 let mut rows = selection.spanned_rows(false, &display_map);
6146 // duplicate line-wise
6147 if whole_lines || selection.start == selection.end {
6148 // Avoid duplicating the same lines twice.
6149 while let Some(next_selection) = selections_iter.peek() {
6150 let next_rows = next_selection.spanned_rows(false, &display_map);
6151 if next_rows.start < rows.end {
6152 rows.end = next_rows.end;
6153 selections_iter.next().unwrap();
6154 } else {
6155 break;
6156 }
6157 }
6158
6159 // Copy the text from the selected row region and splice it either at the start
6160 // or end of the region.
6161 let start = Point::new(rows.start.0, 0);
6162 let end = Point::new(
6163 rows.end.previous_row().0,
6164 buffer.line_len(rows.end.previous_row()),
6165 );
6166 let text = buffer
6167 .text_for_range(start..end)
6168 .chain(Some("\n"))
6169 .collect::<String>();
6170 let insert_location = if upwards {
6171 Point::new(rows.end.0, 0)
6172 } else {
6173 start
6174 };
6175 edits.push((insert_location..insert_location, text));
6176 } else {
6177 // duplicate character-wise
6178 let start = selection.start;
6179 let end = selection.end;
6180 let text = buffer.text_for_range(start..end).collect::<String>();
6181 edits.push((selection.end..selection.end, text));
6182 }
6183 }
6184
6185 self.transact(cx, |this, cx| {
6186 this.buffer.update(cx, |buffer, cx| {
6187 buffer.edit(edits, None, cx);
6188 });
6189
6190 this.request_autoscroll(Autoscroll::fit(), cx);
6191 });
6192 }
6193
6194 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6195 self.duplicate(true, true, cx);
6196 }
6197
6198 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6199 self.duplicate(false, true, cx);
6200 }
6201
6202 pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
6203 self.duplicate(false, false, cx);
6204 }
6205
6206 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6207 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6208 let buffer = self.buffer.read(cx).snapshot(cx);
6209
6210 let mut edits = Vec::new();
6211 let mut unfold_ranges = Vec::new();
6212 let mut refold_creases = Vec::new();
6213
6214 let selections = self.selections.all::<Point>(cx);
6215 let mut selections = selections.iter().peekable();
6216 let mut contiguous_row_selections = Vec::new();
6217 let mut new_selections = Vec::new();
6218
6219 while let Some(selection) = selections.next() {
6220 // Find all the selections that span a contiguous row range
6221 let (start_row, end_row) = consume_contiguous_rows(
6222 &mut contiguous_row_selections,
6223 selection,
6224 &display_map,
6225 &mut selections,
6226 );
6227
6228 // Move the text spanned by the row range to be before the line preceding the row range
6229 if start_row.0 > 0 {
6230 let range_to_move = Point::new(
6231 start_row.previous_row().0,
6232 buffer.line_len(start_row.previous_row()),
6233 )
6234 ..Point::new(
6235 end_row.previous_row().0,
6236 buffer.line_len(end_row.previous_row()),
6237 );
6238 let insertion_point = display_map
6239 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6240 .0;
6241
6242 // Don't move lines across excerpts
6243 if buffer
6244 .excerpt_boundaries_in_range((
6245 Bound::Excluded(insertion_point),
6246 Bound::Included(range_to_move.end),
6247 ))
6248 .next()
6249 .is_none()
6250 {
6251 let text = buffer
6252 .text_for_range(range_to_move.clone())
6253 .flat_map(|s| s.chars())
6254 .skip(1)
6255 .chain(['\n'])
6256 .collect::<String>();
6257
6258 edits.push((
6259 buffer.anchor_after(range_to_move.start)
6260 ..buffer.anchor_before(range_to_move.end),
6261 String::new(),
6262 ));
6263 let insertion_anchor = buffer.anchor_after(insertion_point);
6264 edits.push((insertion_anchor..insertion_anchor, text));
6265
6266 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6267
6268 // Move selections up
6269 new_selections.extend(contiguous_row_selections.drain(..).map(
6270 |mut selection| {
6271 selection.start.row -= row_delta;
6272 selection.end.row -= row_delta;
6273 selection
6274 },
6275 ));
6276
6277 // Move folds up
6278 unfold_ranges.push(range_to_move.clone());
6279 for fold in display_map.folds_in_range(
6280 buffer.anchor_before(range_to_move.start)
6281 ..buffer.anchor_after(range_to_move.end),
6282 ) {
6283 let mut start = fold.range.start.to_point(&buffer);
6284 let mut end = fold.range.end.to_point(&buffer);
6285 start.row -= row_delta;
6286 end.row -= row_delta;
6287 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6288 }
6289 }
6290 }
6291
6292 // If we didn't move line(s), preserve the existing selections
6293 new_selections.append(&mut contiguous_row_selections);
6294 }
6295
6296 self.transact(cx, |this, cx| {
6297 this.unfold_ranges(&unfold_ranges, true, true, cx);
6298 this.buffer.update(cx, |buffer, cx| {
6299 for (range, text) in edits {
6300 buffer.edit([(range, text)], None, cx);
6301 }
6302 });
6303 this.fold_creases(refold_creases, true, cx);
6304 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6305 s.select(new_selections);
6306 })
6307 });
6308 }
6309
6310 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6311 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6312 let buffer = self.buffer.read(cx).snapshot(cx);
6313
6314 let mut edits = Vec::new();
6315 let mut unfold_ranges = Vec::new();
6316 let mut refold_creases = Vec::new();
6317
6318 let selections = self.selections.all::<Point>(cx);
6319 let mut selections = selections.iter().peekable();
6320 let mut contiguous_row_selections = Vec::new();
6321 let mut new_selections = Vec::new();
6322
6323 while let Some(selection) = selections.next() {
6324 // Find all the selections that span a contiguous row range
6325 let (start_row, end_row) = consume_contiguous_rows(
6326 &mut contiguous_row_selections,
6327 selection,
6328 &display_map,
6329 &mut selections,
6330 );
6331
6332 // Move the text spanned by the row range to be after the last line of the row range
6333 if end_row.0 <= buffer.max_point().row {
6334 let range_to_move =
6335 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6336 let insertion_point = display_map
6337 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6338 .0;
6339
6340 // Don't move lines across excerpt boundaries
6341 if buffer
6342 .excerpt_boundaries_in_range((
6343 Bound::Excluded(range_to_move.start),
6344 Bound::Included(insertion_point),
6345 ))
6346 .next()
6347 .is_none()
6348 {
6349 let mut text = String::from("\n");
6350 text.extend(buffer.text_for_range(range_to_move.clone()));
6351 text.pop(); // Drop trailing newline
6352 edits.push((
6353 buffer.anchor_after(range_to_move.start)
6354 ..buffer.anchor_before(range_to_move.end),
6355 String::new(),
6356 ));
6357 let insertion_anchor = buffer.anchor_after(insertion_point);
6358 edits.push((insertion_anchor..insertion_anchor, text));
6359
6360 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6361
6362 // Move selections down
6363 new_selections.extend(contiguous_row_selections.drain(..).map(
6364 |mut selection| {
6365 selection.start.row += row_delta;
6366 selection.end.row += row_delta;
6367 selection
6368 },
6369 ));
6370
6371 // Move folds down
6372 unfold_ranges.push(range_to_move.clone());
6373 for fold in display_map.folds_in_range(
6374 buffer.anchor_before(range_to_move.start)
6375 ..buffer.anchor_after(range_to_move.end),
6376 ) {
6377 let mut start = fold.range.start.to_point(&buffer);
6378 let mut end = fold.range.end.to_point(&buffer);
6379 start.row += row_delta;
6380 end.row += row_delta;
6381 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6382 }
6383 }
6384 }
6385
6386 // If we didn't move line(s), preserve the existing selections
6387 new_selections.append(&mut contiguous_row_selections);
6388 }
6389
6390 self.transact(cx, |this, cx| {
6391 this.unfold_ranges(&unfold_ranges, true, true, cx);
6392 this.buffer.update(cx, |buffer, cx| {
6393 for (range, text) in edits {
6394 buffer.edit([(range, text)], None, cx);
6395 }
6396 });
6397 this.fold_creases(refold_creases, true, cx);
6398 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6399 });
6400 }
6401
6402 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6403 let text_layout_details = &self.text_layout_details(cx);
6404 self.transact(cx, |this, cx| {
6405 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6406 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6407 let line_mode = s.line_mode;
6408 s.move_with(|display_map, selection| {
6409 if !selection.is_empty() || line_mode {
6410 return;
6411 }
6412
6413 let mut head = selection.head();
6414 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6415 if head.column() == display_map.line_len(head.row()) {
6416 transpose_offset = display_map
6417 .buffer_snapshot
6418 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6419 }
6420
6421 if transpose_offset == 0 {
6422 return;
6423 }
6424
6425 *head.column_mut() += 1;
6426 head = display_map.clip_point(head, Bias::Right);
6427 let goal = SelectionGoal::HorizontalPosition(
6428 display_map
6429 .x_for_display_point(head, text_layout_details)
6430 .into(),
6431 );
6432 selection.collapse_to(head, goal);
6433
6434 let transpose_start = display_map
6435 .buffer_snapshot
6436 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6437 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6438 let transpose_end = display_map
6439 .buffer_snapshot
6440 .clip_offset(transpose_offset + 1, Bias::Right);
6441 if let Some(ch) =
6442 display_map.buffer_snapshot.chars_at(transpose_start).next()
6443 {
6444 edits.push((transpose_start..transpose_offset, String::new()));
6445 edits.push((transpose_end..transpose_end, ch.to_string()));
6446 }
6447 }
6448 });
6449 edits
6450 });
6451 this.buffer
6452 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6453 let selections = this.selections.all::<usize>(cx);
6454 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6455 s.select(selections);
6456 });
6457 });
6458 }
6459
6460 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6461 self.rewrap_impl(IsVimMode::No, cx)
6462 }
6463
6464 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
6465 let buffer = self.buffer.read(cx).snapshot(cx);
6466 let selections = self.selections.all::<Point>(cx);
6467 let mut selections = selections.iter().peekable();
6468
6469 let mut edits = Vec::new();
6470 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6471
6472 while let Some(selection) = selections.next() {
6473 let mut start_row = selection.start.row;
6474 let mut end_row = selection.end.row;
6475
6476 // Skip selections that overlap with a range that has already been rewrapped.
6477 let selection_range = start_row..end_row;
6478 if rewrapped_row_ranges
6479 .iter()
6480 .any(|range| range.overlaps(&selection_range))
6481 {
6482 continue;
6483 }
6484
6485 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
6486
6487 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6488 match language_scope.language_name().0.as_ref() {
6489 "Markdown" | "Plain Text" => {
6490 should_rewrap = true;
6491 }
6492 _ => {}
6493 }
6494 }
6495
6496 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
6497
6498 // Since not all lines in the selection may be at the same indent
6499 // level, choose the indent size that is the most common between all
6500 // of the lines.
6501 //
6502 // If there is a tie, we use the deepest indent.
6503 let (indent_size, indent_end) = {
6504 let mut indent_size_occurrences = HashMap::default();
6505 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6506
6507 for row in start_row..=end_row {
6508 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6509 rows_by_indent_size.entry(indent).or_default().push(row);
6510 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6511 }
6512
6513 let indent_size = indent_size_occurrences
6514 .into_iter()
6515 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
6516 .map(|(indent, _)| indent)
6517 .unwrap_or_default();
6518 let row = rows_by_indent_size[&indent_size][0];
6519 let indent_end = Point::new(row, indent_size.len);
6520
6521 (indent_size, indent_end)
6522 };
6523
6524 let mut line_prefix = indent_size.chars().collect::<String>();
6525
6526 if let Some(comment_prefix) =
6527 buffer
6528 .language_scope_at(selection.head())
6529 .and_then(|language| {
6530 language
6531 .line_comment_prefixes()
6532 .iter()
6533 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6534 .cloned()
6535 })
6536 {
6537 line_prefix.push_str(&comment_prefix);
6538 should_rewrap = true;
6539 }
6540
6541 if !should_rewrap {
6542 continue;
6543 }
6544
6545 if selection.is_empty() {
6546 'expand_upwards: while start_row > 0 {
6547 let prev_row = start_row - 1;
6548 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6549 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6550 {
6551 start_row = prev_row;
6552 } else {
6553 break 'expand_upwards;
6554 }
6555 }
6556
6557 'expand_downwards: while end_row < buffer.max_point().row {
6558 let next_row = end_row + 1;
6559 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6560 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6561 {
6562 end_row = next_row;
6563 } else {
6564 break 'expand_downwards;
6565 }
6566 }
6567 }
6568
6569 let start = Point::new(start_row, 0);
6570 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6571 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6572 let Some(lines_without_prefixes) = selection_text
6573 .lines()
6574 .map(|line| {
6575 line.strip_prefix(&line_prefix)
6576 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6577 .ok_or_else(|| {
6578 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6579 })
6580 })
6581 .collect::<Result<Vec<_>, _>>()
6582 .log_err()
6583 else {
6584 continue;
6585 };
6586
6587 let wrap_column = buffer
6588 .settings_at(Point::new(start_row, 0), cx)
6589 .preferred_line_length as usize;
6590 let wrapped_text = wrap_with_prefix(
6591 line_prefix,
6592 lines_without_prefixes.join(" "),
6593 wrap_column,
6594 tab_size,
6595 );
6596
6597 // TODO: should always use char-based diff while still supporting cursor behavior that
6598 // matches vim.
6599 let diff = match is_vim_mode {
6600 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
6601 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
6602 };
6603 let mut offset = start.to_offset(&buffer);
6604 let mut moved_since_edit = true;
6605
6606 for change in diff.iter_all_changes() {
6607 let value = change.value();
6608 match change.tag() {
6609 ChangeTag::Equal => {
6610 offset += value.len();
6611 moved_since_edit = true;
6612 }
6613 ChangeTag::Delete => {
6614 let start = buffer.anchor_after(offset);
6615 let end = buffer.anchor_before(offset + value.len());
6616
6617 if moved_since_edit {
6618 edits.push((start..end, String::new()));
6619 } else {
6620 edits.last_mut().unwrap().0.end = end;
6621 }
6622
6623 offset += value.len();
6624 moved_since_edit = false;
6625 }
6626 ChangeTag::Insert => {
6627 if moved_since_edit {
6628 let anchor = buffer.anchor_after(offset);
6629 edits.push((anchor..anchor, value.to_string()));
6630 } else {
6631 edits.last_mut().unwrap().1.push_str(value);
6632 }
6633
6634 moved_since_edit = false;
6635 }
6636 }
6637 }
6638
6639 rewrapped_row_ranges.push(start_row..=end_row);
6640 }
6641
6642 self.buffer
6643 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6644 }
6645
6646 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
6647 let mut text = String::new();
6648 let buffer = self.buffer.read(cx).snapshot(cx);
6649 let mut selections = self.selections.all::<Point>(cx);
6650 let mut clipboard_selections = Vec::with_capacity(selections.len());
6651 {
6652 let max_point = buffer.max_point();
6653 let mut is_first = true;
6654 for selection in &mut selections {
6655 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6656 if is_entire_line {
6657 selection.start = Point::new(selection.start.row, 0);
6658 if !selection.is_empty() && selection.end.column == 0 {
6659 selection.end = cmp::min(max_point, selection.end);
6660 } else {
6661 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6662 }
6663 selection.goal = SelectionGoal::None;
6664 }
6665 if is_first {
6666 is_first = false;
6667 } else {
6668 text += "\n";
6669 }
6670 let mut len = 0;
6671 for chunk in buffer.text_for_range(selection.start..selection.end) {
6672 text.push_str(chunk);
6673 len += chunk.len();
6674 }
6675 clipboard_selections.push(ClipboardSelection {
6676 len,
6677 is_entire_line,
6678 first_line_indent: buffer
6679 .indent_size_for_line(MultiBufferRow(selection.start.row))
6680 .len,
6681 });
6682 }
6683 }
6684
6685 self.transact(cx, |this, cx| {
6686 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6687 s.select(selections);
6688 });
6689 this.insert("", cx);
6690 });
6691 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
6692 }
6693
6694 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6695 let item = self.cut_common(cx);
6696 cx.write_to_clipboard(item);
6697 }
6698
6699 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
6700 self.change_selections(None, cx, |s| {
6701 s.move_with(|snapshot, sel| {
6702 if sel.is_empty() {
6703 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
6704 }
6705 });
6706 });
6707 let item = self.cut_common(cx);
6708 cx.set_global(KillRing(item))
6709 }
6710
6711 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
6712 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
6713 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
6714 (kill_ring.text().to_string(), kill_ring.metadata_json())
6715 } else {
6716 return;
6717 }
6718 } else {
6719 return;
6720 };
6721 self.do_paste(&text, metadata, false, cx);
6722 }
6723
6724 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6725 let selections = self.selections.all::<Point>(cx);
6726 let buffer = self.buffer.read(cx).read(cx);
6727 let mut text = String::new();
6728
6729 let mut clipboard_selections = Vec::with_capacity(selections.len());
6730 {
6731 let max_point = buffer.max_point();
6732 let mut is_first = true;
6733 for selection in selections.iter() {
6734 let mut start = selection.start;
6735 let mut end = selection.end;
6736 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6737 if is_entire_line {
6738 start = Point::new(start.row, 0);
6739 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6740 }
6741 if is_first {
6742 is_first = false;
6743 } else {
6744 text += "\n";
6745 }
6746 let mut len = 0;
6747 for chunk in buffer.text_for_range(start..end) {
6748 text.push_str(chunk);
6749 len += chunk.len();
6750 }
6751 clipboard_selections.push(ClipboardSelection {
6752 len,
6753 is_entire_line,
6754 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6755 });
6756 }
6757 }
6758
6759 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6760 text,
6761 clipboard_selections,
6762 ));
6763 }
6764
6765 pub fn do_paste(
6766 &mut self,
6767 text: &String,
6768 clipboard_selections: Option<Vec<ClipboardSelection>>,
6769 handle_entire_lines: bool,
6770 cx: &mut ViewContext<Self>,
6771 ) {
6772 if self.read_only(cx) {
6773 return;
6774 }
6775
6776 let clipboard_text = Cow::Borrowed(text);
6777
6778 self.transact(cx, |this, cx| {
6779 if let Some(mut clipboard_selections) = clipboard_selections {
6780 let old_selections = this.selections.all::<usize>(cx);
6781 let all_selections_were_entire_line =
6782 clipboard_selections.iter().all(|s| s.is_entire_line);
6783 let first_selection_indent_column =
6784 clipboard_selections.first().map(|s| s.first_line_indent);
6785 if clipboard_selections.len() != old_selections.len() {
6786 clipboard_selections.drain(..);
6787 }
6788 let cursor_offset = this.selections.last::<usize>(cx).head();
6789 let mut auto_indent_on_paste = true;
6790
6791 this.buffer.update(cx, |buffer, cx| {
6792 let snapshot = buffer.read(cx);
6793 auto_indent_on_paste =
6794 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
6795
6796 let mut start_offset = 0;
6797 let mut edits = Vec::new();
6798 let mut original_indent_columns = Vec::new();
6799 for (ix, selection) in old_selections.iter().enumerate() {
6800 let to_insert;
6801 let entire_line;
6802 let original_indent_column;
6803 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6804 let end_offset = start_offset + clipboard_selection.len;
6805 to_insert = &clipboard_text[start_offset..end_offset];
6806 entire_line = clipboard_selection.is_entire_line;
6807 start_offset = end_offset + 1;
6808 original_indent_column = Some(clipboard_selection.first_line_indent);
6809 } else {
6810 to_insert = clipboard_text.as_str();
6811 entire_line = all_selections_were_entire_line;
6812 original_indent_column = first_selection_indent_column
6813 }
6814
6815 // If the corresponding selection was empty when this slice of the
6816 // clipboard text was written, then the entire line containing the
6817 // selection was copied. If this selection is also currently empty,
6818 // then paste the line before the current line of the buffer.
6819 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6820 let column = selection.start.to_point(&snapshot).column as usize;
6821 let line_start = selection.start - column;
6822 line_start..line_start
6823 } else {
6824 selection.range()
6825 };
6826
6827 edits.push((range, to_insert));
6828 original_indent_columns.extend(original_indent_column);
6829 }
6830 drop(snapshot);
6831
6832 buffer.edit(
6833 edits,
6834 if auto_indent_on_paste {
6835 Some(AutoindentMode::Block {
6836 original_indent_columns,
6837 })
6838 } else {
6839 None
6840 },
6841 cx,
6842 );
6843 });
6844
6845 let selections = this.selections.all::<usize>(cx);
6846 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6847 } else {
6848 this.insert(&clipboard_text, cx);
6849 }
6850 });
6851 }
6852
6853 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
6854 if let Some(item) = cx.read_from_clipboard() {
6855 let entries = item.entries();
6856
6857 match entries.first() {
6858 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
6859 // of all the pasted entries.
6860 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
6861 .do_paste(
6862 clipboard_string.text(),
6863 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
6864 true,
6865 cx,
6866 ),
6867 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
6868 }
6869 }
6870 }
6871
6872 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
6873 if self.read_only(cx) {
6874 return;
6875 }
6876
6877 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
6878 if let Some((selections, _)) =
6879 self.selection_history.transaction(transaction_id).cloned()
6880 {
6881 self.change_selections(None, cx, |s| {
6882 s.select_anchors(selections.to_vec());
6883 });
6884 }
6885 self.request_autoscroll(Autoscroll::fit(), cx);
6886 self.unmark_text(cx);
6887 self.refresh_inline_completion(true, false, cx);
6888 cx.emit(EditorEvent::Edited { transaction_id });
6889 cx.emit(EditorEvent::TransactionUndone { transaction_id });
6890 }
6891 }
6892
6893 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
6894 if self.read_only(cx) {
6895 return;
6896 }
6897
6898 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
6899 if let Some((_, Some(selections))) =
6900 self.selection_history.transaction(transaction_id).cloned()
6901 {
6902 self.change_selections(None, cx, |s| {
6903 s.select_anchors(selections.to_vec());
6904 });
6905 }
6906 self.request_autoscroll(Autoscroll::fit(), cx);
6907 self.unmark_text(cx);
6908 self.refresh_inline_completion(true, false, cx);
6909 cx.emit(EditorEvent::Edited { transaction_id });
6910 }
6911 }
6912
6913 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
6914 self.buffer
6915 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
6916 }
6917
6918 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
6919 self.buffer
6920 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
6921 }
6922
6923 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
6924 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6925 let line_mode = s.line_mode;
6926 s.move_with(|map, selection| {
6927 let cursor = if selection.is_empty() && !line_mode {
6928 movement::left(map, selection.start)
6929 } else {
6930 selection.start
6931 };
6932 selection.collapse_to(cursor, SelectionGoal::None);
6933 });
6934 })
6935 }
6936
6937 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
6938 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6939 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
6940 })
6941 }
6942
6943 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
6944 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6945 let line_mode = s.line_mode;
6946 s.move_with(|map, selection| {
6947 let cursor = if selection.is_empty() && !line_mode {
6948 movement::right(map, selection.end)
6949 } else {
6950 selection.end
6951 };
6952 selection.collapse_to(cursor, SelectionGoal::None)
6953 });
6954 })
6955 }
6956
6957 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
6958 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6959 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
6960 })
6961 }
6962
6963 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
6964 if self.take_rename(true, cx).is_some() {
6965 return;
6966 }
6967
6968 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6969 cx.propagate();
6970 return;
6971 }
6972
6973 let text_layout_details = &self.text_layout_details(cx);
6974 let selection_count = self.selections.count();
6975 let first_selection = self.selections.first_anchor();
6976
6977 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6978 let line_mode = s.line_mode;
6979 s.move_with(|map, selection| {
6980 if !selection.is_empty() && !line_mode {
6981 selection.goal = SelectionGoal::None;
6982 }
6983 let (cursor, goal) = movement::up(
6984 map,
6985 selection.start,
6986 selection.goal,
6987 false,
6988 text_layout_details,
6989 );
6990 selection.collapse_to(cursor, goal);
6991 });
6992 });
6993
6994 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
6995 {
6996 cx.propagate();
6997 }
6998 }
6999
7000 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7001 if self.take_rename(true, cx).is_some() {
7002 return;
7003 }
7004
7005 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7006 cx.propagate();
7007 return;
7008 }
7009
7010 let text_layout_details = &self.text_layout_details(cx);
7011
7012 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7013 let line_mode = s.line_mode;
7014 s.move_with(|map, selection| {
7015 if !selection.is_empty() && !line_mode {
7016 selection.goal = SelectionGoal::None;
7017 }
7018 let (cursor, goal) = movement::up_by_rows(
7019 map,
7020 selection.start,
7021 action.lines,
7022 selection.goal,
7023 false,
7024 text_layout_details,
7025 );
7026 selection.collapse_to(cursor, goal);
7027 });
7028 })
7029 }
7030
7031 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7032 if self.take_rename(true, cx).is_some() {
7033 return;
7034 }
7035
7036 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7037 cx.propagate();
7038 return;
7039 }
7040
7041 let text_layout_details = &self.text_layout_details(cx);
7042
7043 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7044 let line_mode = s.line_mode;
7045 s.move_with(|map, selection| {
7046 if !selection.is_empty() && !line_mode {
7047 selection.goal = SelectionGoal::None;
7048 }
7049 let (cursor, goal) = movement::down_by_rows(
7050 map,
7051 selection.start,
7052 action.lines,
7053 selection.goal,
7054 false,
7055 text_layout_details,
7056 );
7057 selection.collapse_to(cursor, goal);
7058 });
7059 })
7060 }
7061
7062 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7063 let text_layout_details = &self.text_layout_details(cx);
7064 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7065 s.move_heads_with(|map, head, goal| {
7066 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7067 })
7068 })
7069 }
7070
7071 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7072 let text_layout_details = &self.text_layout_details(cx);
7073 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7074 s.move_heads_with(|map, head, goal| {
7075 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7076 })
7077 })
7078 }
7079
7080 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7081 let Some(row_count) = self.visible_row_count() else {
7082 return;
7083 };
7084
7085 let text_layout_details = &self.text_layout_details(cx);
7086
7087 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7088 s.move_heads_with(|map, head, goal| {
7089 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7090 })
7091 })
7092 }
7093
7094 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7095 if self.take_rename(true, cx).is_some() {
7096 return;
7097 }
7098
7099 if self
7100 .context_menu
7101 .borrow_mut()
7102 .as_mut()
7103 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7104 .unwrap_or(false)
7105 {
7106 return;
7107 }
7108
7109 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7110 cx.propagate();
7111 return;
7112 }
7113
7114 let Some(row_count) = self.visible_row_count() else {
7115 return;
7116 };
7117
7118 let autoscroll = if action.center_cursor {
7119 Autoscroll::center()
7120 } else {
7121 Autoscroll::fit()
7122 };
7123
7124 let text_layout_details = &self.text_layout_details(cx);
7125
7126 self.change_selections(Some(autoscroll), cx, |s| {
7127 let line_mode = s.line_mode;
7128 s.move_with(|map, selection| {
7129 if !selection.is_empty() && !line_mode {
7130 selection.goal = SelectionGoal::None;
7131 }
7132 let (cursor, goal) = movement::up_by_rows(
7133 map,
7134 selection.end,
7135 row_count,
7136 selection.goal,
7137 false,
7138 text_layout_details,
7139 );
7140 selection.collapse_to(cursor, goal);
7141 });
7142 });
7143 }
7144
7145 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7146 let text_layout_details = &self.text_layout_details(cx);
7147 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7148 s.move_heads_with(|map, head, goal| {
7149 movement::up(map, head, goal, false, text_layout_details)
7150 })
7151 })
7152 }
7153
7154 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7155 self.take_rename(true, cx);
7156
7157 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7158 cx.propagate();
7159 return;
7160 }
7161
7162 let text_layout_details = &self.text_layout_details(cx);
7163 let selection_count = self.selections.count();
7164 let first_selection = self.selections.first_anchor();
7165
7166 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7167 let line_mode = s.line_mode;
7168 s.move_with(|map, selection| {
7169 if !selection.is_empty() && !line_mode {
7170 selection.goal = SelectionGoal::None;
7171 }
7172 let (cursor, goal) = movement::down(
7173 map,
7174 selection.end,
7175 selection.goal,
7176 false,
7177 text_layout_details,
7178 );
7179 selection.collapse_to(cursor, goal);
7180 });
7181 });
7182
7183 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7184 {
7185 cx.propagate();
7186 }
7187 }
7188
7189 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7190 let Some(row_count) = self.visible_row_count() else {
7191 return;
7192 };
7193
7194 let text_layout_details = &self.text_layout_details(cx);
7195
7196 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7197 s.move_heads_with(|map, head, goal| {
7198 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7199 })
7200 })
7201 }
7202
7203 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7204 if self.take_rename(true, cx).is_some() {
7205 return;
7206 }
7207
7208 if self
7209 .context_menu
7210 .borrow_mut()
7211 .as_mut()
7212 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7213 .unwrap_or(false)
7214 {
7215 return;
7216 }
7217
7218 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7219 cx.propagate();
7220 return;
7221 }
7222
7223 let Some(row_count) = self.visible_row_count() else {
7224 return;
7225 };
7226
7227 let autoscroll = if action.center_cursor {
7228 Autoscroll::center()
7229 } else {
7230 Autoscroll::fit()
7231 };
7232
7233 let text_layout_details = &self.text_layout_details(cx);
7234 self.change_selections(Some(autoscroll), cx, |s| {
7235 let line_mode = s.line_mode;
7236 s.move_with(|map, selection| {
7237 if !selection.is_empty() && !line_mode {
7238 selection.goal = SelectionGoal::None;
7239 }
7240 let (cursor, goal) = movement::down_by_rows(
7241 map,
7242 selection.end,
7243 row_count,
7244 selection.goal,
7245 false,
7246 text_layout_details,
7247 );
7248 selection.collapse_to(cursor, goal);
7249 });
7250 });
7251 }
7252
7253 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7254 let text_layout_details = &self.text_layout_details(cx);
7255 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7256 s.move_heads_with(|map, head, goal| {
7257 movement::down(map, head, goal, false, text_layout_details)
7258 })
7259 });
7260 }
7261
7262 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7263 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7264 context_menu.select_first(self.completion_provider.as_deref(), cx);
7265 }
7266 }
7267
7268 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7269 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7270 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7271 }
7272 }
7273
7274 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7275 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7276 context_menu.select_next(self.completion_provider.as_deref(), cx);
7277 }
7278 }
7279
7280 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7281 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7282 context_menu.select_last(self.completion_provider.as_deref(), cx);
7283 }
7284 }
7285
7286 pub fn move_to_previous_word_start(
7287 &mut self,
7288 _: &MoveToPreviousWordStart,
7289 cx: &mut ViewContext<Self>,
7290 ) {
7291 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7292 s.move_cursors_with(|map, head, _| {
7293 (
7294 movement::previous_word_start(map, head),
7295 SelectionGoal::None,
7296 )
7297 });
7298 })
7299 }
7300
7301 pub fn move_to_previous_subword_start(
7302 &mut self,
7303 _: &MoveToPreviousSubwordStart,
7304 cx: &mut ViewContext<Self>,
7305 ) {
7306 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7307 s.move_cursors_with(|map, head, _| {
7308 (
7309 movement::previous_subword_start(map, head),
7310 SelectionGoal::None,
7311 )
7312 });
7313 })
7314 }
7315
7316 pub fn select_to_previous_word_start(
7317 &mut self,
7318 _: &SelectToPreviousWordStart,
7319 cx: &mut ViewContext<Self>,
7320 ) {
7321 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7322 s.move_heads_with(|map, head, _| {
7323 (
7324 movement::previous_word_start(map, head),
7325 SelectionGoal::None,
7326 )
7327 });
7328 })
7329 }
7330
7331 pub fn select_to_previous_subword_start(
7332 &mut self,
7333 _: &SelectToPreviousSubwordStart,
7334 cx: &mut ViewContext<Self>,
7335 ) {
7336 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7337 s.move_heads_with(|map, head, _| {
7338 (
7339 movement::previous_subword_start(map, head),
7340 SelectionGoal::None,
7341 )
7342 });
7343 })
7344 }
7345
7346 pub fn delete_to_previous_word_start(
7347 &mut self,
7348 action: &DeleteToPreviousWordStart,
7349 cx: &mut ViewContext<Self>,
7350 ) {
7351 self.transact(cx, |this, cx| {
7352 this.select_autoclose_pair(cx);
7353 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7354 let line_mode = s.line_mode;
7355 s.move_with(|map, selection| {
7356 if selection.is_empty() && !line_mode {
7357 let cursor = if action.ignore_newlines {
7358 movement::previous_word_start(map, selection.head())
7359 } else {
7360 movement::previous_word_start_or_newline(map, selection.head())
7361 };
7362 selection.set_head(cursor, SelectionGoal::None);
7363 }
7364 });
7365 });
7366 this.insert("", cx);
7367 });
7368 }
7369
7370 pub fn delete_to_previous_subword_start(
7371 &mut self,
7372 _: &DeleteToPreviousSubwordStart,
7373 cx: &mut ViewContext<Self>,
7374 ) {
7375 self.transact(cx, |this, cx| {
7376 this.select_autoclose_pair(cx);
7377 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7378 let line_mode = s.line_mode;
7379 s.move_with(|map, selection| {
7380 if selection.is_empty() && !line_mode {
7381 let cursor = movement::previous_subword_start(map, selection.head());
7382 selection.set_head(cursor, SelectionGoal::None);
7383 }
7384 });
7385 });
7386 this.insert("", cx);
7387 });
7388 }
7389
7390 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7391 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7392 s.move_cursors_with(|map, head, _| {
7393 (movement::next_word_end(map, head), SelectionGoal::None)
7394 });
7395 })
7396 }
7397
7398 pub fn move_to_next_subword_end(
7399 &mut self,
7400 _: &MoveToNextSubwordEnd,
7401 cx: &mut ViewContext<Self>,
7402 ) {
7403 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7404 s.move_cursors_with(|map, head, _| {
7405 (movement::next_subword_end(map, head), SelectionGoal::None)
7406 });
7407 })
7408 }
7409
7410 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7411 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7412 s.move_heads_with(|map, head, _| {
7413 (movement::next_word_end(map, head), SelectionGoal::None)
7414 });
7415 })
7416 }
7417
7418 pub fn select_to_next_subword_end(
7419 &mut self,
7420 _: &SelectToNextSubwordEnd,
7421 cx: &mut ViewContext<Self>,
7422 ) {
7423 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7424 s.move_heads_with(|map, head, _| {
7425 (movement::next_subword_end(map, head), SelectionGoal::None)
7426 });
7427 })
7428 }
7429
7430 pub fn delete_to_next_word_end(
7431 &mut self,
7432 action: &DeleteToNextWordEnd,
7433 cx: &mut ViewContext<Self>,
7434 ) {
7435 self.transact(cx, |this, cx| {
7436 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7437 let line_mode = s.line_mode;
7438 s.move_with(|map, selection| {
7439 if selection.is_empty() && !line_mode {
7440 let cursor = if action.ignore_newlines {
7441 movement::next_word_end(map, selection.head())
7442 } else {
7443 movement::next_word_end_or_newline(map, selection.head())
7444 };
7445 selection.set_head(cursor, SelectionGoal::None);
7446 }
7447 });
7448 });
7449 this.insert("", cx);
7450 });
7451 }
7452
7453 pub fn delete_to_next_subword_end(
7454 &mut self,
7455 _: &DeleteToNextSubwordEnd,
7456 cx: &mut ViewContext<Self>,
7457 ) {
7458 self.transact(cx, |this, cx| {
7459 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7460 s.move_with(|map, selection| {
7461 if selection.is_empty() {
7462 let cursor = movement::next_subword_end(map, selection.head());
7463 selection.set_head(cursor, SelectionGoal::None);
7464 }
7465 });
7466 });
7467 this.insert("", cx);
7468 });
7469 }
7470
7471 pub fn move_to_beginning_of_line(
7472 &mut self,
7473 action: &MoveToBeginningOfLine,
7474 cx: &mut ViewContext<Self>,
7475 ) {
7476 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7477 s.move_cursors_with(|map, head, _| {
7478 (
7479 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7480 SelectionGoal::None,
7481 )
7482 });
7483 })
7484 }
7485
7486 pub fn select_to_beginning_of_line(
7487 &mut self,
7488 action: &SelectToBeginningOfLine,
7489 cx: &mut ViewContext<Self>,
7490 ) {
7491 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7492 s.move_heads_with(|map, head, _| {
7493 (
7494 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7495 SelectionGoal::None,
7496 )
7497 });
7498 });
7499 }
7500
7501 pub fn delete_to_beginning_of_line(
7502 &mut self,
7503 _: &DeleteToBeginningOfLine,
7504 cx: &mut ViewContext<Self>,
7505 ) {
7506 self.transact(cx, |this, cx| {
7507 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7508 s.move_with(|_, selection| {
7509 selection.reversed = true;
7510 });
7511 });
7512
7513 this.select_to_beginning_of_line(
7514 &SelectToBeginningOfLine {
7515 stop_at_soft_wraps: false,
7516 },
7517 cx,
7518 );
7519 this.backspace(&Backspace, cx);
7520 });
7521 }
7522
7523 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7524 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7525 s.move_cursors_with(|map, head, _| {
7526 (
7527 movement::line_end(map, head, action.stop_at_soft_wraps),
7528 SelectionGoal::None,
7529 )
7530 });
7531 })
7532 }
7533
7534 pub fn select_to_end_of_line(
7535 &mut self,
7536 action: &SelectToEndOfLine,
7537 cx: &mut ViewContext<Self>,
7538 ) {
7539 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7540 s.move_heads_with(|map, head, _| {
7541 (
7542 movement::line_end(map, head, action.stop_at_soft_wraps),
7543 SelectionGoal::None,
7544 )
7545 });
7546 })
7547 }
7548
7549 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7550 self.transact(cx, |this, cx| {
7551 this.select_to_end_of_line(
7552 &SelectToEndOfLine {
7553 stop_at_soft_wraps: false,
7554 },
7555 cx,
7556 );
7557 this.delete(&Delete, cx);
7558 });
7559 }
7560
7561 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7562 self.transact(cx, |this, cx| {
7563 this.select_to_end_of_line(
7564 &SelectToEndOfLine {
7565 stop_at_soft_wraps: false,
7566 },
7567 cx,
7568 );
7569 this.cut(&Cut, cx);
7570 });
7571 }
7572
7573 pub fn move_to_start_of_paragraph(
7574 &mut self,
7575 _: &MoveToStartOfParagraph,
7576 cx: &mut ViewContext<Self>,
7577 ) {
7578 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7579 cx.propagate();
7580 return;
7581 }
7582
7583 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7584 s.move_with(|map, selection| {
7585 selection.collapse_to(
7586 movement::start_of_paragraph(map, selection.head(), 1),
7587 SelectionGoal::None,
7588 )
7589 });
7590 })
7591 }
7592
7593 pub fn move_to_end_of_paragraph(
7594 &mut self,
7595 _: &MoveToEndOfParagraph,
7596 cx: &mut ViewContext<Self>,
7597 ) {
7598 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7599 cx.propagate();
7600 return;
7601 }
7602
7603 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7604 s.move_with(|map, selection| {
7605 selection.collapse_to(
7606 movement::end_of_paragraph(map, selection.head(), 1),
7607 SelectionGoal::None,
7608 )
7609 });
7610 })
7611 }
7612
7613 pub fn select_to_start_of_paragraph(
7614 &mut self,
7615 _: &SelectToStartOfParagraph,
7616 cx: &mut ViewContext<Self>,
7617 ) {
7618 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7619 cx.propagate();
7620 return;
7621 }
7622
7623 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7624 s.move_heads_with(|map, head, _| {
7625 (
7626 movement::start_of_paragraph(map, head, 1),
7627 SelectionGoal::None,
7628 )
7629 });
7630 })
7631 }
7632
7633 pub fn select_to_end_of_paragraph(
7634 &mut self,
7635 _: &SelectToEndOfParagraph,
7636 cx: &mut ViewContext<Self>,
7637 ) {
7638 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7639 cx.propagate();
7640 return;
7641 }
7642
7643 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7644 s.move_heads_with(|map, head, _| {
7645 (
7646 movement::end_of_paragraph(map, head, 1),
7647 SelectionGoal::None,
7648 )
7649 });
7650 })
7651 }
7652
7653 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7654 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7655 cx.propagate();
7656 return;
7657 }
7658
7659 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7660 s.select_ranges(vec![0..0]);
7661 });
7662 }
7663
7664 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7665 let mut selection = self.selections.last::<Point>(cx);
7666 selection.set_head(Point::zero(), SelectionGoal::None);
7667
7668 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7669 s.select(vec![selection]);
7670 });
7671 }
7672
7673 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7674 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7675 cx.propagate();
7676 return;
7677 }
7678
7679 let cursor = self.buffer.read(cx).read(cx).len();
7680 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7681 s.select_ranges(vec![cursor..cursor])
7682 });
7683 }
7684
7685 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7686 self.nav_history = nav_history;
7687 }
7688
7689 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7690 self.nav_history.as_ref()
7691 }
7692
7693 fn push_to_nav_history(
7694 &mut self,
7695 cursor_anchor: Anchor,
7696 new_position: Option<Point>,
7697 cx: &mut ViewContext<Self>,
7698 ) {
7699 if let Some(nav_history) = self.nav_history.as_mut() {
7700 let buffer = self.buffer.read(cx).read(cx);
7701 let cursor_position = cursor_anchor.to_point(&buffer);
7702 let scroll_state = self.scroll_manager.anchor();
7703 let scroll_top_row = scroll_state.top_row(&buffer);
7704 drop(buffer);
7705
7706 if let Some(new_position) = new_position {
7707 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7708 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7709 return;
7710 }
7711 }
7712
7713 nav_history.push(
7714 Some(NavigationData {
7715 cursor_anchor,
7716 cursor_position,
7717 scroll_anchor: scroll_state,
7718 scroll_top_row,
7719 }),
7720 cx,
7721 );
7722 }
7723 }
7724
7725 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7726 let buffer = self.buffer.read(cx).snapshot(cx);
7727 let mut selection = self.selections.first::<usize>(cx);
7728 selection.set_head(buffer.len(), SelectionGoal::None);
7729 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7730 s.select(vec![selection]);
7731 });
7732 }
7733
7734 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7735 let end = self.buffer.read(cx).read(cx).len();
7736 self.change_selections(None, cx, |s| {
7737 s.select_ranges(vec![0..end]);
7738 });
7739 }
7740
7741 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7742 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7743 let mut selections = self.selections.all::<Point>(cx);
7744 let max_point = display_map.buffer_snapshot.max_point();
7745 for selection in &mut selections {
7746 let rows = selection.spanned_rows(true, &display_map);
7747 selection.start = Point::new(rows.start.0, 0);
7748 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7749 selection.reversed = false;
7750 }
7751 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7752 s.select(selections);
7753 });
7754 }
7755
7756 pub fn split_selection_into_lines(
7757 &mut self,
7758 _: &SplitSelectionIntoLines,
7759 cx: &mut ViewContext<Self>,
7760 ) {
7761 let mut to_unfold = Vec::new();
7762 let mut new_selection_ranges = Vec::new();
7763 {
7764 let selections = self.selections.all::<Point>(cx);
7765 let buffer = self.buffer.read(cx).read(cx);
7766 for selection in selections {
7767 for row in selection.start.row..selection.end.row {
7768 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7769 new_selection_ranges.push(cursor..cursor);
7770 }
7771 new_selection_ranges.push(selection.end..selection.end);
7772 to_unfold.push(selection.start..selection.end);
7773 }
7774 }
7775 self.unfold_ranges(&to_unfold, true, true, cx);
7776 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7777 s.select_ranges(new_selection_ranges);
7778 });
7779 }
7780
7781 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7782 self.add_selection(true, cx);
7783 }
7784
7785 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7786 self.add_selection(false, cx);
7787 }
7788
7789 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7790 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7791 let mut selections = self.selections.all::<Point>(cx);
7792 let text_layout_details = self.text_layout_details(cx);
7793 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7794 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7795 let range = oldest_selection.display_range(&display_map).sorted();
7796
7797 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7798 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7799 let positions = start_x.min(end_x)..start_x.max(end_x);
7800
7801 selections.clear();
7802 let mut stack = Vec::new();
7803 for row in range.start.row().0..=range.end.row().0 {
7804 if let Some(selection) = self.selections.build_columnar_selection(
7805 &display_map,
7806 DisplayRow(row),
7807 &positions,
7808 oldest_selection.reversed,
7809 &text_layout_details,
7810 ) {
7811 stack.push(selection.id);
7812 selections.push(selection);
7813 }
7814 }
7815
7816 if above {
7817 stack.reverse();
7818 }
7819
7820 AddSelectionsState { above, stack }
7821 });
7822
7823 let last_added_selection = *state.stack.last().unwrap();
7824 let mut new_selections = Vec::new();
7825 if above == state.above {
7826 let end_row = if above {
7827 DisplayRow(0)
7828 } else {
7829 display_map.max_point().row()
7830 };
7831
7832 'outer: for selection in selections {
7833 if selection.id == last_added_selection {
7834 let range = selection.display_range(&display_map).sorted();
7835 debug_assert_eq!(range.start.row(), range.end.row());
7836 let mut row = range.start.row();
7837 let positions =
7838 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7839 px(start)..px(end)
7840 } else {
7841 let start_x =
7842 display_map.x_for_display_point(range.start, &text_layout_details);
7843 let end_x =
7844 display_map.x_for_display_point(range.end, &text_layout_details);
7845 start_x.min(end_x)..start_x.max(end_x)
7846 };
7847
7848 while row != end_row {
7849 if above {
7850 row.0 -= 1;
7851 } else {
7852 row.0 += 1;
7853 }
7854
7855 if let Some(new_selection) = self.selections.build_columnar_selection(
7856 &display_map,
7857 row,
7858 &positions,
7859 selection.reversed,
7860 &text_layout_details,
7861 ) {
7862 state.stack.push(new_selection.id);
7863 if above {
7864 new_selections.push(new_selection);
7865 new_selections.push(selection);
7866 } else {
7867 new_selections.push(selection);
7868 new_selections.push(new_selection);
7869 }
7870
7871 continue 'outer;
7872 }
7873 }
7874 }
7875
7876 new_selections.push(selection);
7877 }
7878 } else {
7879 new_selections = selections;
7880 new_selections.retain(|s| s.id != last_added_selection);
7881 state.stack.pop();
7882 }
7883
7884 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7885 s.select(new_selections);
7886 });
7887 if state.stack.len() > 1 {
7888 self.add_selections_state = Some(state);
7889 }
7890 }
7891
7892 pub fn select_next_match_internal(
7893 &mut self,
7894 display_map: &DisplaySnapshot,
7895 replace_newest: bool,
7896 autoscroll: Option<Autoscroll>,
7897 cx: &mut ViewContext<Self>,
7898 ) -> Result<()> {
7899 fn select_next_match_ranges(
7900 this: &mut Editor,
7901 range: Range<usize>,
7902 replace_newest: bool,
7903 auto_scroll: Option<Autoscroll>,
7904 cx: &mut ViewContext<Editor>,
7905 ) {
7906 this.unfold_ranges(&[range.clone()], false, true, cx);
7907 this.change_selections(auto_scroll, cx, |s| {
7908 if replace_newest {
7909 s.delete(s.newest_anchor().id);
7910 }
7911 s.insert_range(range.clone());
7912 });
7913 }
7914
7915 let buffer = &display_map.buffer_snapshot;
7916 let mut selections = self.selections.all::<usize>(cx);
7917 if let Some(mut select_next_state) = self.select_next_state.take() {
7918 let query = &select_next_state.query;
7919 if !select_next_state.done {
7920 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7921 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7922 let mut next_selected_range = None;
7923
7924 let bytes_after_last_selection =
7925 buffer.bytes_in_range(last_selection.end..buffer.len());
7926 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
7927 let query_matches = query
7928 .stream_find_iter(bytes_after_last_selection)
7929 .map(|result| (last_selection.end, result))
7930 .chain(
7931 query
7932 .stream_find_iter(bytes_before_first_selection)
7933 .map(|result| (0, result)),
7934 );
7935
7936 for (start_offset, query_match) in query_matches {
7937 let query_match = query_match.unwrap(); // can only fail due to I/O
7938 let offset_range =
7939 start_offset + query_match.start()..start_offset + query_match.end();
7940 let display_range = offset_range.start.to_display_point(display_map)
7941 ..offset_range.end.to_display_point(display_map);
7942
7943 if !select_next_state.wordwise
7944 || (!movement::is_inside_word(display_map, display_range.start)
7945 && !movement::is_inside_word(display_map, display_range.end))
7946 {
7947 // TODO: This is n^2, because we might check all the selections
7948 if !selections
7949 .iter()
7950 .any(|selection| selection.range().overlaps(&offset_range))
7951 {
7952 next_selected_range = Some(offset_range);
7953 break;
7954 }
7955 }
7956 }
7957
7958 if let Some(next_selected_range) = next_selected_range {
7959 select_next_match_ranges(
7960 self,
7961 next_selected_range,
7962 replace_newest,
7963 autoscroll,
7964 cx,
7965 );
7966 } else {
7967 select_next_state.done = true;
7968 }
7969 }
7970
7971 self.select_next_state = Some(select_next_state);
7972 } else {
7973 let mut only_carets = true;
7974 let mut same_text_selected = true;
7975 let mut selected_text = None;
7976
7977 let mut selections_iter = selections.iter().peekable();
7978 while let Some(selection) = selections_iter.next() {
7979 if selection.start != selection.end {
7980 only_carets = false;
7981 }
7982
7983 if same_text_selected {
7984 if selected_text.is_none() {
7985 selected_text =
7986 Some(buffer.text_for_range(selection.range()).collect::<String>());
7987 }
7988
7989 if let Some(next_selection) = selections_iter.peek() {
7990 if next_selection.range().len() == selection.range().len() {
7991 let next_selected_text = buffer
7992 .text_for_range(next_selection.range())
7993 .collect::<String>();
7994 if Some(next_selected_text) != selected_text {
7995 same_text_selected = false;
7996 selected_text = None;
7997 }
7998 } else {
7999 same_text_selected = false;
8000 selected_text = None;
8001 }
8002 }
8003 }
8004 }
8005
8006 if only_carets {
8007 for selection in &mut selections {
8008 let word_range = movement::surrounding_word(
8009 display_map,
8010 selection.start.to_display_point(display_map),
8011 );
8012 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8013 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8014 selection.goal = SelectionGoal::None;
8015 selection.reversed = false;
8016 select_next_match_ranges(
8017 self,
8018 selection.start..selection.end,
8019 replace_newest,
8020 autoscroll,
8021 cx,
8022 );
8023 }
8024
8025 if selections.len() == 1 {
8026 let selection = selections
8027 .last()
8028 .expect("ensured that there's only one selection");
8029 let query = buffer
8030 .text_for_range(selection.start..selection.end)
8031 .collect::<String>();
8032 let is_empty = query.is_empty();
8033 let select_state = SelectNextState {
8034 query: AhoCorasick::new(&[query])?,
8035 wordwise: true,
8036 done: is_empty,
8037 };
8038 self.select_next_state = Some(select_state);
8039 } else {
8040 self.select_next_state = None;
8041 }
8042 } else if let Some(selected_text) = selected_text {
8043 self.select_next_state = Some(SelectNextState {
8044 query: AhoCorasick::new(&[selected_text])?,
8045 wordwise: false,
8046 done: false,
8047 });
8048 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8049 }
8050 }
8051 Ok(())
8052 }
8053
8054 pub fn select_all_matches(
8055 &mut self,
8056 _action: &SelectAllMatches,
8057 cx: &mut ViewContext<Self>,
8058 ) -> Result<()> {
8059 self.push_to_selection_history();
8060 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8061
8062 self.select_next_match_internal(&display_map, false, None, cx)?;
8063 let Some(select_next_state) = self.select_next_state.as_mut() else {
8064 return Ok(());
8065 };
8066 if select_next_state.done {
8067 return Ok(());
8068 }
8069
8070 let mut new_selections = self.selections.all::<usize>(cx);
8071
8072 let buffer = &display_map.buffer_snapshot;
8073 let query_matches = select_next_state
8074 .query
8075 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8076
8077 for query_match in query_matches {
8078 let query_match = query_match.unwrap(); // can only fail due to I/O
8079 let offset_range = query_match.start()..query_match.end();
8080 let display_range = offset_range.start.to_display_point(&display_map)
8081 ..offset_range.end.to_display_point(&display_map);
8082
8083 if !select_next_state.wordwise
8084 || (!movement::is_inside_word(&display_map, display_range.start)
8085 && !movement::is_inside_word(&display_map, display_range.end))
8086 {
8087 self.selections.change_with(cx, |selections| {
8088 new_selections.push(Selection {
8089 id: selections.new_selection_id(),
8090 start: offset_range.start,
8091 end: offset_range.end,
8092 reversed: false,
8093 goal: SelectionGoal::None,
8094 });
8095 });
8096 }
8097 }
8098
8099 new_selections.sort_by_key(|selection| selection.start);
8100 let mut ix = 0;
8101 while ix + 1 < new_selections.len() {
8102 let current_selection = &new_selections[ix];
8103 let next_selection = &new_selections[ix + 1];
8104 if current_selection.range().overlaps(&next_selection.range()) {
8105 if current_selection.id < next_selection.id {
8106 new_selections.remove(ix + 1);
8107 } else {
8108 new_selections.remove(ix);
8109 }
8110 } else {
8111 ix += 1;
8112 }
8113 }
8114
8115 select_next_state.done = true;
8116 self.unfold_ranges(
8117 &new_selections
8118 .iter()
8119 .map(|selection| selection.range())
8120 .collect::<Vec<_>>(),
8121 false,
8122 false,
8123 cx,
8124 );
8125 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8126 selections.select(new_selections)
8127 });
8128
8129 Ok(())
8130 }
8131
8132 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8133 self.push_to_selection_history();
8134 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8135 self.select_next_match_internal(
8136 &display_map,
8137 action.replace_newest,
8138 Some(Autoscroll::newest()),
8139 cx,
8140 )?;
8141 Ok(())
8142 }
8143
8144 pub fn select_previous(
8145 &mut self,
8146 action: &SelectPrevious,
8147 cx: &mut ViewContext<Self>,
8148 ) -> Result<()> {
8149 self.push_to_selection_history();
8150 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8151 let buffer = &display_map.buffer_snapshot;
8152 let mut selections = self.selections.all::<usize>(cx);
8153 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8154 let query = &select_prev_state.query;
8155 if !select_prev_state.done {
8156 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8157 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8158 let mut next_selected_range = None;
8159 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8160 let bytes_before_last_selection =
8161 buffer.reversed_bytes_in_range(0..last_selection.start);
8162 let bytes_after_first_selection =
8163 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8164 let query_matches = query
8165 .stream_find_iter(bytes_before_last_selection)
8166 .map(|result| (last_selection.start, result))
8167 .chain(
8168 query
8169 .stream_find_iter(bytes_after_first_selection)
8170 .map(|result| (buffer.len(), result)),
8171 );
8172 for (end_offset, query_match) in query_matches {
8173 let query_match = query_match.unwrap(); // can only fail due to I/O
8174 let offset_range =
8175 end_offset - query_match.end()..end_offset - query_match.start();
8176 let display_range = offset_range.start.to_display_point(&display_map)
8177 ..offset_range.end.to_display_point(&display_map);
8178
8179 if !select_prev_state.wordwise
8180 || (!movement::is_inside_word(&display_map, display_range.start)
8181 && !movement::is_inside_word(&display_map, display_range.end))
8182 {
8183 next_selected_range = Some(offset_range);
8184 break;
8185 }
8186 }
8187
8188 if let Some(next_selected_range) = next_selected_range {
8189 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8190 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8191 if action.replace_newest {
8192 s.delete(s.newest_anchor().id);
8193 }
8194 s.insert_range(next_selected_range);
8195 });
8196 } else {
8197 select_prev_state.done = true;
8198 }
8199 }
8200
8201 self.select_prev_state = Some(select_prev_state);
8202 } else {
8203 let mut only_carets = true;
8204 let mut same_text_selected = true;
8205 let mut selected_text = None;
8206
8207 let mut selections_iter = selections.iter().peekable();
8208 while let Some(selection) = selections_iter.next() {
8209 if selection.start != selection.end {
8210 only_carets = false;
8211 }
8212
8213 if same_text_selected {
8214 if selected_text.is_none() {
8215 selected_text =
8216 Some(buffer.text_for_range(selection.range()).collect::<String>());
8217 }
8218
8219 if let Some(next_selection) = selections_iter.peek() {
8220 if next_selection.range().len() == selection.range().len() {
8221 let next_selected_text = buffer
8222 .text_for_range(next_selection.range())
8223 .collect::<String>();
8224 if Some(next_selected_text) != selected_text {
8225 same_text_selected = false;
8226 selected_text = None;
8227 }
8228 } else {
8229 same_text_selected = false;
8230 selected_text = None;
8231 }
8232 }
8233 }
8234 }
8235
8236 if only_carets {
8237 for selection in &mut selections {
8238 let word_range = movement::surrounding_word(
8239 &display_map,
8240 selection.start.to_display_point(&display_map),
8241 );
8242 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8243 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8244 selection.goal = SelectionGoal::None;
8245 selection.reversed = false;
8246 }
8247 if selections.len() == 1 {
8248 let selection = selections
8249 .last()
8250 .expect("ensured that there's only one selection");
8251 let query = buffer
8252 .text_for_range(selection.start..selection.end)
8253 .collect::<String>();
8254 let is_empty = query.is_empty();
8255 let select_state = SelectNextState {
8256 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8257 wordwise: true,
8258 done: is_empty,
8259 };
8260 self.select_prev_state = Some(select_state);
8261 } else {
8262 self.select_prev_state = None;
8263 }
8264
8265 self.unfold_ranges(
8266 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8267 false,
8268 true,
8269 cx,
8270 );
8271 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8272 s.select(selections);
8273 });
8274 } else if let Some(selected_text) = selected_text {
8275 self.select_prev_state = Some(SelectNextState {
8276 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8277 wordwise: false,
8278 done: false,
8279 });
8280 self.select_previous(action, cx)?;
8281 }
8282 }
8283 Ok(())
8284 }
8285
8286 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8287 if self.read_only(cx) {
8288 return;
8289 }
8290 let text_layout_details = &self.text_layout_details(cx);
8291 self.transact(cx, |this, cx| {
8292 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8293 let mut edits = Vec::new();
8294 let mut selection_edit_ranges = Vec::new();
8295 let mut last_toggled_row = None;
8296 let snapshot = this.buffer.read(cx).read(cx);
8297 let empty_str: Arc<str> = Arc::default();
8298 let mut suffixes_inserted = Vec::new();
8299 let ignore_indent = action.ignore_indent;
8300
8301 fn comment_prefix_range(
8302 snapshot: &MultiBufferSnapshot,
8303 row: MultiBufferRow,
8304 comment_prefix: &str,
8305 comment_prefix_whitespace: &str,
8306 ignore_indent: bool,
8307 ) -> Range<Point> {
8308 let indent_size = if ignore_indent {
8309 0
8310 } else {
8311 snapshot.indent_size_for_line(row).len
8312 };
8313
8314 let start = Point::new(row.0, indent_size);
8315
8316 let mut line_bytes = snapshot
8317 .bytes_in_range(start..snapshot.max_point())
8318 .flatten()
8319 .copied();
8320
8321 // If this line currently begins with the line comment prefix, then record
8322 // the range containing the prefix.
8323 if line_bytes
8324 .by_ref()
8325 .take(comment_prefix.len())
8326 .eq(comment_prefix.bytes())
8327 {
8328 // Include any whitespace that matches the comment prefix.
8329 let matching_whitespace_len = line_bytes
8330 .zip(comment_prefix_whitespace.bytes())
8331 .take_while(|(a, b)| a == b)
8332 .count() as u32;
8333 let end = Point::new(
8334 start.row,
8335 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8336 );
8337 start..end
8338 } else {
8339 start..start
8340 }
8341 }
8342
8343 fn comment_suffix_range(
8344 snapshot: &MultiBufferSnapshot,
8345 row: MultiBufferRow,
8346 comment_suffix: &str,
8347 comment_suffix_has_leading_space: bool,
8348 ) -> Range<Point> {
8349 let end = Point::new(row.0, snapshot.line_len(row));
8350 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8351
8352 let mut line_end_bytes = snapshot
8353 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8354 .flatten()
8355 .copied();
8356
8357 let leading_space_len = if suffix_start_column > 0
8358 && line_end_bytes.next() == Some(b' ')
8359 && comment_suffix_has_leading_space
8360 {
8361 1
8362 } else {
8363 0
8364 };
8365
8366 // If this line currently begins with the line comment prefix, then record
8367 // the range containing the prefix.
8368 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8369 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8370 start..end
8371 } else {
8372 end..end
8373 }
8374 }
8375
8376 // TODO: Handle selections that cross excerpts
8377 for selection in &mut selections {
8378 let start_column = snapshot
8379 .indent_size_for_line(MultiBufferRow(selection.start.row))
8380 .len;
8381 let language = if let Some(language) =
8382 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8383 {
8384 language
8385 } else {
8386 continue;
8387 };
8388
8389 selection_edit_ranges.clear();
8390
8391 // If multiple selections contain a given row, avoid processing that
8392 // row more than once.
8393 let mut start_row = MultiBufferRow(selection.start.row);
8394 if last_toggled_row == Some(start_row) {
8395 start_row = start_row.next_row();
8396 }
8397 let end_row =
8398 if selection.end.row > selection.start.row && selection.end.column == 0 {
8399 MultiBufferRow(selection.end.row - 1)
8400 } else {
8401 MultiBufferRow(selection.end.row)
8402 };
8403 last_toggled_row = Some(end_row);
8404
8405 if start_row > end_row {
8406 continue;
8407 }
8408
8409 // If the language has line comments, toggle those.
8410 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8411
8412 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8413 if ignore_indent {
8414 full_comment_prefixes = full_comment_prefixes
8415 .into_iter()
8416 .map(|s| Arc::from(s.trim_end()))
8417 .collect();
8418 }
8419
8420 if !full_comment_prefixes.is_empty() {
8421 let first_prefix = full_comment_prefixes
8422 .first()
8423 .expect("prefixes is non-empty");
8424 let prefix_trimmed_lengths = full_comment_prefixes
8425 .iter()
8426 .map(|p| p.trim_end_matches(' ').len())
8427 .collect::<SmallVec<[usize; 4]>>();
8428
8429 let mut all_selection_lines_are_comments = true;
8430
8431 for row in start_row.0..=end_row.0 {
8432 let row = MultiBufferRow(row);
8433 if start_row < end_row && snapshot.is_line_blank(row) {
8434 continue;
8435 }
8436
8437 let prefix_range = full_comment_prefixes
8438 .iter()
8439 .zip(prefix_trimmed_lengths.iter().copied())
8440 .map(|(prefix, trimmed_prefix_len)| {
8441 comment_prefix_range(
8442 snapshot.deref(),
8443 row,
8444 &prefix[..trimmed_prefix_len],
8445 &prefix[trimmed_prefix_len..],
8446 ignore_indent,
8447 )
8448 })
8449 .max_by_key(|range| range.end.column - range.start.column)
8450 .expect("prefixes is non-empty");
8451
8452 if prefix_range.is_empty() {
8453 all_selection_lines_are_comments = false;
8454 }
8455
8456 selection_edit_ranges.push(prefix_range);
8457 }
8458
8459 if all_selection_lines_are_comments {
8460 edits.extend(
8461 selection_edit_ranges
8462 .iter()
8463 .cloned()
8464 .map(|range| (range, empty_str.clone())),
8465 );
8466 } else {
8467 let min_column = selection_edit_ranges
8468 .iter()
8469 .map(|range| range.start.column)
8470 .min()
8471 .unwrap_or(0);
8472 edits.extend(selection_edit_ranges.iter().map(|range| {
8473 let position = Point::new(range.start.row, min_column);
8474 (position..position, first_prefix.clone())
8475 }));
8476 }
8477 } else if let Some((full_comment_prefix, comment_suffix)) =
8478 language.block_comment_delimiters()
8479 {
8480 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8481 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8482 let prefix_range = comment_prefix_range(
8483 snapshot.deref(),
8484 start_row,
8485 comment_prefix,
8486 comment_prefix_whitespace,
8487 ignore_indent,
8488 );
8489 let suffix_range = comment_suffix_range(
8490 snapshot.deref(),
8491 end_row,
8492 comment_suffix.trim_start_matches(' '),
8493 comment_suffix.starts_with(' '),
8494 );
8495
8496 if prefix_range.is_empty() || suffix_range.is_empty() {
8497 edits.push((
8498 prefix_range.start..prefix_range.start,
8499 full_comment_prefix.clone(),
8500 ));
8501 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8502 suffixes_inserted.push((end_row, comment_suffix.len()));
8503 } else {
8504 edits.push((prefix_range, empty_str.clone()));
8505 edits.push((suffix_range, empty_str.clone()));
8506 }
8507 } else {
8508 continue;
8509 }
8510 }
8511
8512 drop(snapshot);
8513 this.buffer.update(cx, |buffer, cx| {
8514 buffer.edit(edits, None, cx);
8515 });
8516
8517 // Adjust selections so that they end before any comment suffixes that
8518 // were inserted.
8519 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8520 let mut selections = this.selections.all::<Point>(cx);
8521 let snapshot = this.buffer.read(cx).read(cx);
8522 for selection in &mut selections {
8523 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8524 match row.cmp(&MultiBufferRow(selection.end.row)) {
8525 Ordering::Less => {
8526 suffixes_inserted.next();
8527 continue;
8528 }
8529 Ordering::Greater => break,
8530 Ordering::Equal => {
8531 if selection.end.column == snapshot.line_len(row) {
8532 if selection.is_empty() {
8533 selection.start.column -= suffix_len as u32;
8534 }
8535 selection.end.column -= suffix_len as u32;
8536 }
8537 break;
8538 }
8539 }
8540 }
8541 }
8542
8543 drop(snapshot);
8544 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8545
8546 let selections = this.selections.all::<Point>(cx);
8547 let selections_on_single_row = selections.windows(2).all(|selections| {
8548 selections[0].start.row == selections[1].start.row
8549 && selections[0].end.row == selections[1].end.row
8550 && selections[0].start.row == selections[0].end.row
8551 });
8552 let selections_selecting = selections
8553 .iter()
8554 .any(|selection| selection.start != selection.end);
8555 let advance_downwards = action.advance_downwards
8556 && selections_on_single_row
8557 && !selections_selecting
8558 && !matches!(this.mode, EditorMode::SingleLine { .. });
8559
8560 if advance_downwards {
8561 let snapshot = this.buffer.read(cx).snapshot(cx);
8562
8563 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8564 s.move_cursors_with(|display_snapshot, display_point, _| {
8565 let mut point = display_point.to_point(display_snapshot);
8566 point.row += 1;
8567 point = snapshot.clip_point(point, Bias::Left);
8568 let display_point = point.to_display_point(display_snapshot);
8569 let goal = SelectionGoal::HorizontalPosition(
8570 display_snapshot
8571 .x_for_display_point(display_point, text_layout_details)
8572 .into(),
8573 );
8574 (display_point, goal)
8575 })
8576 });
8577 }
8578 });
8579 }
8580
8581 pub fn select_enclosing_symbol(
8582 &mut self,
8583 _: &SelectEnclosingSymbol,
8584 cx: &mut ViewContext<Self>,
8585 ) {
8586 let buffer = self.buffer.read(cx).snapshot(cx);
8587 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8588
8589 fn update_selection(
8590 selection: &Selection<usize>,
8591 buffer_snap: &MultiBufferSnapshot,
8592 ) -> Option<Selection<usize>> {
8593 let cursor = selection.head();
8594 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8595 for symbol in symbols.iter().rev() {
8596 let start = symbol.range.start.to_offset(buffer_snap);
8597 let end = symbol.range.end.to_offset(buffer_snap);
8598 let new_range = start..end;
8599 if start < selection.start || end > selection.end {
8600 return Some(Selection {
8601 id: selection.id,
8602 start: new_range.start,
8603 end: new_range.end,
8604 goal: SelectionGoal::None,
8605 reversed: selection.reversed,
8606 });
8607 }
8608 }
8609 None
8610 }
8611
8612 let mut selected_larger_symbol = false;
8613 let new_selections = old_selections
8614 .iter()
8615 .map(|selection| match update_selection(selection, &buffer) {
8616 Some(new_selection) => {
8617 if new_selection.range() != selection.range() {
8618 selected_larger_symbol = true;
8619 }
8620 new_selection
8621 }
8622 None => selection.clone(),
8623 })
8624 .collect::<Vec<_>>();
8625
8626 if selected_larger_symbol {
8627 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8628 s.select(new_selections);
8629 });
8630 }
8631 }
8632
8633 pub fn select_larger_syntax_node(
8634 &mut self,
8635 _: &SelectLargerSyntaxNode,
8636 cx: &mut ViewContext<Self>,
8637 ) {
8638 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8639 let buffer = self.buffer.read(cx).snapshot(cx);
8640 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8641
8642 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8643 let mut selected_larger_node = false;
8644 let new_selections = old_selections
8645 .iter()
8646 .map(|selection| {
8647 let old_range = selection.start..selection.end;
8648 let mut new_range = old_range.clone();
8649 while let Some(containing_range) =
8650 buffer.range_for_syntax_ancestor(new_range.clone())
8651 {
8652 new_range = containing_range;
8653 if !display_map.intersects_fold(new_range.start)
8654 && !display_map.intersects_fold(new_range.end)
8655 {
8656 break;
8657 }
8658 }
8659
8660 selected_larger_node |= new_range != old_range;
8661 Selection {
8662 id: selection.id,
8663 start: new_range.start,
8664 end: new_range.end,
8665 goal: SelectionGoal::None,
8666 reversed: selection.reversed,
8667 }
8668 })
8669 .collect::<Vec<_>>();
8670
8671 if selected_larger_node {
8672 stack.push(old_selections);
8673 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8674 s.select(new_selections);
8675 });
8676 }
8677 self.select_larger_syntax_node_stack = stack;
8678 }
8679
8680 pub fn select_smaller_syntax_node(
8681 &mut self,
8682 _: &SelectSmallerSyntaxNode,
8683 cx: &mut ViewContext<Self>,
8684 ) {
8685 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8686 if let Some(selections) = stack.pop() {
8687 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8688 s.select(selections.to_vec());
8689 });
8690 }
8691 self.select_larger_syntax_node_stack = stack;
8692 }
8693
8694 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8695 if !EditorSettings::get_global(cx).gutter.runnables {
8696 self.clear_tasks();
8697 return Task::ready(());
8698 }
8699 let project = self.project.as_ref().map(Model::downgrade);
8700 cx.spawn(|this, mut cx| async move {
8701 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
8702 let Some(project) = project.and_then(|p| p.upgrade()) else {
8703 return;
8704 };
8705 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8706 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8707 }) else {
8708 return;
8709 };
8710
8711 let hide_runnables = project
8712 .update(&mut cx, |project, cx| {
8713 // Do not display any test indicators in non-dev server remote projects.
8714 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8715 })
8716 .unwrap_or(true);
8717 if hide_runnables {
8718 return;
8719 }
8720 let new_rows =
8721 cx.background_executor()
8722 .spawn({
8723 let snapshot = display_snapshot.clone();
8724 async move {
8725 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8726 }
8727 })
8728 .await;
8729 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8730
8731 this.update(&mut cx, |this, _| {
8732 this.clear_tasks();
8733 for (key, value) in rows {
8734 this.insert_tasks(key, value);
8735 }
8736 })
8737 .ok();
8738 })
8739 }
8740 fn fetch_runnable_ranges(
8741 snapshot: &DisplaySnapshot,
8742 range: Range<Anchor>,
8743 ) -> Vec<language::RunnableRange> {
8744 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8745 }
8746
8747 fn runnable_rows(
8748 project: Model<Project>,
8749 snapshot: DisplaySnapshot,
8750 runnable_ranges: Vec<RunnableRange>,
8751 mut cx: AsyncWindowContext,
8752 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8753 runnable_ranges
8754 .into_iter()
8755 .filter_map(|mut runnable| {
8756 let tasks = cx
8757 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8758 .ok()?;
8759 if tasks.is_empty() {
8760 return None;
8761 }
8762
8763 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8764
8765 let row = snapshot
8766 .buffer_snapshot
8767 .buffer_line_for_row(MultiBufferRow(point.row))?
8768 .1
8769 .start
8770 .row;
8771
8772 let context_range =
8773 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8774 Some((
8775 (runnable.buffer_id, row),
8776 RunnableTasks {
8777 templates: tasks,
8778 offset: MultiBufferOffset(runnable.run_range.start),
8779 context_range,
8780 column: point.column,
8781 extra_variables: runnable.extra_captures,
8782 },
8783 ))
8784 })
8785 .collect()
8786 }
8787
8788 fn templates_with_tags(
8789 project: &Model<Project>,
8790 runnable: &mut Runnable,
8791 cx: &WindowContext<'_>,
8792 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8793 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8794 let (worktree_id, file) = project
8795 .buffer_for_id(runnable.buffer, cx)
8796 .and_then(|buffer| buffer.read(cx).file())
8797 .map(|file| (file.worktree_id(cx), file.clone()))
8798 .unzip();
8799
8800 (
8801 project.task_store().read(cx).task_inventory().cloned(),
8802 worktree_id,
8803 file,
8804 )
8805 });
8806
8807 let tags = mem::take(&mut runnable.tags);
8808 let mut tags: Vec<_> = tags
8809 .into_iter()
8810 .flat_map(|tag| {
8811 let tag = tag.0.clone();
8812 inventory
8813 .as_ref()
8814 .into_iter()
8815 .flat_map(|inventory| {
8816 inventory.read(cx).list_tasks(
8817 file.clone(),
8818 Some(runnable.language.clone()),
8819 worktree_id,
8820 cx,
8821 )
8822 })
8823 .filter(move |(_, template)| {
8824 template.tags.iter().any(|source_tag| source_tag == &tag)
8825 })
8826 })
8827 .sorted_by_key(|(kind, _)| kind.to_owned())
8828 .collect();
8829 if let Some((leading_tag_source, _)) = tags.first() {
8830 // Strongest source wins; if we have worktree tag binding, prefer that to
8831 // global and language bindings;
8832 // if we have a global binding, prefer that to language binding.
8833 let first_mismatch = tags
8834 .iter()
8835 .position(|(tag_source, _)| tag_source != leading_tag_source);
8836 if let Some(index) = first_mismatch {
8837 tags.truncate(index);
8838 }
8839 }
8840
8841 tags
8842 }
8843
8844 pub fn move_to_enclosing_bracket(
8845 &mut self,
8846 _: &MoveToEnclosingBracket,
8847 cx: &mut ViewContext<Self>,
8848 ) {
8849 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8850 s.move_offsets_with(|snapshot, selection| {
8851 let Some(enclosing_bracket_ranges) =
8852 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
8853 else {
8854 return;
8855 };
8856
8857 let mut best_length = usize::MAX;
8858 let mut best_inside = false;
8859 let mut best_in_bracket_range = false;
8860 let mut best_destination = None;
8861 for (open, close) in enclosing_bracket_ranges {
8862 let close = close.to_inclusive();
8863 let length = close.end() - open.start;
8864 let inside = selection.start >= open.end && selection.end <= *close.start();
8865 let in_bracket_range = open.to_inclusive().contains(&selection.head())
8866 || close.contains(&selection.head());
8867
8868 // If best is next to a bracket and current isn't, skip
8869 if !in_bracket_range && best_in_bracket_range {
8870 continue;
8871 }
8872
8873 // Prefer smaller lengths unless best is inside and current isn't
8874 if length > best_length && (best_inside || !inside) {
8875 continue;
8876 }
8877
8878 best_length = length;
8879 best_inside = inside;
8880 best_in_bracket_range = in_bracket_range;
8881 best_destination = Some(
8882 if close.contains(&selection.start) && close.contains(&selection.end) {
8883 if inside {
8884 open.end
8885 } else {
8886 open.start
8887 }
8888 } else if inside {
8889 *close.start()
8890 } else {
8891 *close.end()
8892 },
8893 );
8894 }
8895
8896 if let Some(destination) = best_destination {
8897 selection.collapse_to(destination, SelectionGoal::None);
8898 }
8899 })
8900 });
8901 }
8902
8903 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
8904 self.end_selection(cx);
8905 self.selection_history.mode = SelectionHistoryMode::Undoing;
8906 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
8907 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8908 self.select_next_state = entry.select_next_state;
8909 self.select_prev_state = entry.select_prev_state;
8910 self.add_selections_state = entry.add_selections_state;
8911 self.request_autoscroll(Autoscroll::newest(), cx);
8912 }
8913 self.selection_history.mode = SelectionHistoryMode::Normal;
8914 }
8915
8916 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
8917 self.end_selection(cx);
8918 self.selection_history.mode = SelectionHistoryMode::Redoing;
8919 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
8920 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8921 self.select_next_state = entry.select_next_state;
8922 self.select_prev_state = entry.select_prev_state;
8923 self.add_selections_state = entry.add_selections_state;
8924 self.request_autoscroll(Autoscroll::newest(), cx);
8925 }
8926 self.selection_history.mode = SelectionHistoryMode::Normal;
8927 }
8928
8929 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
8930 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
8931 }
8932
8933 pub fn expand_excerpts_down(
8934 &mut self,
8935 action: &ExpandExcerptsDown,
8936 cx: &mut ViewContext<Self>,
8937 ) {
8938 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
8939 }
8940
8941 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
8942 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
8943 }
8944
8945 pub fn expand_excerpts_for_direction(
8946 &mut self,
8947 lines: u32,
8948 direction: ExpandExcerptDirection,
8949 cx: &mut ViewContext<Self>,
8950 ) {
8951 let selections = self.selections.disjoint_anchors();
8952
8953 let lines = if lines == 0 {
8954 EditorSettings::get_global(cx).expand_excerpt_lines
8955 } else {
8956 lines
8957 };
8958
8959 self.buffer.update(cx, |buffer, cx| {
8960 buffer.expand_excerpts(
8961 selections
8962 .iter()
8963 .map(|selection| selection.head().excerpt_id)
8964 .dedup(),
8965 lines,
8966 direction,
8967 cx,
8968 )
8969 })
8970 }
8971
8972 pub fn expand_excerpt(
8973 &mut self,
8974 excerpt: ExcerptId,
8975 direction: ExpandExcerptDirection,
8976 cx: &mut ViewContext<Self>,
8977 ) {
8978 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
8979 self.buffer.update(cx, |buffer, cx| {
8980 buffer.expand_excerpts([excerpt], lines, direction, cx)
8981 })
8982 }
8983
8984 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
8985 self.go_to_diagnostic_impl(Direction::Next, cx)
8986 }
8987
8988 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
8989 self.go_to_diagnostic_impl(Direction::Prev, cx)
8990 }
8991
8992 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
8993 let buffer = self.buffer.read(cx).snapshot(cx);
8994 let selection = self.selections.newest::<usize>(cx);
8995
8996 // If there is an active Diagnostic Popover jump to its diagnostic instead.
8997 if direction == Direction::Next {
8998 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
8999 let (group_id, jump_to) = popover.activation_info();
9000 if self.activate_diagnostics(group_id, cx) {
9001 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9002 let mut new_selection = s.newest_anchor().clone();
9003 new_selection.collapse_to(jump_to, SelectionGoal::None);
9004 s.select_anchors(vec![new_selection.clone()]);
9005 });
9006 }
9007 return;
9008 }
9009 }
9010
9011 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9012 active_diagnostics
9013 .primary_range
9014 .to_offset(&buffer)
9015 .to_inclusive()
9016 });
9017 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9018 if active_primary_range.contains(&selection.head()) {
9019 *active_primary_range.start()
9020 } else {
9021 selection.head()
9022 }
9023 } else {
9024 selection.head()
9025 };
9026 let snapshot = self.snapshot(cx);
9027 loop {
9028 let diagnostics = if direction == Direction::Prev {
9029 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9030 } else {
9031 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9032 }
9033 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9034 let group = diagnostics
9035 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9036 // be sorted in a stable way
9037 // skip until we are at current active diagnostic, if it exists
9038 .skip_while(|entry| {
9039 (match direction {
9040 Direction::Prev => entry.range.start >= search_start,
9041 Direction::Next => entry.range.start <= search_start,
9042 }) && self
9043 .active_diagnostics
9044 .as_ref()
9045 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9046 })
9047 .find_map(|entry| {
9048 if entry.diagnostic.is_primary
9049 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9050 && !entry.range.is_empty()
9051 // if we match with the active diagnostic, skip it
9052 && Some(entry.diagnostic.group_id)
9053 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9054 {
9055 Some((entry.range, entry.diagnostic.group_id))
9056 } else {
9057 None
9058 }
9059 });
9060
9061 if let Some((primary_range, group_id)) = group {
9062 if self.activate_diagnostics(group_id, cx) {
9063 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9064 s.select(vec![Selection {
9065 id: selection.id,
9066 start: primary_range.start,
9067 end: primary_range.start,
9068 reversed: false,
9069 goal: SelectionGoal::None,
9070 }]);
9071 });
9072 }
9073 break;
9074 } else {
9075 // Cycle around to the start of the buffer, potentially moving back to the start of
9076 // the currently active diagnostic.
9077 active_primary_range.take();
9078 if direction == Direction::Prev {
9079 if search_start == buffer.len() {
9080 break;
9081 } else {
9082 search_start = buffer.len();
9083 }
9084 } else if search_start == 0 {
9085 break;
9086 } else {
9087 search_start = 0;
9088 }
9089 }
9090 }
9091 }
9092
9093 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9094 let snapshot = self.snapshot(cx);
9095 let selection = self.selections.newest::<Point>(cx);
9096 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9097 }
9098
9099 fn go_to_hunk_after_position(
9100 &mut self,
9101 snapshot: &EditorSnapshot,
9102 position: Point,
9103 cx: &mut ViewContext<'_, Editor>,
9104 ) -> Option<MultiBufferDiffHunk> {
9105 for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
9106 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9107 snapshot,
9108 position,
9109 ix > 0,
9110 snapshot.diff_map.diff_hunks_in_range(
9111 position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
9112 &snapshot.buffer_snapshot,
9113 ),
9114 cx,
9115 ) {
9116 return Some(hunk);
9117 }
9118 }
9119 None
9120 }
9121
9122 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9123 let snapshot = self.snapshot(cx);
9124 let selection = self.selections.newest::<Point>(cx);
9125 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9126 }
9127
9128 fn go_to_hunk_before_position(
9129 &mut self,
9130 snapshot: &EditorSnapshot,
9131 position: Point,
9132 cx: &mut ViewContext<'_, Editor>,
9133 ) -> Option<MultiBufferDiffHunk> {
9134 for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
9135 .into_iter()
9136 .enumerate()
9137 {
9138 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9139 snapshot,
9140 position,
9141 ix > 0,
9142 snapshot
9143 .diff_map
9144 .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
9145 cx,
9146 ) {
9147 return Some(hunk);
9148 }
9149 }
9150 None
9151 }
9152
9153 fn go_to_next_hunk_in_direction(
9154 &mut self,
9155 snapshot: &DisplaySnapshot,
9156 initial_point: Point,
9157 is_wrapped: bool,
9158 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9159 cx: &mut ViewContext<Editor>,
9160 ) -> Option<MultiBufferDiffHunk> {
9161 let display_point = initial_point.to_display_point(snapshot);
9162 let mut hunks = hunks
9163 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9164 .filter(|(display_hunk, _)| {
9165 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9166 })
9167 .dedup();
9168
9169 if let Some((display_hunk, hunk)) = hunks.next() {
9170 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9171 let row = display_hunk.start_display_row();
9172 let point = DisplayPoint::new(row, 0);
9173 s.select_display_ranges([point..point]);
9174 });
9175
9176 Some(hunk)
9177 } else {
9178 None
9179 }
9180 }
9181
9182 pub fn go_to_definition(
9183 &mut self,
9184 _: &GoToDefinition,
9185 cx: &mut ViewContext<Self>,
9186 ) -> Task<Result<Navigated>> {
9187 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9188 cx.spawn(|editor, mut cx| async move {
9189 if definition.await? == Navigated::Yes {
9190 return Ok(Navigated::Yes);
9191 }
9192 match editor.update(&mut cx, |editor, cx| {
9193 editor.find_all_references(&FindAllReferences, cx)
9194 })? {
9195 Some(references) => references.await,
9196 None => Ok(Navigated::No),
9197 }
9198 })
9199 }
9200
9201 pub fn go_to_declaration(
9202 &mut self,
9203 _: &GoToDeclaration,
9204 cx: &mut ViewContext<Self>,
9205 ) -> Task<Result<Navigated>> {
9206 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9207 }
9208
9209 pub fn go_to_declaration_split(
9210 &mut self,
9211 _: &GoToDeclaration,
9212 cx: &mut ViewContext<Self>,
9213 ) -> Task<Result<Navigated>> {
9214 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9215 }
9216
9217 pub fn go_to_implementation(
9218 &mut self,
9219 _: &GoToImplementation,
9220 cx: &mut ViewContext<Self>,
9221 ) -> Task<Result<Navigated>> {
9222 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9223 }
9224
9225 pub fn go_to_implementation_split(
9226 &mut self,
9227 _: &GoToImplementationSplit,
9228 cx: &mut ViewContext<Self>,
9229 ) -> Task<Result<Navigated>> {
9230 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9231 }
9232
9233 pub fn go_to_type_definition(
9234 &mut self,
9235 _: &GoToTypeDefinition,
9236 cx: &mut ViewContext<Self>,
9237 ) -> Task<Result<Navigated>> {
9238 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9239 }
9240
9241 pub fn go_to_definition_split(
9242 &mut self,
9243 _: &GoToDefinitionSplit,
9244 cx: &mut ViewContext<Self>,
9245 ) -> Task<Result<Navigated>> {
9246 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9247 }
9248
9249 pub fn go_to_type_definition_split(
9250 &mut self,
9251 _: &GoToTypeDefinitionSplit,
9252 cx: &mut ViewContext<Self>,
9253 ) -> Task<Result<Navigated>> {
9254 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9255 }
9256
9257 fn go_to_definition_of_kind(
9258 &mut self,
9259 kind: GotoDefinitionKind,
9260 split: bool,
9261 cx: &mut ViewContext<Self>,
9262 ) -> Task<Result<Navigated>> {
9263 let Some(provider) = self.semantics_provider.clone() else {
9264 return Task::ready(Ok(Navigated::No));
9265 };
9266 let head = self.selections.newest::<usize>(cx).head();
9267 let buffer = self.buffer.read(cx);
9268 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9269 text_anchor
9270 } else {
9271 return Task::ready(Ok(Navigated::No));
9272 };
9273
9274 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9275 return Task::ready(Ok(Navigated::No));
9276 };
9277
9278 cx.spawn(|editor, mut cx| async move {
9279 let definitions = definitions.await?;
9280 let navigated = editor
9281 .update(&mut cx, |editor, cx| {
9282 editor.navigate_to_hover_links(
9283 Some(kind),
9284 definitions
9285 .into_iter()
9286 .filter(|location| {
9287 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9288 })
9289 .map(HoverLink::Text)
9290 .collect::<Vec<_>>(),
9291 split,
9292 cx,
9293 )
9294 })?
9295 .await?;
9296 anyhow::Ok(navigated)
9297 })
9298 }
9299
9300 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9301 let selection = self.selections.newest_anchor();
9302 let head = selection.head();
9303 let tail = selection.tail();
9304
9305 let Some((buffer, start_position)) =
9306 self.buffer.read(cx).text_anchor_for_position(head, cx)
9307 else {
9308 return;
9309 };
9310
9311 let end_position = if head != tail {
9312 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
9313 return;
9314 };
9315 Some(pos)
9316 } else {
9317 None
9318 };
9319
9320 let url_finder = cx.spawn(|editor, mut cx| async move {
9321 let url = if let Some(end_pos) = end_position {
9322 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
9323 } else {
9324 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
9325 };
9326
9327 if let Some(url) = url {
9328 editor.update(&mut cx, |_, cx| {
9329 cx.open_url(&url);
9330 })
9331 } else {
9332 Ok(())
9333 }
9334 });
9335
9336 url_finder.detach();
9337 }
9338
9339 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9340 let Some(workspace) = self.workspace() else {
9341 return;
9342 };
9343
9344 let position = self.selections.newest_anchor().head();
9345
9346 let Some((buffer, buffer_position)) =
9347 self.buffer.read(cx).text_anchor_for_position(position, cx)
9348 else {
9349 return;
9350 };
9351
9352 let project = self.project.clone();
9353
9354 cx.spawn(|_, mut cx| async move {
9355 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9356
9357 if let Some((_, path)) = result {
9358 workspace
9359 .update(&mut cx, |workspace, cx| {
9360 workspace.open_resolved_path(path, cx)
9361 })?
9362 .await?;
9363 }
9364 anyhow::Ok(())
9365 })
9366 .detach();
9367 }
9368
9369 pub(crate) fn navigate_to_hover_links(
9370 &mut self,
9371 kind: Option<GotoDefinitionKind>,
9372 mut definitions: Vec<HoverLink>,
9373 split: bool,
9374 cx: &mut ViewContext<Editor>,
9375 ) -> Task<Result<Navigated>> {
9376 // If there is one definition, just open it directly
9377 if definitions.len() == 1 {
9378 let definition = definitions.pop().unwrap();
9379
9380 enum TargetTaskResult {
9381 Location(Option<Location>),
9382 AlreadyNavigated,
9383 }
9384
9385 let target_task = match definition {
9386 HoverLink::Text(link) => {
9387 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9388 }
9389 HoverLink::InlayHint(lsp_location, server_id) => {
9390 let computation = self.compute_target_location(lsp_location, server_id, cx);
9391 cx.background_executor().spawn(async move {
9392 let location = computation.await?;
9393 Ok(TargetTaskResult::Location(location))
9394 })
9395 }
9396 HoverLink::Url(url) => {
9397 cx.open_url(&url);
9398 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9399 }
9400 HoverLink::File(path) => {
9401 if let Some(workspace) = self.workspace() {
9402 cx.spawn(|_, mut cx| async move {
9403 workspace
9404 .update(&mut cx, |workspace, cx| {
9405 workspace.open_resolved_path(path, cx)
9406 })?
9407 .await
9408 .map(|_| TargetTaskResult::AlreadyNavigated)
9409 })
9410 } else {
9411 Task::ready(Ok(TargetTaskResult::Location(None)))
9412 }
9413 }
9414 };
9415 cx.spawn(|editor, mut cx| async move {
9416 let target = match target_task.await.context("target resolution task")? {
9417 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9418 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9419 TargetTaskResult::Location(Some(target)) => target,
9420 };
9421
9422 editor.update(&mut cx, |editor, cx| {
9423 let Some(workspace) = editor.workspace() else {
9424 return Navigated::No;
9425 };
9426 let pane = workspace.read(cx).active_pane().clone();
9427
9428 let range = target.range.to_offset(target.buffer.read(cx));
9429 let range = editor.range_for_match(&range);
9430
9431 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9432 let buffer = target.buffer.read(cx);
9433 let range = check_multiline_range(buffer, range);
9434 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9435 s.select_ranges([range]);
9436 });
9437 } else {
9438 cx.window_context().defer(move |cx| {
9439 let target_editor: View<Self> =
9440 workspace.update(cx, |workspace, cx| {
9441 let pane = if split {
9442 workspace.adjacent_pane(cx)
9443 } else {
9444 workspace.active_pane().clone()
9445 };
9446
9447 workspace.open_project_item(
9448 pane,
9449 target.buffer.clone(),
9450 true,
9451 true,
9452 cx,
9453 )
9454 });
9455 target_editor.update(cx, |target_editor, cx| {
9456 // When selecting a definition in a different buffer, disable the nav history
9457 // to avoid creating a history entry at the previous cursor location.
9458 pane.update(cx, |pane, _| pane.disable_history());
9459 let buffer = target.buffer.read(cx);
9460 let range = check_multiline_range(buffer, range);
9461 target_editor.change_selections(
9462 Some(Autoscroll::focused()),
9463 cx,
9464 |s| {
9465 s.select_ranges([range]);
9466 },
9467 );
9468 pane.update(cx, |pane, _| pane.enable_history());
9469 });
9470 });
9471 }
9472 Navigated::Yes
9473 })
9474 })
9475 } else if !definitions.is_empty() {
9476 cx.spawn(|editor, mut cx| async move {
9477 let (title, location_tasks, workspace) = editor
9478 .update(&mut cx, |editor, cx| {
9479 let tab_kind = match kind {
9480 Some(GotoDefinitionKind::Implementation) => "Implementations",
9481 _ => "Definitions",
9482 };
9483 let title = definitions
9484 .iter()
9485 .find_map(|definition| match definition {
9486 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9487 let buffer = origin.buffer.read(cx);
9488 format!(
9489 "{} for {}",
9490 tab_kind,
9491 buffer
9492 .text_for_range(origin.range.clone())
9493 .collect::<String>()
9494 )
9495 }),
9496 HoverLink::InlayHint(_, _) => None,
9497 HoverLink::Url(_) => None,
9498 HoverLink::File(_) => None,
9499 })
9500 .unwrap_or(tab_kind.to_string());
9501 let location_tasks = definitions
9502 .into_iter()
9503 .map(|definition| match definition {
9504 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
9505 HoverLink::InlayHint(lsp_location, server_id) => {
9506 editor.compute_target_location(lsp_location, server_id, cx)
9507 }
9508 HoverLink::Url(_) => Task::ready(Ok(None)),
9509 HoverLink::File(_) => Task::ready(Ok(None)),
9510 })
9511 .collect::<Vec<_>>();
9512 (title, location_tasks, editor.workspace().clone())
9513 })
9514 .context("location tasks preparation")?;
9515
9516 let locations = future::join_all(location_tasks)
9517 .await
9518 .into_iter()
9519 .filter_map(|location| location.transpose())
9520 .collect::<Result<_>>()
9521 .context("location tasks")?;
9522
9523 let Some(workspace) = workspace else {
9524 return Ok(Navigated::No);
9525 };
9526 let opened = workspace
9527 .update(&mut cx, |workspace, cx| {
9528 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9529 })
9530 .ok();
9531
9532 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9533 })
9534 } else {
9535 Task::ready(Ok(Navigated::No))
9536 }
9537 }
9538
9539 fn compute_target_location(
9540 &self,
9541 lsp_location: lsp::Location,
9542 server_id: LanguageServerId,
9543 cx: &mut ViewContext<Self>,
9544 ) -> Task<anyhow::Result<Option<Location>>> {
9545 let Some(project) = self.project.clone() else {
9546 return Task::ready(Ok(None));
9547 };
9548
9549 cx.spawn(move |editor, mut cx| async move {
9550 let location_task = editor.update(&mut cx, |_, cx| {
9551 project.update(cx, |project, cx| {
9552 let language_server_name = project
9553 .language_server_statuses(cx)
9554 .find(|(id, _)| server_id == *id)
9555 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
9556 language_server_name.map(|language_server_name| {
9557 project.open_local_buffer_via_lsp(
9558 lsp_location.uri.clone(),
9559 server_id,
9560 language_server_name,
9561 cx,
9562 )
9563 })
9564 })
9565 })?;
9566 let location = match location_task {
9567 Some(task) => Some({
9568 let target_buffer_handle = task.await.context("open local buffer")?;
9569 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9570 let target_start = target_buffer
9571 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9572 let target_end = target_buffer
9573 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9574 target_buffer.anchor_after(target_start)
9575 ..target_buffer.anchor_before(target_end)
9576 })?;
9577 Location {
9578 buffer: target_buffer_handle,
9579 range,
9580 }
9581 }),
9582 None => None,
9583 };
9584 Ok(location)
9585 })
9586 }
9587
9588 pub fn find_all_references(
9589 &mut self,
9590 _: &FindAllReferences,
9591 cx: &mut ViewContext<Self>,
9592 ) -> Option<Task<Result<Navigated>>> {
9593 let selection = self.selections.newest::<usize>(cx);
9594 let multi_buffer = self.buffer.read(cx);
9595 let head = selection.head();
9596
9597 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9598 let head_anchor = multi_buffer_snapshot.anchor_at(
9599 head,
9600 if head < selection.tail() {
9601 Bias::Right
9602 } else {
9603 Bias::Left
9604 },
9605 );
9606
9607 match self
9608 .find_all_references_task_sources
9609 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9610 {
9611 Ok(_) => {
9612 log::info!(
9613 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9614 );
9615 return None;
9616 }
9617 Err(i) => {
9618 self.find_all_references_task_sources.insert(i, head_anchor);
9619 }
9620 }
9621
9622 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9623 let workspace = self.workspace()?;
9624 let project = workspace.read(cx).project().clone();
9625 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9626 Some(cx.spawn(|editor, mut cx| async move {
9627 let _cleanup = defer({
9628 let mut cx = cx.clone();
9629 move || {
9630 let _ = editor.update(&mut cx, |editor, _| {
9631 if let Ok(i) =
9632 editor
9633 .find_all_references_task_sources
9634 .binary_search_by(|anchor| {
9635 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9636 })
9637 {
9638 editor.find_all_references_task_sources.remove(i);
9639 }
9640 });
9641 }
9642 });
9643
9644 let locations = references.await?;
9645 if locations.is_empty() {
9646 return anyhow::Ok(Navigated::No);
9647 }
9648
9649 workspace.update(&mut cx, |workspace, cx| {
9650 let title = locations
9651 .first()
9652 .as_ref()
9653 .map(|location| {
9654 let buffer = location.buffer.read(cx);
9655 format!(
9656 "References to `{}`",
9657 buffer
9658 .text_for_range(location.range.clone())
9659 .collect::<String>()
9660 )
9661 })
9662 .unwrap();
9663 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9664 Navigated::Yes
9665 })
9666 }))
9667 }
9668
9669 /// Opens a multibuffer with the given project locations in it
9670 pub fn open_locations_in_multibuffer(
9671 workspace: &mut Workspace,
9672 mut locations: Vec<Location>,
9673 title: String,
9674 split: bool,
9675 cx: &mut ViewContext<Workspace>,
9676 ) {
9677 // If there are multiple definitions, open them in a multibuffer
9678 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9679 let mut locations = locations.into_iter().peekable();
9680 let mut ranges_to_highlight = Vec::new();
9681 let capability = workspace.project().read(cx).capability();
9682
9683 let excerpt_buffer = cx.new_model(|cx| {
9684 let mut multibuffer = MultiBuffer::new(capability);
9685 while let Some(location) = locations.next() {
9686 let buffer = location.buffer.read(cx);
9687 let mut ranges_for_buffer = Vec::new();
9688 let range = location.range.to_offset(buffer);
9689 ranges_for_buffer.push(range.clone());
9690
9691 while let Some(next_location) = locations.peek() {
9692 if next_location.buffer == location.buffer {
9693 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9694 locations.next();
9695 } else {
9696 break;
9697 }
9698 }
9699
9700 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9701 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9702 location.buffer.clone(),
9703 ranges_for_buffer,
9704 DEFAULT_MULTIBUFFER_CONTEXT,
9705 cx,
9706 ))
9707 }
9708
9709 multibuffer.with_title(title)
9710 });
9711
9712 let editor = cx.new_view(|cx| {
9713 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9714 });
9715 editor.update(cx, |editor, cx| {
9716 if let Some(first_range) = ranges_to_highlight.first() {
9717 editor.change_selections(None, cx, |selections| {
9718 selections.clear_disjoint();
9719 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9720 });
9721 }
9722 editor.highlight_background::<Self>(
9723 &ranges_to_highlight,
9724 |theme| theme.editor_highlighted_line_background,
9725 cx,
9726 );
9727 editor.register_buffers_with_language_servers(cx);
9728 });
9729
9730 let item = Box::new(editor);
9731 let item_id = item.item_id();
9732
9733 if split {
9734 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9735 } else {
9736 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9737 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9738 pane.close_current_preview_item(cx)
9739 } else {
9740 None
9741 }
9742 });
9743 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9744 }
9745 workspace.active_pane().update(cx, |pane, cx| {
9746 pane.set_preview_item_id(Some(item_id), cx);
9747 });
9748 }
9749
9750 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9751 use language::ToOffset as _;
9752
9753 let provider = self.semantics_provider.clone()?;
9754 let selection = self.selections.newest_anchor().clone();
9755 let (cursor_buffer, cursor_buffer_position) = self
9756 .buffer
9757 .read(cx)
9758 .text_anchor_for_position(selection.head(), cx)?;
9759 let (tail_buffer, cursor_buffer_position_end) = self
9760 .buffer
9761 .read(cx)
9762 .text_anchor_for_position(selection.tail(), cx)?;
9763 if tail_buffer != cursor_buffer {
9764 return None;
9765 }
9766
9767 let snapshot = cursor_buffer.read(cx).snapshot();
9768 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9769 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9770 let prepare_rename = provider
9771 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
9772 .unwrap_or_else(|| Task::ready(Ok(None)));
9773 drop(snapshot);
9774
9775 Some(cx.spawn(|this, mut cx| async move {
9776 let rename_range = if let Some(range) = prepare_rename.await? {
9777 Some(range)
9778 } else {
9779 this.update(&mut cx, |this, cx| {
9780 let buffer = this.buffer.read(cx).snapshot(cx);
9781 let mut buffer_highlights = this
9782 .document_highlights_for_position(selection.head(), &buffer)
9783 .filter(|highlight| {
9784 highlight.start.excerpt_id == selection.head().excerpt_id
9785 && highlight.end.excerpt_id == selection.head().excerpt_id
9786 });
9787 buffer_highlights
9788 .next()
9789 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9790 })?
9791 };
9792 if let Some(rename_range) = rename_range {
9793 this.update(&mut cx, |this, cx| {
9794 let snapshot = cursor_buffer.read(cx).snapshot();
9795 let rename_buffer_range = rename_range.to_offset(&snapshot);
9796 let cursor_offset_in_rename_range =
9797 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9798 let cursor_offset_in_rename_range_end =
9799 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9800
9801 this.take_rename(false, cx);
9802 let buffer = this.buffer.read(cx).read(cx);
9803 let cursor_offset = selection.head().to_offset(&buffer);
9804 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9805 let rename_end = rename_start + rename_buffer_range.len();
9806 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9807 let mut old_highlight_id = None;
9808 let old_name: Arc<str> = buffer
9809 .chunks(rename_start..rename_end, true)
9810 .map(|chunk| {
9811 if old_highlight_id.is_none() {
9812 old_highlight_id = chunk.syntax_highlight_id;
9813 }
9814 chunk.text
9815 })
9816 .collect::<String>()
9817 .into();
9818
9819 drop(buffer);
9820
9821 // Position the selection in the rename editor so that it matches the current selection.
9822 this.show_local_selections = false;
9823 let rename_editor = cx.new_view(|cx| {
9824 let mut editor = Editor::single_line(cx);
9825 editor.buffer.update(cx, |buffer, cx| {
9826 buffer.edit([(0..0, old_name.clone())], None, cx)
9827 });
9828 let rename_selection_range = match cursor_offset_in_rename_range
9829 .cmp(&cursor_offset_in_rename_range_end)
9830 {
9831 Ordering::Equal => {
9832 editor.select_all(&SelectAll, cx);
9833 return editor;
9834 }
9835 Ordering::Less => {
9836 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9837 }
9838 Ordering::Greater => {
9839 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9840 }
9841 };
9842 if rename_selection_range.end > old_name.len() {
9843 editor.select_all(&SelectAll, cx);
9844 } else {
9845 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9846 s.select_ranges([rename_selection_range]);
9847 });
9848 }
9849 editor
9850 });
9851 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
9852 if e == &EditorEvent::Focused {
9853 cx.emit(EditorEvent::FocusedIn)
9854 }
9855 })
9856 .detach();
9857
9858 let write_highlights =
9859 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
9860 let read_highlights =
9861 this.clear_background_highlights::<DocumentHighlightRead>(cx);
9862 let ranges = write_highlights
9863 .iter()
9864 .flat_map(|(_, ranges)| ranges.iter())
9865 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
9866 .cloned()
9867 .collect();
9868
9869 this.highlight_text::<Rename>(
9870 ranges,
9871 HighlightStyle {
9872 fade_out: Some(0.6),
9873 ..Default::default()
9874 },
9875 cx,
9876 );
9877 let rename_focus_handle = rename_editor.focus_handle(cx);
9878 cx.focus(&rename_focus_handle);
9879 let block_id = this.insert_blocks(
9880 [BlockProperties {
9881 style: BlockStyle::Flex,
9882 placement: BlockPlacement::Below(range.start),
9883 height: 1,
9884 render: Arc::new({
9885 let rename_editor = rename_editor.clone();
9886 move |cx: &mut BlockContext| {
9887 let mut text_style = cx.editor_style.text.clone();
9888 if let Some(highlight_style) = old_highlight_id
9889 .and_then(|h| h.style(&cx.editor_style.syntax))
9890 {
9891 text_style = text_style.highlight(highlight_style);
9892 }
9893 div()
9894 .block_mouse_down()
9895 .pl(cx.anchor_x)
9896 .child(EditorElement::new(
9897 &rename_editor,
9898 EditorStyle {
9899 background: cx.theme().system().transparent,
9900 local_player: cx.editor_style.local_player,
9901 text: text_style,
9902 scrollbar_width: cx.editor_style.scrollbar_width,
9903 syntax: cx.editor_style.syntax.clone(),
9904 status: cx.editor_style.status.clone(),
9905 inlay_hints_style: HighlightStyle {
9906 font_weight: Some(FontWeight::BOLD),
9907 ..make_inlay_hints_style(cx)
9908 },
9909 inline_completion_styles: make_suggestion_styles(
9910 cx,
9911 ),
9912 ..EditorStyle::default()
9913 },
9914 ))
9915 .into_any_element()
9916 }
9917 }),
9918 priority: 0,
9919 }],
9920 Some(Autoscroll::fit()),
9921 cx,
9922 )[0];
9923 this.pending_rename = Some(RenameState {
9924 range,
9925 old_name,
9926 editor: rename_editor,
9927 block_id,
9928 });
9929 })?;
9930 }
9931
9932 Ok(())
9933 }))
9934 }
9935
9936 pub fn confirm_rename(
9937 &mut self,
9938 _: &ConfirmRename,
9939 cx: &mut ViewContext<Self>,
9940 ) -> Option<Task<Result<()>>> {
9941 let rename = self.take_rename(false, cx)?;
9942 let workspace = self.workspace()?.downgrade();
9943 let (buffer, start) = self
9944 .buffer
9945 .read(cx)
9946 .text_anchor_for_position(rename.range.start, cx)?;
9947 let (end_buffer, _) = self
9948 .buffer
9949 .read(cx)
9950 .text_anchor_for_position(rename.range.end, cx)?;
9951 if buffer != end_buffer {
9952 return None;
9953 }
9954
9955 let old_name = rename.old_name;
9956 let new_name = rename.editor.read(cx).text(cx);
9957
9958 let rename = self.semantics_provider.as_ref()?.perform_rename(
9959 &buffer,
9960 start,
9961 new_name.clone(),
9962 cx,
9963 )?;
9964
9965 Some(cx.spawn(|editor, mut cx| async move {
9966 let project_transaction = rename.await?;
9967 Self::open_project_transaction(
9968 &editor,
9969 workspace,
9970 project_transaction,
9971 format!("Rename: {} → {}", old_name, new_name),
9972 cx.clone(),
9973 )
9974 .await?;
9975
9976 editor.update(&mut cx, |editor, cx| {
9977 editor.refresh_document_highlights(cx);
9978 })?;
9979 Ok(())
9980 }))
9981 }
9982
9983 fn take_rename(
9984 &mut self,
9985 moving_cursor: bool,
9986 cx: &mut ViewContext<Self>,
9987 ) -> Option<RenameState> {
9988 let rename = self.pending_rename.take()?;
9989 if rename.editor.focus_handle(cx).is_focused(cx) {
9990 cx.focus(&self.focus_handle);
9991 }
9992
9993 self.remove_blocks(
9994 [rename.block_id].into_iter().collect(),
9995 Some(Autoscroll::fit()),
9996 cx,
9997 );
9998 self.clear_highlights::<Rename>(cx);
9999 self.show_local_selections = true;
10000
10001 if moving_cursor {
10002 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10003 editor.selections.newest::<usize>(cx).head()
10004 });
10005
10006 // Update the selection to match the position of the selection inside
10007 // the rename editor.
10008 let snapshot = self.buffer.read(cx).read(cx);
10009 let rename_range = rename.range.to_offset(&snapshot);
10010 let cursor_in_editor = snapshot
10011 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10012 .min(rename_range.end);
10013 drop(snapshot);
10014
10015 self.change_selections(None, cx, |s| {
10016 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10017 });
10018 } else {
10019 self.refresh_document_highlights(cx);
10020 }
10021
10022 Some(rename)
10023 }
10024
10025 pub fn pending_rename(&self) -> Option<&RenameState> {
10026 self.pending_rename.as_ref()
10027 }
10028
10029 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10030 let project = match &self.project {
10031 Some(project) => project.clone(),
10032 None => return None,
10033 };
10034
10035 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10036 }
10037
10038 fn format_selections(
10039 &mut self,
10040 _: &FormatSelections,
10041 cx: &mut ViewContext<Self>,
10042 ) -> Option<Task<Result<()>>> {
10043 let project = match &self.project {
10044 Some(project) => project.clone(),
10045 None => return None,
10046 };
10047
10048 let selections = self
10049 .selections
10050 .all_adjusted(cx)
10051 .into_iter()
10052 .filter(|s| !s.is_empty())
10053 .collect_vec();
10054
10055 Some(self.perform_format(
10056 project,
10057 FormatTrigger::Manual,
10058 FormatTarget::Ranges(selections),
10059 cx,
10060 ))
10061 }
10062
10063 fn perform_format(
10064 &mut self,
10065 project: Model<Project>,
10066 trigger: FormatTrigger,
10067 target: FormatTarget,
10068 cx: &mut ViewContext<Self>,
10069 ) -> Task<Result<()>> {
10070 let buffer = self.buffer().clone();
10071 let mut buffers = buffer.read(cx).all_buffers();
10072 if trigger == FormatTrigger::Save {
10073 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10074 }
10075
10076 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10077 let format = project.update(cx, |project, cx| {
10078 project.format(buffers, true, trigger, target, cx)
10079 });
10080
10081 cx.spawn(|_, mut cx| async move {
10082 let transaction = futures::select_biased! {
10083 () = timeout => {
10084 log::warn!("timed out waiting for formatting");
10085 None
10086 }
10087 transaction = format.log_err().fuse() => transaction,
10088 };
10089
10090 buffer
10091 .update(&mut cx, |buffer, cx| {
10092 if let Some(transaction) = transaction {
10093 if !buffer.is_singleton() {
10094 buffer.push_transaction(&transaction.0, cx);
10095 }
10096 }
10097
10098 cx.notify();
10099 })
10100 .ok();
10101
10102 Ok(())
10103 })
10104 }
10105
10106 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10107 if let Some(project) = self.project.clone() {
10108 self.buffer.update(cx, |multi_buffer, cx| {
10109 project.update(cx, |project, cx| {
10110 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10111 });
10112 })
10113 }
10114 }
10115
10116 fn cancel_language_server_work(
10117 &mut self,
10118 _: &actions::CancelLanguageServerWork,
10119 cx: &mut ViewContext<Self>,
10120 ) {
10121 if let Some(project) = self.project.clone() {
10122 self.buffer.update(cx, |multi_buffer, cx| {
10123 project.update(cx, |project, cx| {
10124 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10125 });
10126 })
10127 }
10128 }
10129
10130 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10131 cx.show_character_palette();
10132 }
10133
10134 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10135 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10136 let buffer = self.buffer.read(cx).snapshot(cx);
10137 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10138 let is_valid = buffer
10139 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10140 .any(|entry| {
10141 entry.diagnostic.is_primary
10142 && !entry.range.is_empty()
10143 && entry.range.start == primary_range_start
10144 && entry.diagnostic.message == active_diagnostics.primary_message
10145 });
10146
10147 if is_valid != active_diagnostics.is_valid {
10148 active_diagnostics.is_valid = is_valid;
10149 let mut new_styles = HashMap::default();
10150 for (block_id, diagnostic) in &active_diagnostics.blocks {
10151 new_styles.insert(
10152 *block_id,
10153 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10154 );
10155 }
10156 self.display_map.update(cx, |display_map, _cx| {
10157 display_map.replace_blocks(new_styles)
10158 });
10159 }
10160 }
10161 }
10162
10163 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10164 self.dismiss_diagnostics(cx);
10165 let snapshot = self.snapshot(cx);
10166 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10167 let buffer = self.buffer.read(cx).snapshot(cx);
10168
10169 let mut primary_range = None;
10170 let mut primary_message = None;
10171 let mut group_end = Point::zero();
10172 let diagnostic_group = buffer
10173 .diagnostic_group::<MultiBufferPoint>(group_id)
10174 .filter_map(|entry| {
10175 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10176 && (entry.range.start.row == entry.range.end.row
10177 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10178 {
10179 return None;
10180 }
10181 if entry.range.end > group_end {
10182 group_end = entry.range.end;
10183 }
10184 if entry.diagnostic.is_primary {
10185 primary_range = Some(entry.range.clone());
10186 primary_message = Some(entry.diagnostic.message.clone());
10187 }
10188 Some(entry)
10189 })
10190 .collect::<Vec<_>>();
10191 let primary_range = primary_range?;
10192 let primary_message = primary_message?;
10193 let primary_range =
10194 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10195
10196 let blocks = display_map
10197 .insert_blocks(
10198 diagnostic_group.iter().map(|entry| {
10199 let diagnostic = entry.diagnostic.clone();
10200 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10201 BlockProperties {
10202 style: BlockStyle::Fixed,
10203 placement: BlockPlacement::Below(
10204 buffer.anchor_after(entry.range.start),
10205 ),
10206 height: message_height,
10207 render: diagnostic_block_renderer(diagnostic, None, true, true),
10208 priority: 0,
10209 }
10210 }),
10211 cx,
10212 )
10213 .into_iter()
10214 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10215 .collect();
10216
10217 Some(ActiveDiagnosticGroup {
10218 primary_range,
10219 primary_message,
10220 group_id,
10221 blocks,
10222 is_valid: true,
10223 })
10224 });
10225 self.active_diagnostics.is_some()
10226 }
10227
10228 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10229 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10230 self.display_map.update(cx, |display_map, cx| {
10231 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10232 });
10233 cx.notify();
10234 }
10235 }
10236
10237 pub fn set_selections_from_remote(
10238 &mut self,
10239 selections: Vec<Selection<Anchor>>,
10240 pending_selection: Option<Selection<Anchor>>,
10241 cx: &mut ViewContext<Self>,
10242 ) {
10243 let old_cursor_position = self.selections.newest_anchor().head();
10244 self.selections.change_with(cx, |s| {
10245 s.select_anchors(selections);
10246 if let Some(pending_selection) = pending_selection {
10247 s.set_pending(pending_selection, SelectMode::Character);
10248 } else {
10249 s.clear_pending();
10250 }
10251 });
10252 self.selections_did_change(false, &old_cursor_position, true, cx);
10253 }
10254
10255 fn push_to_selection_history(&mut self) {
10256 self.selection_history.push(SelectionHistoryEntry {
10257 selections: self.selections.disjoint_anchors(),
10258 select_next_state: self.select_next_state.clone(),
10259 select_prev_state: self.select_prev_state.clone(),
10260 add_selections_state: self.add_selections_state.clone(),
10261 });
10262 }
10263
10264 pub fn transact(
10265 &mut self,
10266 cx: &mut ViewContext<Self>,
10267 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10268 ) -> Option<TransactionId> {
10269 self.start_transaction_at(Instant::now(), cx);
10270 update(self, cx);
10271 self.end_transaction_at(Instant::now(), cx)
10272 }
10273
10274 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10275 self.end_selection(cx);
10276 if let Some(tx_id) = self
10277 .buffer
10278 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10279 {
10280 self.selection_history
10281 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10282 cx.emit(EditorEvent::TransactionBegun {
10283 transaction_id: tx_id,
10284 })
10285 }
10286 }
10287
10288 fn end_transaction_at(
10289 &mut self,
10290 now: Instant,
10291 cx: &mut ViewContext<Self>,
10292 ) -> Option<TransactionId> {
10293 if let Some(transaction_id) = self
10294 .buffer
10295 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10296 {
10297 if let Some((_, end_selections)) =
10298 self.selection_history.transaction_mut(transaction_id)
10299 {
10300 *end_selections = Some(self.selections.disjoint_anchors());
10301 } else {
10302 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10303 }
10304
10305 cx.emit(EditorEvent::Edited { transaction_id });
10306 Some(transaction_id)
10307 } else {
10308 None
10309 }
10310 }
10311
10312 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10313 if self.is_singleton(cx) {
10314 let selection = self.selections.newest::<Point>(cx);
10315
10316 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10317 let range = if selection.is_empty() {
10318 let point = selection.head().to_display_point(&display_map);
10319 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10320 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10321 .to_point(&display_map);
10322 start..end
10323 } else {
10324 selection.range()
10325 };
10326 if display_map.folds_in_range(range).next().is_some() {
10327 self.unfold_lines(&Default::default(), cx)
10328 } else {
10329 self.fold(&Default::default(), cx)
10330 }
10331 } else {
10332 let (display_snapshot, selections) = self.selections.all_adjusted_display(cx);
10333 let mut toggled_buffers = HashSet::default();
10334 for selection in selections {
10335 if let Some(buffer_id) = display_snapshot
10336 .display_point_to_anchor(selection.head(), Bias::Right)
10337 .buffer_id
10338 {
10339 if toggled_buffers.insert(buffer_id) {
10340 if self.buffer_folded(buffer_id, cx) {
10341 self.unfold_buffer(buffer_id, cx);
10342 } else {
10343 self.fold_buffer(buffer_id, cx);
10344 }
10345 }
10346 }
10347 if let Some(buffer_id) = display_snapshot
10348 .display_point_to_anchor(selection.tail(), Bias::Left)
10349 .buffer_id
10350 {
10351 if toggled_buffers.insert(buffer_id) {
10352 if self.buffer_folded(buffer_id, cx) {
10353 self.unfold_buffer(buffer_id, cx);
10354 } else {
10355 self.fold_buffer(buffer_id, cx);
10356 }
10357 }
10358 }
10359 }
10360 }
10361 }
10362
10363 pub fn toggle_fold_recursive(
10364 &mut self,
10365 _: &actions::ToggleFoldRecursive,
10366 cx: &mut ViewContext<Self>,
10367 ) {
10368 let selection = self.selections.newest::<Point>(cx);
10369
10370 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10371 let range = if selection.is_empty() {
10372 let point = selection.head().to_display_point(&display_map);
10373 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10374 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10375 .to_point(&display_map);
10376 start..end
10377 } else {
10378 selection.range()
10379 };
10380 if display_map.folds_in_range(range).next().is_some() {
10381 self.unfold_recursive(&Default::default(), cx)
10382 } else {
10383 self.fold_recursive(&Default::default(), cx)
10384 }
10385 }
10386
10387 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10388 if self.is_singleton(cx) {
10389 let mut to_fold = Vec::new();
10390 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10391 let selections = self.selections.all_adjusted(cx);
10392
10393 for selection in selections {
10394 let range = selection.range().sorted();
10395 let buffer_start_row = range.start.row;
10396
10397 if range.start.row != range.end.row {
10398 let mut found = false;
10399 let mut row = range.start.row;
10400 while row <= range.end.row {
10401 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10402 {
10403 found = true;
10404 row = crease.range().end.row + 1;
10405 to_fold.push(crease);
10406 } else {
10407 row += 1
10408 }
10409 }
10410 if found {
10411 continue;
10412 }
10413 }
10414
10415 for row in (0..=range.start.row).rev() {
10416 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10417 if crease.range().end.row >= buffer_start_row {
10418 to_fold.push(crease);
10419 if row <= range.start.row {
10420 break;
10421 }
10422 }
10423 }
10424 }
10425 }
10426
10427 self.fold_creases(to_fold, true, cx);
10428 } else {
10429 let (display_snapshot, selections) = self.selections.all_adjusted_display(cx);
10430 let mut folded_buffers = HashSet::default();
10431 for selection in selections {
10432 if let Some(buffer_id) = display_snapshot
10433 .display_point_to_anchor(selection.head(), Bias::Right)
10434 .buffer_id
10435 {
10436 if folded_buffers.insert(buffer_id) {
10437 self.fold_buffer(buffer_id, cx);
10438 }
10439 }
10440 if let Some(buffer_id) = display_snapshot
10441 .display_point_to_anchor(selection.tail(), Bias::Left)
10442 .buffer_id
10443 {
10444 if folded_buffers.insert(buffer_id) {
10445 self.fold_buffer(buffer_id, cx);
10446 }
10447 }
10448 }
10449 }
10450 }
10451
10452 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10453 if !self.buffer.read(cx).is_singleton() {
10454 return;
10455 }
10456
10457 let fold_at_level = fold_at.level;
10458 let snapshot = self.buffer.read(cx).snapshot(cx);
10459 let mut to_fold = Vec::new();
10460 let mut stack = vec![(0, snapshot.max_row().0, 1)];
10461
10462 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10463 while start_row < end_row {
10464 match self
10465 .snapshot(cx)
10466 .crease_for_buffer_row(MultiBufferRow(start_row))
10467 {
10468 Some(crease) => {
10469 let nested_start_row = crease.range().start.row + 1;
10470 let nested_end_row = crease.range().end.row;
10471
10472 if current_level < fold_at_level {
10473 stack.push((nested_start_row, nested_end_row, current_level + 1));
10474 } else if current_level == fold_at_level {
10475 to_fold.push(crease);
10476 }
10477
10478 start_row = nested_end_row + 1;
10479 }
10480 None => start_row += 1,
10481 }
10482 }
10483 }
10484
10485 self.fold_creases(to_fold, true, cx);
10486 }
10487
10488 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10489 if self.buffer.read(cx).is_singleton() {
10490 let mut fold_ranges = Vec::new();
10491 let snapshot = self.buffer.read(cx).snapshot(cx);
10492
10493 for row in 0..snapshot.max_row().0 {
10494 if let Some(foldable_range) =
10495 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10496 {
10497 fold_ranges.push(foldable_range);
10498 }
10499 }
10500
10501 self.fold_creases(fold_ranges, true, cx);
10502 } else {
10503 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10504 editor
10505 .update(&mut cx, |editor, cx| {
10506 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10507 editor.fold_buffer(buffer_id, cx);
10508 }
10509 })
10510 .ok();
10511 });
10512 }
10513 }
10514
10515 pub fn fold_function_bodies(
10516 &mut self,
10517 _: &actions::FoldFunctionBodies,
10518 cx: &mut ViewContext<Self>,
10519 ) {
10520 let snapshot = self.buffer.read(cx).snapshot(cx);
10521 let Some((_, _, buffer)) = snapshot.as_singleton() else {
10522 return;
10523 };
10524 let creases = buffer
10525 .function_body_fold_ranges(0..buffer.len())
10526 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10527 .collect();
10528
10529 self.fold_creases(creases, true, cx);
10530 }
10531
10532 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10533 let mut to_fold = Vec::new();
10534 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10535 let selections = self.selections.all_adjusted(cx);
10536
10537 for selection in selections {
10538 let range = selection.range().sorted();
10539 let buffer_start_row = range.start.row;
10540
10541 if range.start.row != range.end.row {
10542 let mut found = false;
10543 for row in range.start.row..=range.end.row {
10544 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10545 found = true;
10546 to_fold.push(crease);
10547 }
10548 }
10549 if found {
10550 continue;
10551 }
10552 }
10553
10554 for row in (0..=range.start.row).rev() {
10555 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10556 if crease.range().end.row >= buffer_start_row {
10557 to_fold.push(crease);
10558 } else {
10559 break;
10560 }
10561 }
10562 }
10563 }
10564
10565 self.fold_creases(to_fold, true, cx);
10566 }
10567
10568 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10569 let buffer_row = fold_at.buffer_row;
10570 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10571
10572 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10573 let autoscroll = self
10574 .selections
10575 .all::<Point>(cx)
10576 .iter()
10577 .any(|selection| crease.range().overlaps(&selection.range()));
10578
10579 self.fold_creases(vec![crease], autoscroll, cx);
10580 }
10581 }
10582
10583 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10584 if self.is_singleton(cx) {
10585 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10586 let buffer = &display_map.buffer_snapshot;
10587 let selections = self.selections.all::<Point>(cx);
10588 let ranges = selections
10589 .iter()
10590 .map(|s| {
10591 let range = s.display_range(&display_map).sorted();
10592 let mut start = range.start.to_point(&display_map);
10593 let mut end = range.end.to_point(&display_map);
10594 start.column = 0;
10595 end.column = buffer.line_len(MultiBufferRow(end.row));
10596 start..end
10597 })
10598 .collect::<Vec<_>>();
10599
10600 self.unfold_ranges(&ranges, true, true, cx);
10601 } else {
10602 let (display_snapshot, selections) = self.selections.all_adjusted_display(cx);
10603 let mut unfolded_buffers = HashSet::default();
10604 for selection in selections {
10605 if let Some(buffer_id) = display_snapshot
10606 .display_point_to_anchor(selection.head(), Bias::Right)
10607 .buffer_id
10608 {
10609 if unfolded_buffers.insert(buffer_id) {
10610 self.unfold_buffer(buffer_id, cx);
10611 }
10612 }
10613 if let Some(buffer_id) = display_snapshot
10614 .display_point_to_anchor(selection.tail(), Bias::Left)
10615 .buffer_id
10616 {
10617 if unfolded_buffers.insert(buffer_id) {
10618 self.unfold_buffer(buffer_id, cx);
10619 }
10620 }
10621 }
10622 }
10623 }
10624
10625 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10626 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10627 let selections = self.selections.all::<Point>(cx);
10628 let ranges = selections
10629 .iter()
10630 .map(|s| {
10631 let mut range = s.display_range(&display_map).sorted();
10632 *range.start.column_mut() = 0;
10633 *range.end.column_mut() = display_map.line_len(range.end.row());
10634 let start = range.start.to_point(&display_map);
10635 let end = range.end.to_point(&display_map);
10636 start..end
10637 })
10638 .collect::<Vec<_>>();
10639
10640 self.unfold_ranges(&ranges, true, true, cx);
10641 }
10642
10643 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10644 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10645
10646 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10647 ..Point::new(
10648 unfold_at.buffer_row.0,
10649 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10650 );
10651
10652 let autoscroll = self
10653 .selections
10654 .all::<Point>(cx)
10655 .iter()
10656 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10657
10658 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10659 }
10660
10661 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10662 if self.buffer.read(cx).is_singleton() {
10663 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10664 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10665 } else {
10666 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10667 editor
10668 .update(&mut cx, |editor, cx| {
10669 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10670 editor.unfold_buffer(buffer_id, cx);
10671 }
10672 })
10673 .ok();
10674 });
10675 }
10676 }
10677
10678 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10679 let selections = self.selections.all::<Point>(cx);
10680 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10681 let line_mode = self.selections.line_mode;
10682 let ranges = selections
10683 .into_iter()
10684 .map(|s| {
10685 if line_mode {
10686 let start = Point::new(s.start.row, 0);
10687 let end = Point::new(
10688 s.end.row,
10689 display_map
10690 .buffer_snapshot
10691 .line_len(MultiBufferRow(s.end.row)),
10692 );
10693 Crease::simple(start..end, display_map.fold_placeholder.clone())
10694 } else {
10695 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10696 }
10697 })
10698 .collect::<Vec<_>>();
10699 self.fold_creases(ranges, true, cx);
10700 }
10701
10702 pub fn fold_creases<T: ToOffset + Clone>(
10703 &mut self,
10704 creases: Vec<Crease<T>>,
10705 auto_scroll: bool,
10706 cx: &mut ViewContext<Self>,
10707 ) {
10708 if creases.is_empty() {
10709 return;
10710 }
10711
10712 let mut buffers_affected = HashSet::default();
10713 let multi_buffer = self.buffer().read(cx);
10714 for crease in &creases {
10715 if let Some((_, buffer, _)) =
10716 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10717 {
10718 buffers_affected.insert(buffer.read(cx).remote_id());
10719 };
10720 }
10721
10722 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10723
10724 if auto_scroll {
10725 self.request_autoscroll(Autoscroll::fit(), cx);
10726 }
10727
10728 for buffer_id in buffers_affected {
10729 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10730 }
10731
10732 cx.notify();
10733
10734 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10735 // Clear diagnostics block when folding a range that contains it.
10736 let snapshot = self.snapshot(cx);
10737 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10738 drop(snapshot);
10739 self.active_diagnostics = Some(active_diagnostics);
10740 self.dismiss_diagnostics(cx);
10741 } else {
10742 self.active_diagnostics = Some(active_diagnostics);
10743 }
10744 }
10745
10746 self.scrollbar_marker_state.dirty = true;
10747 }
10748
10749 /// Removes any folds whose ranges intersect any of the given ranges.
10750 pub fn unfold_ranges<T: ToOffset + Clone>(
10751 &mut self,
10752 ranges: &[Range<T>],
10753 inclusive: bool,
10754 auto_scroll: bool,
10755 cx: &mut ViewContext<Self>,
10756 ) {
10757 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10758 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10759 });
10760 }
10761
10762 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10763 if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10764 return;
10765 }
10766 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10767 return;
10768 };
10769 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10770 self.display_map
10771 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10772 cx.emit(EditorEvent::BufferFoldToggled {
10773 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
10774 folded: true,
10775 });
10776 cx.notify();
10777 }
10778
10779 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10780 if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
10781 return;
10782 }
10783 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10784 return;
10785 };
10786 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10787 self.display_map.update(cx, |display_map, cx| {
10788 display_map.unfold_buffer(buffer_id, cx);
10789 });
10790 cx.emit(EditorEvent::BufferFoldToggled {
10791 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
10792 folded: false,
10793 });
10794 cx.notify();
10795 }
10796
10797 pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
10798 self.display_map.read(cx).buffer_folded(buffer)
10799 }
10800
10801 /// Removes any folds with the given ranges.
10802 pub fn remove_folds_with_type<T: ToOffset + Clone>(
10803 &mut self,
10804 ranges: &[Range<T>],
10805 type_id: TypeId,
10806 auto_scroll: bool,
10807 cx: &mut ViewContext<Self>,
10808 ) {
10809 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10810 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
10811 });
10812 }
10813
10814 fn remove_folds_with<T: ToOffset + Clone>(
10815 &mut self,
10816 ranges: &[Range<T>],
10817 auto_scroll: bool,
10818 cx: &mut ViewContext<Self>,
10819 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
10820 ) {
10821 if ranges.is_empty() {
10822 return;
10823 }
10824
10825 let mut buffers_affected = HashSet::default();
10826 let multi_buffer = self.buffer().read(cx);
10827 for range in ranges {
10828 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10829 buffers_affected.insert(buffer.read(cx).remote_id());
10830 };
10831 }
10832
10833 self.display_map.update(cx, update);
10834
10835 if auto_scroll {
10836 self.request_autoscroll(Autoscroll::fit(), cx);
10837 }
10838
10839 for buffer_id in buffers_affected {
10840 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10841 }
10842
10843 cx.notify();
10844 self.scrollbar_marker_state.dirty = true;
10845 self.active_indent_guides_state.dirty = true;
10846 }
10847
10848 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10849 self.display_map.read(cx).fold_placeholder.clone()
10850 }
10851
10852 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10853 if hovered != self.gutter_hovered {
10854 self.gutter_hovered = hovered;
10855 cx.notify();
10856 }
10857 }
10858
10859 pub fn insert_blocks(
10860 &mut self,
10861 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10862 autoscroll: Option<Autoscroll>,
10863 cx: &mut ViewContext<Self>,
10864 ) -> Vec<CustomBlockId> {
10865 let blocks = self
10866 .display_map
10867 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10868 if let Some(autoscroll) = autoscroll {
10869 self.request_autoscroll(autoscroll, cx);
10870 }
10871 cx.notify();
10872 blocks
10873 }
10874
10875 pub fn resize_blocks(
10876 &mut self,
10877 heights: HashMap<CustomBlockId, u32>,
10878 autoscroll: Option<Autoscroll>,
10879 cx: &mut ViewContext<Self>,
10880 ) {
10881 self.display_map
10882 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10883 if let Some(autoscroll) = autoscroll {
10884 self.request_autoscroll(autoscroll, cx);
10885 }
10886 cx.notify();
10887 }
10888
10889 pub fn replace_blocks(
10890 &mut self,
10891 renderers: HashMap<CustomBlockId, RenderBlock>,
10892 autoscroll: Option<Autoscroll>,
10893 cx: &mut ViewContext<Self>,
10894 ) {
10895 self.display_map
10896 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10897 if let Some(autoscroll) = autoscroll {
10898 self.request_autoscroll(autoscroll, cx);
10899 }
10900 cx.notify();
10901 }
10902
10903 pub fn remove_blocks(
10904 &mut self,
10905 block_ids: HashSet<CustomBlockId>,
10906 autoscroll: Option<Autoscroll>,
10907 cx: &mut ViewContext<Self>,
10908 ) {
10909 self.display_map.update(cx, |display_map, cx| {
10910 display_map.remove_blocks(block_ids, cx)
10911 });
10912 if let Some(autoscroll) = autoscroll {
10913 self.request_autoscroll(autoscroll, cx);
10914 }
10915 cx.notify();
10916 }
10917
10918 pub fn row_for_block(
10919 &self,
10920 block_id: CustomBlockId,
10921 cx: &mut ViewContext<Self>,
10922 ) -> Option<DisplayRow> {
10923 self.display_map
10924 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10925 }
10926
10927 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10928 self.focused_block = Some(focused_block);
10929 }
10930
10931 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10932 self.focused_block.take()
10933 }
10934
10935 pub fn insert_creases(
10936 &mut self,
10937 creases: impl IntoIterator<Item = Crease<Anchor>>,
10938 cx: &mut ViewContext<Self>,
10939 ) -> Vec<CreaseId> {
10940 self.display_map
10941 .update(cx, |map, cx| map.insert_creases(creases, cx))
10942 }
10943
10944 pub fn remove_creases(
10945 &mut self,
10946 ids: impl IntoIterator<Item = CreaseId>,
10947 cx: &mut ViewContext<Self>,
10948 ) {
10949 self.display_map
10950 .update(cx, |map, cx| map.remove_creases(ids, cx));
10951 }
10952
10953 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10954 self.display_map
10955 .update(cx, |map, cx| map.snapshot(cx))
10956 .longest_row()
10957 }
10958
10959 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10960 self.display_map
10961 .update(cx, |map, cx| map.snapshot(cx))
10962 .max_point()
10963 }
10964
10965 pub fn text(&self, cx: &AppContext) -> String {
10966 self.buffer.read(cx).read(cx).text()
10967 }
10968
10969 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10970 let text = self.text(cx);
10971 let text = text.trim();
10972
10973 if text.is_empty() {
10974 return None;
10975 }
10976
10977 Some(text.to_string())
10978 }
10979
10980 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10981 self.transact(cx, |this, cx| {
10982 this.buffer
10983 .read(cx)
10984 .as_singleton()
10985 .expect("you can only call set_text on editors for singleton buffers")
10986 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10987 });
10988 }
10989
10990 pub fn display_text(&self, cx: &mut AppContext) -> String {
10991 self.display_map
10992 .update(cx, |map, cx| map.snapshot(cx))
10993 .text()
10994 }
10995
10996 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10997 let mut wrap_guides = smallvec::smallvec![];
10998
10999 if self.show_wrap_guides == Some(false) {
11000 return wrap_guides;
11001 }
11002
11003 let settings = self.buffer.read(cx).settings_at(0, cx);
11004 if settings.show_wrap_guides {
11005 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11006 wrap_guides.push((soft_wrap as usize, true));
11007 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11008 wrap_guides.push((soft_wrap as usize, true));
11009 }
11010 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11011 }
11012
11013 wrap_guides
11014 }
11015
11016 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11017 let settings = self.buffer.read(cx).settings_at(0, cx);
11018 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11019 match mode {
11020 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11021 SoftWrap::None
11022 }
11023 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11024 language_settings::SoftWrap::PreferredLineLength => {
11025 SoftWrap::Column(settings.preferred_line_length)
11026 }
11027 language_settings::SoftWrap::Bounded => {
11028 SoftWrap::Bounded(settings.preferred_line_length)
11029 }
11030 }
11031 }
11032
11033 pub fn set_soft_wrap_mode(
11034 &mut self,
11035 mode: language_settings::SoftWrap,
11036 cx: &mut ViewContext<Self>,
11037 ) {
11038 self.soft_wrap_mode_override = Some(mode);
11039 cx.notify();
11040 }
11041
11042 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11043 self.text_style_refinement = Some(style);
11044 }
11045
11046 /// called by the Element so we know what style we were most recently rendered with.
11047 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11048 let rem_size = cx.rem_size();
11049 self.display_map.update(cx, |map, cx| {
11050 map.set_font(
11051 style.text.font(),
11052 style.text.font_size.to_pixels(rem_size),
11053 cx,
11054 )
11055 });
11056 self.style = Some(style);
11057 }
11058
11059 pub fn style(&self) -> Option<&EditorStyle> {
11060 self.style.as_ref()
11061 }
11062
11063 // Called by the element. This method is not designed to be called outside of the editor
11064 // element's layout code because it does not notify when rewrapping is computed synchronously.
11065 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11066 self.display_map
11067 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11068 }
11069
11070 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11071 if self.soft_wrap_mode_override.is_some() {
11072 self.soft_wrap_mode_override.take();
11073 } else {
11074 let soft_wrap = match self.soft_wrap_mode(cx) {
11075 SoftWrap::GitDiff => return,
11076 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11077 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11078 language_settings::SoftWrap::None
11079 }
11080 };
11081 self.soft_wrap_mode_override = Some(soft_wrap);
11082 }
11083 cx.notify();
11084 }
11085
11086 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11087 let Some(workspace) = self.workspace() else {
11088 return;
11089 };
11090 let fs = workspace.read(cx).app_state().fs.clone();
11091 let current_show = TabBarSettings::get_global(cx).show;
11092 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11093 setting.show = Some(!current_show);
11094 });
11095 }
11096
11097 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11098 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11099 self.buffer
11100 .read(cx)
11101 .settings_at(0, cx)
11102 .indent_guides
11103 .enabled
11104 });
11105 self.show_indent_guides = Some(!currently_enabled);
11106 cx.notify();
11107 }
11108
11109 fn should_show_indent_guides(&self) -> Option<bool> {
11110 self.show_indent_guides
11111 }
11112
11113 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11114 let mut editor_settings = EditorSettings::get_global(cx).clone();
11115 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11116 EditorSettings::override_global(editor_settings, cx);
11117 }
11118
11119 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11120 self.use_relative_line_numbers
11121 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11122 }
11123
11124 pub fn toggle_relative_line_numbers(
11125 &mut self,
11126 _: &ToggleRelativeLineNumbers,
11127 cx: &mut ViewContext<Self>,
11128 ) {
11129 let is_relative = self.should_use_relative_line_numbers(cx);
11130 self.set_relative_line_number(Some(!is_relative), cx)
11131 }
11132
11133 pub fn set_relative_line_number(
11134 &mut self,
11135 is_relative: Option<bool>,
11136 cx: &mut ViewContext<Self>,
11137 ) {
11138 self.use_relative_line_numbers = is_relative;
11139 cx.notify();
11140 }
11141
11142 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11143 self.show_gutter = show_gutter;
11144 cx.notify();
11145 }
11146
11147 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11148 self.show_line_numbers = Some(show_line_numbers);
11149 cx.notify();
11150 }
11151
11152 pub fn set_show_git_diff_gutter(
11153 &mut self,
11154 show_git_diff_gutter: bool,
11155 cx: &mut ViewContext<Self>,
11156 ) {
11157 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11158 cx.notify();
11159 }
11160
11161 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11162 self.show_code_actions = Some(show_code_actions);
11163 cx.notify();
11164 }
11165
11166 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11167 self.show_runnables = Some(show_runnables);
11168 cx.notify();
11169 }
11170
11171 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11172 if self.display_map.read(cx).masked != masked {
11173 self.display_map.update(cx, |map, _| map.masked = masked);
11174 }
11175 cx.notify()
11176 }
11177
11178 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11179 self.show_wrap_guides = Some(show_wrap_guides);
11180 cx.notify();
11181 }
11182
11183 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11184 self.show_indent_guides = Some(show_indent_guides);
11185 cx.notify();
11186 }
11187
11188 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11189 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11190 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11191 if let Some(dir) = file.abs_path(cx).parent() {
11192 return Some(dir.to_owned());
11193 }
11194 }
11195
11196 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11197 return Some(project_path.path.to_path_buf());
11198 }
11199 }
11200
11201 None
11202 }
11203
11204 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11205 self.active_excerpt(cx)?
11206 .1
11207 .read(cx)
11208 .file()
11209 .and_then(|f| f.as_local())
11210 }
11211
11212 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11213 if let Some(target) = self.target_file(cx) {
11214 cx.reveal_path(&target.abs_path(cx));
11215 }
11216 }
11217
11218 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11219 if let Some(file) = self.target_file(cx) {
11220 if let Some(path) = file.abs_path(cx).to_str() {
11221 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11222 }
11223 }
11224 }
11225
11226 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11227 if let Some(file) = self.target_file(cx) {
11228 if let Some(path) = file.path().to_str() {
11229 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11230 }
11231 }
11232 }
11233
11234 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11235 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11236
11237 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11238 self.start_git_blame(true, cx);
11239 }
11240
11241 cx.notify();
11242 }
11243
11244 pub fn toggle_git_blame_inline(
11245 &mut self,
11246 _: &ToggleGitBlameInline,
11247 cx: &mut ViewContext<Self>,
11248 ) {
11249 self.toggle_git_blame_inline_internal(true, cx);
11250 cx.notify();
11251 }
11252
11253 pub fn git_blame_inline_enabled(&self) -> bool {
11254 self.git_blame_inline_enabled
11255 }
11256
11257 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11258 self.show_selection_menu = self
11259 .show_selection_menu
11260 .map(|show_selections_menu| !show_selections_menu)
11261 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11262
11263 cx.notify();
11264 }
11265
11266 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11267 self.show_selection_menu
11268 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11269 }
11270
11271 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11272 if let Some(project) = self.project.as_ref() {
11273 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11274 return;
11275 };
11276
11277 if buffer.read(cx).file().is_none() {
11278 return;
11279 }
11280
11281 let focused = self.focus_handle(cx).contains_focused(cx);
11282
11283 let project = project.clone();
11284 let blame =
11285 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11286 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11287 self.blame = Some(blame);
11288 }
11289 }
11290
11291 fn toggle_git_blame_inline_internal(
11292 &mut self,
11293 user_triggered: bool,
11294 cx: &mut ViewContext<Self>,
11295 ) {
11296 if self.git_blame_inline_enabled {
11297 self.git_blame_inline_enabled = false;
11298 self.show_git_blame_inline = false;
11299 self.show_git_blame_inline_delay_task.take();
11300 } else {
11301 self.git_blame_inline_enabled = true;
11302 self.start_git_blame_inline(user_triggered, cx);
11303 }
11304
11305 cx.notify();
11306 }
11307
11308 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11309 self.start_git_blame(user_triggered, cx);
11310
11311 if ProjectSettings::get_global(cx)
11312 .git
11313 .inline_blame_delay()
11314 .is_some()
11315 {
11316 self.start_inline_blame_timer(cx);
11317 } else {
11318 self.show_git_blame_inline = true
11319 }
11320 }
11321
11322 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11323 self.blame.as_ref()
11324 }
11325
11326 pub fn show_git_blame_gutter(&self) -> bool {
11327 self.show_git_blame_gutter
11328 }
11329
11330 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11331 self.show_git_blame_gutter && self.has_blame_entries(cx)
11332 }
11333
11334 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11335 self.show_git_blame_inline
11336 && self.focus_handle.is_focused(cx)
11337 && !self.newest_selection_head_on_empty_line(cx)
11338 && self.has_blame_entries(cx)
11339 }
11340
11341 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11342 self.blame()
11343 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11344 }
11345
11346 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11347 let cursor_anchor = self.selections.newest_anchor().head();
11348
11349 let snapshot = self.buffer.read(cx).snapshot(cx);
11350 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11351
11352 snapshot.line_len(buffer_row) == 0
11353 }
11354
11355 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11356 let buffer_and_selection = maybe!({
11357 let selection = self.selections.newest::<Point>(cx);
11358 let selection_range = selection.range();
11359
11360 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11361 (buffer, selection_range.start.row..selection_range.end.row)
11362 } else {
11363 let buffer_ranges = self
11364 .buffer()
11365 .read(cx)
11366 .range_to_buffer_ranges(selection_range, cx);
11367
11368 let (buffer, range, _) = if selection.reversed {
11369 buffer_ranges.first()
11370 } else {
11371 buffer_ranges.last()
11372 }?;
11373
11374 let snapshot = buffer.read(cx).snapshot();
11375 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11376 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11377 (buffer.clone(), selection)
11378 };
11379
11380 Some((buffer, selection))
11381 });
11382
11383 let Some((buffer, selection)) = buffer_and_selection else {
11384 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11385 };
11386
11387 let Some(project) = self.project.as_ref() else {
11388 return Task::ready(Err(anyhow!("editor does not have project")));
11389 };
11390
11391 project.update(cx, |project, cx| {
11392 project.get_permalink_to_line(&buffer, selection, cx)
11393 })
11394 }
11395
11396 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11397 let permalink_task = self.get_permalink_to_line(cx);
11398 let workspace = self.workspace();
11399
11400 cx.spawn(|_, mut cx| async move {
11401 match permalink_task.await {
11402 Ok(permalink) => {
11403 cx.update(|cx| {
11404 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11405 })
11406 .ok();
11407 }
11408 Err(err) => {
11409 let message = format!("Failed to copy permalink: {err}");
11410
11411 Err::<(), anyhow::Error>(err).log_err();
11412
11413 if let Some(workspace) = workspace {
11414 workspace
11415 .update(&mut cx, |workspace, cx| {
11416 struct CopyPermalinkToLine;
11417
11418 workspace.show_toast(
11419 Toast::new(
11420 NotificationId::unique::<CopyPermalinkToLine>(),
11421 message,
11422 ),
11423 cx,
11424 )
11425 })
11426 .ok();
11427 }
11428 }
11429 }
11430 })
11431 .detach();
11432 }
11433
11434 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11435 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11436 if let Some(file) = self.target_file(cx) {
11437 if let Some(path) = file.path().to_str() {
11438 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11439 }
11440 }
11441 }
11442
11443 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11444 let permalink_task = self.get_permalink_to_line(cx);
11445 let workspace = self.workspace();
11446
11447 cx.spawn(|_, mut cx| async move {
11448 match permalink_task.await {
11449 Ok(permalink) => {
11450 cx.update(|cx| {
11451 cx.open_url(permalink.as_ref());
11452 })
11453 .ok();
11454 }
11455 Err(err) => {
11456 let message = format!("Failed to open permalink: {err}");
11457
11458 Err::<(), anyhow::Error>(err).log_err();
11459
11460 if let Some(workspace) = workspace {
11461 workspace
11462 .update(&mut cx, |workspace, cx| {
11463 struct OpenPermalinkToLine;
11464
11465 workspace.show_toast(
11466 Toast::new(
11467 NotificationId::unique::<OpenPermalinkToLine>(),
11468 message,
11469 ),
11470 cx,
11471 )
11472 })
11473 .ok();
11474 }
11475 }
11476 }
11477 })
11478 .detach();
11479 }
11480
11481 pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11482 self.insert_uuid(UuidVersion::V4, cx);
11483 }
11484
11485 pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11486 self.insert_uuid(UuidVersion::V7, cx);
11487 }
11488
11489 fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11490 self.transact(cx, |this, cx| {
11491 let edits = this
11492 .selections
11493 .all::<Point>(cx)
11494 .into_iter()
11495 .map(|selection| {
11496 let uuid = match version {
11497 UuidVersion::V4 => uuid::Uuid::new_v4(),
11498 UuidVersion::V7 => uuid::Uuid::now_v7(),
11499 };
11500
11501 (selection.range(), uuid.to_string())
11502 });
11503 this.edit(edits, cx);
11504 this.refresh_inline_completion(true, false, cx);
11505 });
11506 }
11507
11508 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11509 /// last highlight added will be used.
11510 ///
11511 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11512 pub fn highlight_rows<T: 'static>(
11513 &mut self,
11514 range: Range<Anchor>,
11515 color: Hsla,
11516 should_autoscroll: bool,
11517 cx: &mut ViewContext<Self>,
11518 ) {
11519 let snapshot = self.buffer().read(cx).snapshot(cx);
11520 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11521 let ix = row_highlights.binary_search_by(|highlight| {
11522 Ordering::Equal
11523 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11524 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11525 });
11526
11527 if let Err(mut ix) = ix {
11528 let index = post_inc(&mut self.highlight_order);
11529
11530 // If this range intersects with the preceding highlight, then merge it with
11531 // the preceding highlight. Otherwise insert a new highlight.
11532 let mut merged = false;
11533 if ix > 0 {
11534 let prev_highlight = &mut row_highlights[ix - 1];
11535 if prev_highlight
11536 .range
11537 .end
11538 .cmp(&range.start, &snapshot)
11539 .is_ge()
11540 {
11541 ix -= 1;
11542 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11543 prev_highlight.range.end = range.end;
11544 }
11545 merged = true;
11546 prev_highlight.index = index;
11547 prev_highlight.color = color;
11548 prev_highlight.should_autoscroll = should_autoscroll;
11549 }
11550 }
11551
11552 if !merged {
11553 row_highlights.insert(
11554 ix,
11555 RowHighlight {
11556 range: range.clone(),
11557 index,
11558 color,
11559 should_autoscroll,
11560 },
11561 );
11562 }
11563
11564 // If any of the following highlights intersect with this one, merge them.
11565 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11566 let highlight = &row_highlights[ix];
11567 if next_highlight
11568 .range
11569 .start
11570 .cmp(&highlight.range.end, &snapshot)
11571 .is_le()
11572 {
11573 if next_highlight
11574 .range
11575 .end
11576 .cmp(&highlight.range.end, &snapshot)
11577 .is_gt()
11578 {
11579 row_highlights[ix].range.end = next_highlight.range.end;
11580 }
11581 row_highlights.remove(ix + 1);
11582 } else {
11583 break;
11584 }
11585 }
11586 }
11587 }
11588
11589 /// Remove any highlighted row ranges of the given type that intersect the
11590 /// given ranges.
11591 pub fn remove_highlighted_rows<T: 'static>(
11592 &mut self,
11593 ranges_to_remove: Vec<Range<Anchor>>,
11594 cx: &mut ViewContext<Self>,
11595 ) {
11596 let snapshot = self.buffer().read(cx).snapshot(cx);
11597 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11598 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11599 row_highlights.retain(|highlight| {
11600 while let Some(range_to_remove) = ranges_to_remove.peek() {
11601 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11602 Ordering::Less | Ordering::Equal => {
11603 ranges_to_remove.next();
11604 }
11605 Ordering::Greater => {
11606 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11607 Ordering::Less | Ordering::Equal => {
11608 return false;
11609 }
11610 Ordering::Greater => break,
11611 }
11612 }
11613 }
11614 }
11615
11616 true
11617 })
11618 }
11619
11620 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11621 pub fn clear_row_highlights<T: 'static>(&mut self) {
11622 self.highlighted_rows.remove(&TypeId::of::<T>());
11623 }
11624
11625 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11626 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11627 self.highlighted_rows
11628 .get(&TypeId::of::<T>())
11629 .map_or(&[] as &[_], |vec| vec.as_slice())
11630 .iter()
11631 .map(|highlight| (highlight.range.clone(), highlight.color))
11632 }
11633
11634 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11635 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11636 /// Allows to ignore certain kinds of highlights.
11637 pub fn highlighted_display_rows(
11638 &mut self,
11639 cx: &mut WindowContext,
11640 ) -> BTreeMap<DisplayRow, Hsla> {
11641 let snapshot = self.snapshot(cx);
11642 let mut used_highlight_orders = HashMap::default();
11643 self.highlighted_rows
11644 .iter()
11645 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11646 .fold(
11647 BTreeMap::<DisplayRow, Hsla>::new(),
11648 |mut unique_rows, highlight| {
11649 let start = highlight.range.start.to_display_point(&snapshot);
11650 let end = highlight.range.end.to_display_point(&snapshot);
11651 let start_row = start.row().0;
11652 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11653 && end.column() == 0
11654 {
11655 end.row().0.saturating_sub(1)
11656 } else {
11657 end.row().0
11658 };
11659 for row in start_row..=end_row {
11660 let used_index =
11661 used_highlight_orders.entry(row).or_insert(highlight.index);
11662 if highlight.index >= *used_index {
11663 *used_index = highlight.index;
11664 unique_rows.insert(DisplayRow(row), highlight.color);
11665 }
11666 }
11667 unique_rows
11668 },
11669 )
11670 }
11671
11672 pub fn highlighted_display_row_for_autoscroll(
11673 &self,
11674 snapshot: &DisplaySnapshot,
11675 ) -> Option<DisplayRow> {
11676 self.highlighted_rows
11677 .values()
11678 .flat_map(|highlighted_rows| highlighted_rows.iter())
11679 .filter_map(|highlight| {
11680 if highlight.should_autoscroll {
11681 Some(highlight.range.start.to_display_point(snapshot).row())
11682 } else {
11683 None
11684 }
11685 })
11686 .min()
11687 }
11688
11689 pub fn set_search_within_ranges(
11690 &mut self,
11691 ranges: &[Range<Anchor>],
11692 cx: &mut ViewContext<Self>,
11693 ) {
11694 self.highlight_background::<SearchWithinRange>(
11695 ranges,
11696 |colors| colors.editor_document_highlight_read_background,
11697 cx,
11698 )
11699 }
11700
11701 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11702 self.breadcrumb_header = Some(new_header);
11703 }
11704
11705 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11706 self.clear_background_highlights::<SearchWithinRange>(cx);
11707 }
11708
11709 pub fn highlight_background<T: 'static>(
11710 &mut self,
11711 ranges: &[Range<Anchor>],
11712 color_fetcher: fn(&ThemeColors) -> Hsla,
11713 cx: &mut ViewContext<Self>,
11714 ) {
11715 self.background_highlights
11716 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11717 self.scrollbar_marker_state.dirty = true;
11718 cx.notify();
11719 }
11720
11721 pub fn clear_background_highlights<T: 'static>(
11722 &mut self,
11723 cx: &mut ViewContext<Self>,
11724 ) -> Option<BackgroundHighlight> {
11725 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11726 if !text_highlights.1.is_empty() {
11727 self.scrollbar_marker_state.dirty = true;
11728 cx.notify();
11729 }
11730 Some(text_highlights)
11731 }
11732
11733 pub fn highlight_gutter<T: 'static>(
11734 &mut self,
11735 ranges: &[Range<Anchor>],
11736 color_fetcher: fn(&AppContext) -> Hsla,
11737 cx: &mut ViewContext<Self>,
11738 ) {
11739 self.gutter_highlights
11740 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11741 cx.notify();
11742 }
11743
11744 pub fn clear_gutter_highlights<T: 'static>(
11745 &mut self,
11746 cx: &mut ViewContext<Self>,
11747 ) -> Option<GutterHighlight> {
11748 cx.notify();
11749 self.gutter_highlights.remove(&TypeId::of::<T>())
11750 }
11751
11752 #[cfg(feature = "test-support")]
11753 pub fn all_text_background_highlights(
11754 &mut self,
11755 cx: &mut ViewContext<Self>,
11756 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11757 let snapshot = self.snapshot(cx);
11758 let buffer = &snapshot.buffer_snapshot;
11759 let start = buffer.anchor_before(0);
11760 let end = buffer.anchor_after(buffer.len());
11761 let theme = cx.theme().colors();
11762 self.background_highlights_in_range(start..end, &snapshot, theme)
11763 }
11764
11765 #[cfg(feature = "test-support")]
11766 pub fn search_background_highlights(
11767 &mut self,
11768 cx: &mut ViewContext<Self>,
11769 ) -> Vec<Range<Point>> {
11770 let snapshot = self.buffer().read(cx).snapshot(cx);
11771
11772 let highlights = self
11773 .background_highlights
11774 .get(&TypeId::of::<items::BufferSearchHighlights>());
11775
11776 if let Some((_color, ranges)) = highlights {
11777 ranges
11778 .iter()
11779 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11780 .collect_vec()
11781 } else {
11782 vec![]
11783 }
11784 }
11785
11786 fn document_highlights_for_position<'a>(
11787 &'a self,
11788 position: Anchor,
11789 buffer: &'a MultiBufferSnapshot,
11790 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11791 let read_highlights = self
11792 .background_highlights
11793 .get(&TypeId::of::<DocumentHighlightRead>())
11794 .map(|h| &h.1);
11795 let write_highlights = self
11796 .background_highlights
11797 .get(&TypeId::of::<DocumentHighlightWrite>())
11798 .map(|h| &h.1);
11799 let left_position = position.bias_left(buffer);
11800 let right_position = position.bias_right(buffer);
11801 read_highlights
11802 .into_iter()
11803 .chain(write_highlights)
11804 .flat_map(move |ranges| {
11805 let start_ix = match ranges.binary_search_by(|probe| {
11806 let cmp = probe.end.cmp(&left_position, buffer);
11807 if cmp.is_ge() {
11808 Ordering::Greater
11809 } else {
11810 Ordering::Less
11811 }
11812 }) {
11813 Ok(i) | Err(i) => i,
11814 };
11815
11816 ranges[start_ix..]
11817 .iter()
11818 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11819 })
11820 }
11821
11822 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11823 self.background_highlights
11824 .get(&TypeId::of::<T>())
11825 .map_or(false, |(_, highlights)| !highlights.is_empty())
11826 }
11827
11828 pub fn background_highlights_in_range(
11829 &self,
11830 search_range: Range<Anchor>,
11831 display_snapshot: &DisplaySnapshot,
11832 theme: &ThemeColors,
11833 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11834 let mut results = Vec::new();
11835 for (color_fetcher, ranges) in self.background_highlights.values() {
11836 let color = color_fetcher(theme);
11837 let start_ix = match ranges.binary_search_by(|probe| {
11838 let cmp = probe
11839 .end
11840 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11841 if cmp.is_gt() {
11842 Ordering::Greater
11843 } else {
11844 Ordering::Less
11845 }
11846 }) {
11847 Ok(i) | Err(i) => i,
11848 };
11849 for range in &ranges[start_ix..] {
11850 if range
11851 .start
11852 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11853 .is_ge()
11854 {
11855 break;
11856 }
11857
11858 let start = range.start.to_display_point(display_snapshot);
11859 let end = range.end.to_display_point(display_snapshot);
11860 results.push((start..end, color))
11861 }
11862 }
11863 results
11864 }
11865
11866 pub fn background_highlight_row_ranges<T: 'static>(
11867 &self,
11868 search_range: Range<Anchor>,
11869 display_snapshot: &DisplaySnapshot,
11870 count: usize,
11871 ) -> Vec<RangeInclusive<DisplayPoint>> {
11872 let mut results = Vec::new();
11873 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11874 return vec![];
11875 };
11876
11877 let start_ix = match ranges.binary_search_by(|probe| {
11878 let cmp = probe
11879 .end
11880 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11881 if cmp.is_gt() {
11882 Ordering::Greater
11883 } else {
11884 Ordering::Less
11885 }
11886 }) {
11887 Ok(i) | Err(i) => i,
11888 };
11889 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11890 if let (Some(start_display), Some(end_display)) = (start, end) {
11891 results.push(
11892 start_display.to_display_point(display_snapshot)
11893 ..=end_display.to_display_point(display_snapshot),
11894 );
11895 }
11896 };
11897 let mut start_row: Option<Point> = None;
11898 let mut end_row: Option<Point> = None;
11899 if ranges.len() > count {
11900 return Vec::new();
11901 }
11902 for range in &ranges[start_ix..] {
11903 if range
11904 .start
11905 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11906 .is_ge()
11907 {
11908 break;
11909 }
11910 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11911 if let Some(current_row) = &end_row {
11912 if end.row == current_row.row {
11913 continue;
11914 }
11915 }
11916 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11917 if start_row.is_none() {
11918 assert_eq!(end_row, None);
11919 start_row = Some(start);
11920 end_row = Some(end);
11921 continue;
11922 }
11923 if let Some(current_end) = end_row.as_mut() {
11924 if start.row > current_end.row + 1 {
11925 push_region(start_row, end_row);
11926 start_row = Some(start);
11927 end_row = Some(end);
11928 } else {
11929 // Merge two hunks.
11930 *current_end = end;
11931 }
11932 } else {
11933 unreachable!();
11934 }
11935 }
11936 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11937 push_region(start_row, end_row);
11938 results
11939 }
11940
11941 pub fn gutter_highlights_in_range(
11942 &self,
11943 search_range: Range<Anchor>,
11944 display_snapshot: &DisplaySnapshot,
11945 cx: &AppContext,
11946 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11947 let mut results = Vec::new();
11948 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11949 let color = color_fetcher(cx);
11950 let start_ix = match ranges.binary_search_by(|probe| {
11951 let cmp = probe
11952 .end
11953 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11954 if cmp.is_gt() {
11955 Ordering::Greater
11956 } else {
11957 Ordering::Less
11958 }
11959 }) {
11960 Ok(i) | Err(i) => i,
11961 };
11962 for range in &ranges[start_ix..] {
11963 if range
11964 .start
11965 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11966 .is_ge()
11967 {
11968 break;
11969 }
11970
11971 let start = range.start.to_display_point(display_snapshot);
11972 let end = range.end.to_display_point(display_snapshot);
11973 results.push((start..end, color))
11974 }
11975 }
11976 results
11977 }
11978
11979 /// Get the text ranges corresponding to the redaction query
11980 pub fn redacted_ranges(
11981 &self,
11982 search_range: Range<Anchor>,
11983 display_snapshot: &DisplaySnapshot,
11984 cx: &WindowContext,
11985 ) -> Vec<Range<DisplayPoint>> {
11986 display_snapshot
11987 .buffer_snapshot
11988 .redacted_ranges(search_range, |file| {
11989 if let Some(file) = file {
11990 file.is_private()
11991 && EditorSettings::get(
11992 Some(SettingsLocation {
11993 worktree_id: file.worktree_id(cx),
11994 path: file.path().as_ref(),
11995 }),
11996 cx,
11997 )
11998 .redact_private_values
11999 } else {
12000 false
12001 }
12002 })
12003 .map(|range| {
12004 range.start.to_display_point(display_snapshot)
12005 ..range.end.to_display_point(display_snapshot)
12006 })
12007 .collect()
12008 }
12009
12010 pub fn highlight_text<T: 'static>(
12011 &mut self,
12012 ranges: Vec<Range<Anchor>>,
12013 style: HighlightStyle,
12014 cx: &mut ViewContext<Self>,
12015 ) {
12016 self.display_map.update(cx, |map, _| {
12017 map.highlight_text(TypeId::of::<T>(), ranges, style)
12018 });
12019 cx.notify();
12020 }
12021
12022 pub(crate) fn highlight_inlays<T: 'static>(
12023 &mut self,
12024 highlights: Vec<InlayHighlight>,
12025 style: HighlightStyle,
12026 cx: &mut ViewContext<Self>,
12027 ) {
12028 self.display_map.update(cx, |map, _| {
12029 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12030 });
12031 cx.notify();
12032 }
12033
12034 pub fn text_highlights<'a, T: 'static>(
12035 &'a self,
12036 cx: &'a AppContext,
12037 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12038 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12039 }
12040
12041 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12042 let cleared = self
12043 .display_map
12044 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12045 if cleared {
12046 cx.notify();
12047 }
12048 }
12049
12050 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12051 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12052 && self.focus_handle.is_focused(cx)
12053 }
12054
12055 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12056 self.show_cursor_when_unfocused = is_enabled;
12057 cx.notify();
12058 }
12059
12060 pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12061 self.project
12062 .as_ref()
12063 .map(|project| project.read(cx).lsp_store())
12064 }
12065
12066 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12067 cx.notify();
12068 }
12069
12070 fn on_buffer_event(
12071 &mut self,
12072 multibuffer: Model<MultiBuffer>,
12073 event: &multi_buffer::Event,
12074 cx: &mut ViewContext<Self>,
12075 ) {
12076 match event {
12077 multi_buffer::Event::Edited {
12078 singleton_buffer_edited,
12079 edited_buffer: buffer_edited,
12080 } => {
12081 self.scrollbar_marker_state.dirty = true;
12082 self.active_indent_guides_state.dirty = true;
12083 self.refresh_active_diagnostics(cx);
12084 self.refresh_code_actions(cx);
12085 if self.has_active_inline_completion() {
12086 self.update_visible_inline_completion(cx);
12087 }
12088 if let Some(buffer) = buffer_edited {
12089 let buffer_id = buffer.read(cx).remote_id();
12090 if !self.registered_buffers.contains_key(&buffer_id) {
12091 if let Some(lsp_store) = self.lsp_store(cx) {
12092 lsp_store.update(cx, |lsp_store, cx| {
12093 self.registered_buffers.insert(
12094 buffer_id,
12095 lsp_store.register_buffer_with_language_servers(&buffer, cx),
12096 );
12097 })
12098 }
12099 }
12100 }
12101 cx.emit(EditorEvent::BufferEdited);
12102 cx.emit(SearchEvent::MatchesInvalidated);
12103 if *singleton_buffer_edited {
12104 if let Some(project) = &self.project {
12105 let project = project.read(cx);
12106 #[allow(clippy::mutable_key_type)]
12107 let languages_affected = multibuffer
12108 .read(cx)
12109 .all_buffers()
12110 .into_iter()
12111 .filter_map(|buffer| {
12112 let buffer = buffer.read(cx);
12113 let language = buffer.language()?;
12114 if project.is_local()
12115 && project
12116 .language_servers_for_local_buffer(buffer, cx)
12117 .count()
12118 == 0
12119 {
12120 None
12121 } else {
12122 Some(language)
12123 }
12124 })
12125 .cloned()
12126 .collect::<HashSet<_>>();
12127 if !languages_affected.is_empty() {
12128 self.refresh_inlay_hints(
12129 InlayHintRefreshReason::BufferEdited(languages_affected),
12130 cx,
12131 );
12132 }
12133 }
12134 }
12135
12136 let Some(project) = &self.project else { return };
12137 let (telemetry, is_via_ssh) = {
12138 let project = project.read(cx);
12139 let telemetry = project.client().telemetry().clone();
12140 let is_via_ssh = project.is_via_ssh();
12141 (telemetry, is_via_ssh)
12142 };
12143 refresh_linked_ranges(self, cx);
12144 telemetry.log_edit_event("editor", is_via_ssh);
12145 }
12146 multi_buffer::Event::ExcerptsAdded {
12147 buffer,
12148 predecessor,
12149 excerpts,
12150 } => {
12151 self.tasks_update_task = Some(self.refresh_runnables(cx));
12152 let buffer_id = buffer.read(cx).remote_id();
12153 if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12154 if let Some(project) = &self.project {
12155 get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12156 }
12157 }
12158 cx.emit(EditorEvent::ExcerptsAdded {
12159 buffer: buffer.clone(),
12160 predecessor: *predecessor,
12161 excerpts: excerpts.clone(),
12162 });
12163 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12164 }
12165 multi_buffer::Event::ExcerptsRemoved { ids } => {
12166 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12167 let buffer = self.buffer.read(cx);
12168 self.registered_buffers
12169 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12170 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12171 }
12172 multi_buffer::Event::ExcerptsEdited { ids } => {
12173 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12174 }
12175 multi_buffer::Event::ExcerptsExpanded { ids } => {
12176 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12177 }
12178 multi_buffer::Event::Reparsed(buffer_id) => {
12179 self.tasks_update_task = Some(self.refresh_runnables(cx));
12180
12181 cx.emit(EditorEvent::Reparsed(*buffer_id));
12182 }
12183 multi_buffer::Event::LanguageChanged(buffer_id) => {
12184 linked_editing_ranges::refresh_linked_ranges(self, cx);
12185 cx.emit(EditorEvent::Reparsed(*buffer_id));
12186 cx.notify();
12187 }
12188 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12189 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12190 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12191 cx.emit(EditorEvent::TitleChanged)
12192 }
12193 // multi_buffer::Event::DiffBaseChanged => {
12194 // self.scrollbar_marker_state.dirty = true;
12195 // cx.emit(EditorEvent::DiffBaseChanged);
12196 // cx.notify();
12197 // }
12198 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12199 multi_buffer::Event::DiagnosticsUpdated => {
12200 self.refresh_active_diagnostics(cx);
12201 self.scrollbar_marker_state.dirty = true;
12202 cx.notify();
12203 }
12204 _ => {}
12205 };
12206 }
12207
12208 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12209 cx.notify();
12210 }
12211
12212 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12213 self.tasks_update_task = Some(self.refresh_runnables(cx));
12214 self.refresh_inline_completion(true, false, cx);
12215 self.refresh_inlay_hints(
12216 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12217 self.selections.newest_anchor().head(),
12218 &self.buffer.read(cx).snapshot(cx),
12219 cx,
12220 )),
12221 cx,
12222 );
12223
12224 let old_cursor_shape = self.cursor_shape;
12225
12226 {
12227 let editor_settings = EditorSettings::get_global(cx);
12228 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12229 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12230 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12231 }
12232
12233 if old_cursor_shape != self.cursor_shape {
12234 cx.emit(EditorEvent::CursorShapeChanged);
12235 }
12236
12237 let project_settings = ProjectSettings::get_global(cx);
12238 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12239
12240 if self.mode == EditorMode::Full {
12241 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12242 if self.git_blame_inline_enabled != inline_blame_enabled {
12243 self.toggle_git_blame_inline_internal(false, cx);
12244 }
12245 }
12246
12247 cx.notify();
12248 }
12249
12250 pub fn set_searchable(&mut self, searchable: bool) {
12251 self.searchable = searchable;
12252 }
12253
12254 pub fn searchable(&self) -> bool {
12255 self.searchable
12256 }
12257
12258 fn open_proposed_changes_editor(
12259 &mut self,
12260 _: &OpenProposedChangesEditor,
12261 cx: &mut ViewContext<Self>,
12262 ) {
12263 let Some(workspace) = self.workspace() else {
12264 cx.propagate();
12265 return;
12266 };
12267
12268 let selections = self.selections.all::<usize>(cx);
12269 let buffer = self.buffer.read(cx);
12270 let mut new_selections_by_buffer = HashMap::default();
12271 for selection in selections {
12272 for (buffer, range, _) in
12273 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12274 {
12275 let mut range = range.to_point(buffer.read(cx));
12276 range.start.column = 0;
12277 range.end.column = buffer.read(cx).line_len(range.end.row);
12278 new_selections_by_buffer
12279 .entry(buffer)
12280 .or_insert(Vec::new())
12281 .push(range)
12282 }
12283 }
12284
12285 let proposed_changes_buffers = new_selections_by_buffer
12286 .into_iter()
12287 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12288 .collect::<Vec<_>>();
12289 let proposed_changes_editor = cx.new_view(|cx| {
12290 ProposedChangesEditor::new(
12291 "Proposed changes",
12292 proposed_changes_buffers,
12293 self.project.clone(),
12294 cx,
12295 )
12296 });
12297
12298 cx.window_context().defer(move |cx| {
12299 workspace.update(cx, |workspace, cx| {
12300 workspace.active_pane().update(cx, |pane, cx| {
12301 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12302 });
12303 });
12304 });
12305 }
12306
12307 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12308 self.open_excerpts_common(None, true, cx)
12309 }
12310
12311 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12312 self.open_excerpts_common(None, false, cx)
12313 }
12314
12315 fn open_excerpts_common(
12316 &mut self,
12317 jump_data: Option<JumpData>,
12318 split: bool,
12319 cx: &mut ViewContext<Self>,
12320 ) {
12321 let Some(workspace) = self.workspace() else {
12322 cx.propagate();
12323 return;
12324 };
12325
12326 if self.buffer.read(cx).is_singleton() {
12327 cx.propagate();
12328 return;
12329 }
12330
12331 let mut new_selections_by_buffer = HashMap::default();
12332 match &jump_data {
12333 Some(jump_data) => {
12334 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12335 if let Some(buffer) = multi_buffer_snapshot
12336 .buffer_id_for_excerpt(jump_data.excerpt_id)
12337 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12338 {
12339 let buffer_snapshot = buffer.read(cx).snapshot();
12340 let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12341 language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12342 } else {
12343 buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12344 };
12345 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12346 new_selections_by_buffer.insert(
12347 buffer,
12348 (
12349 vec![jump_to_offset..jump_to_offset],
12350 Some(jump_data.line_offset_from_top),
12351 ),
12352 );
12353 }
12354 }
12355 None => {
12356 let selections = self.selections.all::<usize>(cx);
12357 let buffer = self.buffer.read(cx);
12358 for selection in selections {
12359 for (mut buffer_handle, mut range, _) in
12360 buffer.range_to_buffer_ranges(selection.range(), cx)
12361 {
12362 // When editing branch buffers, jump to the corresponding location
12363 // in their base buffer.
12364 let buffer = buffer_handle.read(cx);
12365 if let Some(base_buffer) = buffer.base_buffer() {
12366 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12367 buffer_handle = base_buffer;
12368 }
12369
12370 if selection.reversed {
12371 mem::swap(&mut range.start, &mut range.end);
12372 }
12373 new_selections_by_buffer
12374 .entry(buffer_handle)
12375 .or_insert((Vec::new(), None))
12376 .0
12377 .push(range)
12378 }
12379 }
12380 }
12381 }
12382
12383 if new_selections_by_buffer.is_empty() {
12384 return;
12385 }
12386
12387 // We defer the pane interaction because we ourselves are a workspace item
12388 // and activating a new item causes the pane to call a method on us reentrantly,
12389 // which panics if we're on the stack.
12390 cx.window_context().defer(move |cx| {
12391 workspace.update(cx, |workspace, cx| {
12392 let pane = if split {
12393 workspace.adjacent_pane(cx)
12394 } else {
12395 workspace.active_pane().clone()
12396 };
12397
12398 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12399 let editor = buffer
12400 .read(cx)
12401 .file()
12402 .is_none()
12403 .then(|| {
12404 // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
12405 // so `workspace.open_project_item` will never find them, always opening a new editor.
12406 // Instead, we try to activate the existing editor in the pane first.
12407 let (editor, pane_item_index) =
12408 pane.read(cx).items().enumerate().find_map(|(i, item)| {
12409 let editor = item.downcast::<Editor>()?;
12410 let singleton_buffer =
12411 editor.read(cx).buffer().read(cx).as_singleton()?;
12412 if singleton_buffer == buffer {
12413 Some((editor, i))
12414 } else {
12415 None
12416 }
12417 })?;
12418 pane.update(cx, |pane, cx| {
12419 pane.activate_item(pane_item_index, true, true, cx)
12420 });
12421 Some(editor)
12422 })
12423 .flatten()
12424 .unwrap_or_else(|| {
12425 workspace.open_project_item::<Self>(
12426 pane.clone(),
12427 buffer,
12428 true,
12429 true,
12430 cx,
12431 )
12432 });
12433
12434 editor.update(cx, |editor, cx| {
12435 let autoscroll = match scroll_offset {
12436 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12437 None => Autoscroll::newest(),
12438 };
12439 let nav_history = editor.nav_history.take();
12440 editor.change_selections(Some(autoscroll), cx, |s| {
12441 s.select_ranges(ranges);
12442 });
12443 editor.nav_history = nav_history;
12444 });
12445 }
12446 })
12447 });
12448 }
12449
12450 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12451 let snapshot = self.buffer.read(cx).read(cx);
12452 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12453 Some(
12454 ranges
12455 .iter()
12456 .map(move |range| {
12457 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12458 })
12459 .collect(),
12460 )
12461 }
12462
12463 fn selection_replacement_ranges(
12464 &self,
12465 range: Range<OffsetUtf16>,
12466 cx: &mut AppContext,
12467 ) -> Vec<Range<OffsetUtf16>> {
12468 let selections = self.selections.all::<OffsetUtf16>(cx);
12469 let newest_selection = selections
12470 .iter()
12471 .max_by_key(|selection| selection.id)
12472 .unwrap();
12473 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12474 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12475 let snapshot = self.buffer.read(cx).read(cx);
12476 selections
12477 .into_iter()
12478 .map(|mut selection| {
12479 selection.start.0 =
12480 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12481 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12482 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12483 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12484 })
12485 .collect()
12486 }
12487
12488 fn report_editor_event(
12489 &self,
12490 operation: &'static str,
12491 file_extension: Option<String>,
12492 cx: &AppContext,
12493 ) {
12494 if cfg!(any(test, feature = "test-support")) {
12495 return;
12496 }
12497
12498 let Some(project) = &self.project else { return };
12499
12500 // If None, we are in a file without an extension
12501 let file = self
12502 .buffer
12503 .read(cx)
12504 .as_singleton()
12505 .and_then(|b| b.read(cx).file());
12506 let file_extension = file_extension.or(file
12507 .as_ref()
12508 .and_then(|file| Path::new(file.file_name(cx)).extension())
12509 .and_then(|e| e.to_str())
12510 .map(|a| a.to_string()));
12511
12512 let vim_mode = cx
12513 .global::<SettingsStore>()
12514 .raw_user_settings()
12515 .get("vim_mode")
12516 == Some(&serde_json::Value::Bool(true));
12517
12518 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12519 == language::language_settings::InlineCompletionProvider::Copilot;
12520 let copilot_enabled_for_language = self
12521 .buffer
12522 .read(cx)
12523 .settings_at(0, cx)
12524 .show_inline_completions;
12525
12526 let project = project.read(cx);
12527 let telemetry = project.client().telemetry().clone();
12528 telemetry.report_editor_event(
12529 file_extension,
12530 vim_mode,
12531 operation,
12532 copilot_enabled,
12533 copilot_enabled_for_language,
12534 project.is_via_ssh(),
12535 )
12536 }
12537
12538 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12539 /// with each line being an array of {text, highlight} objects.
12540 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12541 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12542 return;
12543 };
12544
12545 #[derive(Serialize)]
12546 struct Chunk<'a> {
12547 text: String,
12548 highlight: Option<&'a str>,
12549 }
12550
12551 let snapshot = buffer.read(cx).snapshot();
12552 let range = self
12553 .selected_text_range(false, cx)
12554 .and_then(|selection| {
12555 if selection.range.is_empty() {
12556 None
12557 } else {
12558 Some(selection.range)
12559 }
12560 })
12561 .unwrap_or_else(|| 0..snapshot.len());
12562
12563 let chunks = snapshot.chunks(range, true);
12564 let mut lines = Vec::new();
12565 let mut line: VecDeque<Chunk> = VecDeque::new();
12566
12567 let Some(style) = self.style.as_ref() else {
12568 return;
12569 };
12570
12571 for chunk in chunks {
12572 let highlight = chunk
12573 .syntax_highlight_id
12574 .and_then(|id| id.name(&style.syntax));
12575 let mut chunk_lines = chunk.text.split('\n').peekable();
12576 while let Some(text) = chunk_lines.next() {
12577 let mut merged_with_last_token = false;
12578 if let Some(last_token) = line.back_mut() {
12579 if last_token.highlight == highlight {
12580 last_token.text.push_str(text);
12581 merged_with_last_token = true;
12582 }
12583 }
12584
12585 if !merged_with_last_token {
12586 line.push_back(Chunk {
12587 text: text.into(),
12588 highlight,
12589 });
12590 }
12591
12592 if chunk_lines.peek().is_some() {
12593 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12594 line.pop_front();
12595 }
12596 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12597 line.pop_back();
12598 }
12599
12600 lines.push(mem::take(&mut line));
12601 }
12602 }
12603 }
12604
12605 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12606 return;
12607 };
12608 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12609 }
12610
12611 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12612 self.request_autoscroll(Autoscroll::newest(), cx);
12613 let position = self.selections.newest_display(cx).start;
12614 mouse_context_menu::deploy_context_menu(self, None, position, cx);
12615 }
12616
12617 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12618 &self.inlay_hint_cache
12619 }
12620
12621 pub fn replay_insert_event(
12622 &mut self,
12623 text: &str,
12624 relative_utf16_range: Option<Range<isize>>,
12625 cx: &mut ViewContext<Self>,
12626 ) {
12627 if !self.input_enabled {
12628 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12629 return;
12630 }
12631 if let Some(relative_utf16_range) = relative_utf16_range {
12632 let selections = self.selections.all::<OffsetUtf16>(cx);
12633 self.change_selections(None, cx, |s| {
12634 let new_ranges = selections.into_iter().map(|range| {
12635 let start = OffsetUtf16(
12636 range
12637 .head()
12638 .0
12639 .saturating_add_signed(relative_utf16_range.start),
12640 );
12641 let end = OffsetUtf16(
12642 range
12643 .head()
12644 .0
12645 .saturating_add_signed(relative_utf16_range.end),
12646 );
12647 start..end
12648 });
12649 s.select_ranges(new_ranges);
12650 });
12651 }
12652
12653 self.handle_input(text, cx);
12654 }
12655
12656 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12657 let Some(provider) = self.semantics_provider.as_ref() else {
12658 return false;
12659 };
12660
12661 let mut supports = false;
12662 self.buffer().read(cx).for_each_buffer(|buffer| {
12663 supports |= provider.supports_inlay_hints(buffer, cx);
12664 });
12665 supports
12666 }
12667
12668 pub fn focus(&self, cx: &mut WindowContext) {
12669 cx.focus(&self.focus_handle)
12670 }
12671
12672 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12673 self.focus_handle.is_focused(cx)
12674 }
12675
12676 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12677 cx.emit(EditorEvent::Focused);
12678
12679 if let Some(descendant) = self
12680 .last_focused_descendant
12681 .take()
12682 .and_then(|descendant| descendant.upgrade())
12683 {
12684 cx.focus(&descendant);
12685 } else {
12686 if let Some(blame) = self.blame.as_ref() {
12687 blame.update(cx, GitBlame::focus)
12688 }
12689
12690 self.blink_manager.update(cx, BlinkManager::enable);
12691 self.show_cursor_names(cx);
12692 self.buffer.update(cx, |buffer, cx| {
12693 buffer.finalize_last_transaction(cx);
12694 if self.leader_peer_id.is_none() {
12695 buffer.set_active_selections(
12696 &self.selections.disjoint_anchors(),
12697 self.selections.line_mode,
12698 self.cursor_shape,
12699 cx,
12700 );
12701 }
12702 });
12703 }
12704 }
12705
12706 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12707 cx.emit(EditorEvent::FocusedIn)
12708 }
12709
12710 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12711 if event.blurred != self.focus_handle {
12712 self.last_focused_descendant = Some(event.blurred);
12713 }
12714 }
12715
12716 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12717 self.blink_manager.update(cx, BlinkManager::disable);
12718 self.buffer
12719 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12720
12721 if let Some(blame) = self.blame.as_ref() {
12722 blame.update(cx, GitBlame::blur)
12723 }
12724 if !self.hover_state.focused(cx) {
12725 hide_hover(self, cx);
12726 }
12727
12728 self.hide_context_menu(cx);
12729 cx.emit(EditorEvent::Blurred);
12730 cx.notify();
12731 }
12732
12733 pub fn register_action<A: Action>(
12734 &mut self,
12735 listener: impl Fn(&A, &mut WindowContext) + 'static,
12736 ) -> Subscription {
12737 let id = self.next_editor_action_id.post_inc();
12738 let listener = Arc::new(listener);
12739 self.editor_actions.borrow_mut().insert(
12740 id,
12741 Box::new(move |cx| {
12742 let cx = cx.window_context();
12743 let listener = listener.clone();
12744 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12745 let action = action.downcast_ref().unwrap();
12746 if phase == DispatchPhase::Bubble {
12747 listener(action, cx)
12748 }
12749 })
12750 }),
12751 );
12752
12753 let editor_actions = self.editor_actions.clone();
12754 Subscription::new(move || {
12755 editor_actions.borrow_mut().remove(&id);
12756 })
12757 }
12758
12759 pub fn file_header_size(&self) -> u32 {
12760 FILE_HEADER_HEIGHT
12761 }
12762
12763 pub fn revert(
12764 &mut self,
12765 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12766 cx: &mut ViewContext<Self>,
12767 ) {
12768 self.buffer().update(cx, |multi_buffer, cx| {
12769 for (buffer_id, changes) in revert_changes {
12770 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12771 buffer.update(cx, |buffer, cx| {
12772 buffer.edit(
12773 changes.into_iter().map(|(range, text)| {
12774 (range, text.to_string().map(Arc::<str>::from))
12775 }),
12776 None,
12777 cx,
12778 );
12779 });
12780 }
12781 }
12782 });
12783 self.change_selections(None, cx, |selections| selections.refresh());
12784 }
12785
12786 pub fn to_pixel_point(
12787 &mut self,
12788 source: multi_buffer::Anchor,
12789 editor_snapshot: &EditorSnapshot,
12790 cx: &mut ViewContext<Self>,
12791 ) -> Option<gpui::Point<Pixels>> {
12792 let source_point = source.to_display_point(editor_snapshot);
12793 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12794 }
12795
12796 pub fn display_to_pixel_point(
12797 &self,
12798 source: DisplayPoint,
12799 editor_snapshot: &EditorSnapshot,
12800 cx: &WindowContext,
12801 ) -> Option<gpui::Point<Pixels>> {
12802 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12803 let text_layout_details = self.text_layout_details(cx);
12804 let scroll_top = text_layout_details
12805 .scroll_anchor
12806 .scroll_position(editor_snapshot)
12807 .y;
12808
12809 if source.row().as_f32() < scroll_top.floor() {
12810 return None;
12811 }
12812 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12813 let source_y = line_height * (source.row().as_f32() - scroll_top);
12814 Some(gpui::Point::new(source_x, source_y))
12815 }
12816
12817 pub fn has_active_completions_menu(&self) -> bool {
12818 self.context_menu.borrow().as_ref().map_or(false, |menu| {
12819 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
12820 })
12821 }
12822
12823 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12824 self.addons
12825 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12826 }
12827
12828 pub fn unregister_addon<T: Addon>(&mut self) {
12829 self.addons.remove(&std::any::TypeId::of::<T>());
12830 }
12831
12832 pub fn addon<T: Addon>(&self) -> Option<&T> {
12833 let type_id = std::any::TypeId::of::<T>();
12834 self.addons
12835 .get(&type_id)
12836 .and_then(|item| item.to_any().downcast_ref::<T>())
12837 }
12838
12839 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
12840 let text_layout_details = self.text_layout_details(cx);
12841 let style = &text_layout_details.editor_style;
12842 let font_id = cx.text_system().resolve_font(&style.text.font());
12843 let font_size = style.text.font_size.to_pixels(cx.rem_size());
12844 let line_height = style.text.line_height_in_pixels(cx.rem_size());
12845
12846 let em_width = cx
12847 .text_system()
12848 .typographic_bounds(font_id, font_size, 'm')
12849 .unwrap()
12850 .size
12851 .width;
12852
12853 gpui::Point::new(em_width, line_height)
12854 }
12855}
12856
12857fn get_unstaged_changes_for_buffers(
12858 project: &Model<Project>,
12859 buffers: impl IntoIterator<Item = Model<Buffer>>,
12860 cx: &mut ViewContext<Editor>,
12861) {
12862 let mut tasks = Vec::new();
12863 project.update(cx, |project, cx| {
12864 for buffer in buffers {
12865 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
12866 }
12867 });
12868 cx.spawn(|this, mut cx| async move {
12869 let change_sets = futures::future::join_all(tasks).await;
12870 this.update(&mut cx, |this, cx| {
12871 for change_set in change_sets {
12872 if let Some(change_set) = change_set.log_err() {
12873 this.diff_map.add_change_set(change_set, cx);
12874 }
12875 }
12876 })
12877 .ok();
12878 })
12879 .detach();
12880}
12881
12882fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
12883 let tab_size = tab_size.get() as usize;
12884 let mut width = offset;
12885
12886 for ch in text.chars() {
12887 width += if ch == '\t' {
12888 tab_size - (width % tab_size)
12889 } else {
12890 1
12891 };
12892 }
12893
12894 width - offset
12895}
12896
12897#[cfg(test)]
12898mod tests {
12899 use super::*;
12900
12901 #[test]
12902 fn test_string_size_with_expanded_tabs() {
12903 let nz = |val| NonZeroU32::new(val).unwrap();
12904 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
12905 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
12906 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
12907 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
12908 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
12909 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
12910 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
12911 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
12912 }
12913}
12914
12915/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
12916struct WordBreakingTokenizer<'a> {
12917 input: &'a str,
12918}
12919
12920impl<'a> WordBreakingTokenizer<'a> {
12921 fn new(input: &'a str) -> Self {
12922 Self { input }
12923 }
12924}
12925
12926fn is_char_ideographic(ch: char) -> bool {
12927 use unicode_script::Script::*;
12928 use unicode_script::UnicodeScript;
12929 matches!(ch.script(), Han | Tangut | Yi)
12930}
12931
12932fn is_grapheme_ideographic(text: &str) -> bool {
12933 text.chars().any(is_char_ideographic)
12934}
12935
12936fn is_grapheme_whitespace(text: &str) -> bool {
12937 text.chars().any(|x| x.is_whitespace())
12938}
12939
12940fn should_stay_with_preceding_ideograph(text: &str) -> bool {
12941 text.chars().next().map_or(false, |ch| {
12942 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
12943 })
12944}
12945
12946#[derive(PartialEq, Eq, Debug, Clone, Copy)]
12947struct WordBreakToken<'a> {
12948 token: &'a str,
12949 grapheme_len: usize,
12950 is_whitespace: bool,
12951}
12952
12953impl<'a> Iterator for WordBreakingTokenizer<'a> {
12954 /// Yields a span, the count of graphemes in the token, and whether it was
12955 /// whitespace. Note that it also breaks at word boundaries.
12956 type Item = WordBreakToken<'a>;
12957
12958 fn next(&mut self) -> Option<Self::Item> {
12959 use unicode_segmentation::UnicodeSegmentation;
12960 if self.input.is_empty() {
12961 return None;
12962 }
12963
12964 let mut iter = self.input.graphemes(true).peekable();
12965 let mut offset = 0;
12966 let mut graphemes = 0;
12967 if let Some(first_grapheme) = iter.next() {
12968 let is_whitespace = is_grapheme_whitespace(first_grapheme);
12969 offset += first_grapheme.len();
12970 graphemes += 1;
12971 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
12972 if let Some(grapheme) = iter.peek().copied() {
12973 if should_stay_with_preceding_ideograph(grapheme) {
12974 offset += grapheme.len();
12975 graphemes += 1;
12976 }
12977 }
12978 } else {
12979 let mut words = self.input[offset..].split_word_bound_indices().peekable();
12980 let mut next_word_bound = words.peek().copied();
12981 if next_word_bound.map_or(false, |(i, _)| i == 0) {
12982 next_word_bound = words.next();
12983 }
12984 while let Some(grapheme) = iter.peek().copied() {
12985 if next_word_bound.map_or(false, |(i, _)| i == offset) {
12986 break;
12987 };
12988 if is_grapheme_whitespace(grapheme) != is_whitespace {
12989 break;
12990 };
12991 offset += grapheme.len();
12992 graphemes += 1;
12993 iter.next();
12994 }
12995 }
12996 let token = &self.input[..offset];
12997 self.input = &self.input[offset..];
12998 if is_whitespace {
12999 Some(WordBreakToken {
13000 token: " ",
13001 grapheme_len: 1,
13002 is_whitespace: true,
13003 })
13004 } else {
13005 Some(WordBreakToken {
13006 token,
13007 grapheme_len: graphemes,
13008 is_whitespace: false,
13009 })
13010 }
13011 } else {
13012 None
13013 }
13014 }
13015}
13016
13017#[test]
13018fn test_word_breaking_tokenizer() {
13019 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13020 ("", &[]),
13021 (" ", &[(" ", 1, true)]),
13022 ("Ʒ", &[("Ʒ", 1, false)]),
13023 ("Ǽ", &[("Ǽ", 1, false)]),
13024 ("⋑", &[("⋑", 1, false)]),
13025 ("⋑⋑", &[("⋑⋑", 2, false)]),
13026 (
13027 "原理,进而",
13028 &[
13029 ("原", 1, false),
13030 ("理,", 2, false),
13031 ("进", 1, false),
13032 ("而", 1, false),
13033 ],
13034 ),
13035 (
13036 "hello world",
13037 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13038 ),
13039 (
13040 "hello, world",
13041 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13042 ),
13043 (
13044 " hello world",
13045 &[
13046 (" ", 1, true),
13047 ("hello", 5, false),
13048 (" ", 1, true),
13049 ("world", 5, false),
13050 ],
13051 ),
13052 (
13053 "这是什么 \n 钢笔",
13054 &[
13055 ("这", 1, false),
13056 ("是", 1, false),
13057 ("什", 1, false),
13058 ("么", 1, false),
13059 (" ", 1, true),
13060 ("钢", 1, false),
13061 ("笔", 1, false),
13062 ],
13063 ),
13064 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13065 ];
13066
13067 for (input, result) in tests {
13068 assert_eq!(
13069 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13070 result
13071 .iter()
13072 .copied()
13073 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13074 token,
13075 grapheme_len,
13076 is_whitespace,
13077 })
13078 .collect::<Vec<_>>()
13079 );
13080 }
13081}
13082
13083fn wrap_with_prefix(
13084 line_prefix: String,
13085 unwrapped_text: String,
13086 wrap_column: usize,
13087 tab_size: NonZeroU32,
13088) -> String {
13089 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13090 let mut wrapped_text = String::new();
13091 let mut current_line = line_prefix.clone();
13092
13093 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13094 let mut current_line_len = line_prefix_len;
13095 for WordBreakToken {
13096 token,
13097 grapheme_len,
13098 is_whitespace,
13099 } in tokenizer
13100 {
13101 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13102 wrapped_text.push_str(current_line.trim_end());
13103 wrapped_text.push('\n');
13104 current_line.truncate(line_prefix.len());
13105 current_line_len = line_prefix_len;
13106 if !is_whitespace {
13107 current_line.push_str(token);
13108 current_line_len += grapheme_len;
13109 }
13110 } else if !is_whitespace {
13111 current_line.push_str(token);
13112 current_line_len += grapheme_len;
13113 } else if current_line_len != line_prefix_len {
13114 current_line.push(' ');
13115 current_line_len += 1;
13116 }
13117 }
13118
13119 if !current_line.is_empty() {
13120 wrapped_text.push_str(¤t_line);
13121 }
13122 wrapped_text
13123}
13124
13125#[test]
13126fn test_wrap_with_prefix() {
13127 assert_eq!(
13128 wrap_with_prefix(
13129 "# ".to_string(),
13130 "abcdefg".to_string(),
13131 4,
13132 NonZeroU32::new(4).unwrap()
13133 ),
13134 "# abcdefg"
13135 );
13136 assert_eq!(
13137 wrap_with_prefix(
13138 "".to_string(),
13139 "\thello world".to_string(),
13140 8,
13141 NonZeroU32::new(4).unwrap()
13142 ),
13143 "hello\nworld"
13144 );
13145 assert_eq!(
13146 wrap_with_prefix(
13147 "// ".to_string(),
13148 "xx \nyy zz aa bb cc".to_string(),
13149 12,
13150 NonZeroU32::new(4).unwrap()
13151 ),
13152 "// xx yy zz\n// aa bb cc"
13153 );
13154 assert_eq!(
13155 wrap_with_prefix(
13156 String::new(),
13157 "这是什么 \n 钢笔".to_string(),
13158 3,
13159 NonZeroU32::new(4).unwrap()
13160 ),
13161 "这是什\n么 钢\n笔"
13162 );
13163}
13164
13165fn hunks_for_selections(
13166 snapshot: &EditorSnapshot,
13167 selections: &[Selection<Point>],
13168) -> Vec<MultiBufferDiffHunk> {
13169 hunks_for_ranges(
13170 selections.iter().map(|selection| selection.range()),
13171 snapshot,
13172 )
13173}
13174
13175pub fn hunks_for_ranges(
13176 ranges: impl Iterator<Item = Range<Point>>,
13177 snapshot: &EditorSnapshot,
13178) -> Vec<MultiBufferDiffHunk> {
13179 let mut hunks = Vec::new();
13180 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13181 HashMap::default();
13182 for query_range in ranges {
13183 let query_rows =
13184 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13185 for hunk in snapshot.diff_map.diff_hunks_in_range(
13186 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13187 &snapshot.buffer_snapshot,
13188 ) {
13189 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13190 // when the caret is just above or just below the deleted hunk.
13191 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13192 let related_to_selection = if allow_adjacent {
13193 hunk.row_range.overlaps(&query_rows)
13194 || hunk.row_range.start == query_rows.end
13195 || hunk.row_range.end == query_rows.start
13196 } else {
13197 hunk.row_range.overlaps(&query_rows)
13198 };
13199 if related_to_selection {
13200 if !processed_buffer_rows
13201 .entry(hunk.buffer_id)
13202 .or_default()
13203 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13204 {
13205 continue;
13206 }
13207 hunks.push(hunk);
13208 }
13209 }
13210 }
13211
13212 hunks
13213}
13214
13215pub trait CollaborationHub {
13216 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13217 fn user_participant_indices<'a>(
13218 &self,
13219 cx: &'a AppContext,
13220 ) -> &'a HashMap<u64, ParticipantIndex>;
13221 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13222}
13223
13224impl CollaborationHub for Model<Project> {
13225 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13226 self.read(cx).collaborators()
13227 }
13228
13229 fn user_participant_indices<'a>(
13230 &self,
13231 cx: &'a AppContext,
13232 ) -> &'a HashMap<u64, ParticipantIndex> {
13233 self.read(cx).user_store().read(cx).participant_indices()
13234 }
13235
13236 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13237 let this = self.read(cx);
13238 let user_ids = this.collaborators().values().map(|c| c.user_id);
13239 this.user_store().read_with(cx, |user_store, cx| {
13240 user_store.participant_names(user_ids, cx)
13241 })
13242 }
13243}
13244
13245pub trait SemanticsProvider {
13246 fn hover(
13247 &self,
13248 buffer: &Model<Buffer>,
13249 position: text::Anchor,
13250 cx: &mut AppContext,
13251 ) -> Option<Task<Vec<project::Hover>>>;
13252
13253 fn inlay_hints(
13254 &self,
13255 buffer_handle: Model<Buffer>,
13256 range: Range<text::Anchor>,
13257 cx: &mut AppContext,
13258 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13259
13260 fn resolve_inlay_hint(
13261 &self,
13262 hint: InlayHint,
13263 buffer_handle: Model<Buffer>,
13264 server_id: LanguageServerId,
13265 cx: &mut AppContext,
13266 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13267
13268 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13269
13270 fn document_highlights(
13271 &self,
13272 buffer: &Model<Buffer>,
13273 position: text::Anchor,
13274 cx: &mut AppContext,
13275 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13276
13277 fn definitions(
13278 &self,
13279 buffer: &Model<Buffer>,
13280 position: text::Anchor,
13281 kind: GotoDefinitionKind,
13282 cx: &mut AppContext,
13283 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13284
13285 fn range_for_rename(
13286 &self,
13287 buffer: &Model<Buffer>,
13288 position: text::Anchor,
13289 cx: &mut AppContext,
13290 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13291
13292 fn perform_rename(
13293 &self,
13294 buffer: &Model<Buffer>,
13295 position: text::Anchor,
13296 new_name: String,
13297 cx: &mut AppContext,
13298 ) -> Option<Task<Result<ProjectTransaction>>>;
13299}
13300
13301pub trait CompletionProvider {
13302 fn completions(
13303 &self,
13304 buffer: &Model<Buffer>,
13305 buffer_position: text::Anchor,
13306 trigger: CompletionContext,
13307 cx: &mut ViewContext<Editor>,
13308 ) -> Task<Result<Vec<Completion>>>;
13309
13310 fn resolve_completions(
13311 &self,
13312 buffer: Model<Buffer>,
13313 completion_indices: Vec<usize>,
13314 completions: Rc<RefCell<Box<[Completion]>>>,
13315 cx: &mut ViewContext<Editor>,
13316 ) -> Task<Result<bool>>;
13317
13318 fn apply_additional_edits_for_completion(
13319 &self,
13320 buffer: Model<Buffer>,
13321 completion: Completion,
13322 push_to_history: bool,
13323 cx: &mut ViewContext<Editor>,
13324 ) -> Task<Result<Option<language::Transaction>>>;
13325
13326 fn is_completion_trigger(
13327 &self,
13328 buffer: &Model<Buffer>,
13329 position: language::Anchor,
13330 text: &str,
13331 trigger_in_words: bool,
13332 cx: &mut ViewContext<Editor>,
13333 ) -> bool;
13334
13335 fn sort_completions(&self) -> bool {
13336 true
13337 }
13338}
13339
13340pub trait CodeActionProvider {
13341 fn code_actions(
13342 &self,
13343 buffer: &Model<Buffer>,
13344 range: Range<text::Anchor>,
13345 cx: &mut WindowContext,
13346 ) -> Task<Result<Vec<CodeAction>>>;
13347
13348 fn apply_code_action(
13349 &self,
13350 buffer_handle: Model<Buffer>,
13351 action: CodeAction,
13352 excerpt_id: ExcerptId,
13353 push_to_history: bool,
13354 cx: &mut WindowContext,
13355 ) -> Task<Result<ProjectTransaction>>;
13356}
13357
13358impl CodeActionProvider for Model<Project> {
13359 fn code_actions(
13360 &self,
13361 buffer: &Model<Buffer>,
13362 range: Range<text::Anchor>,
13363 cx: &mut WindowContext,
13364 ) -> Task<Result<Vec<CodeAction>>> {
13365 self.update(cx, |project, cx| {
13366 project.code_actions(buffer, range, None, cx)
13367 })
13368 }
13369
13370 fn apply_code_action(
13371 &self,
13372 buffer_handle: Model<Buffer>,
13373 action: CodeAction,
13374 _excerpt_id: ExcerptId,
13375 push_to_history: bool,
13376 cx: &mut WindowContext,
13377 ) -> Task<Result<ProjectTransaction>> {
13378 self.update(cx, |project, cx| {
13379 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13380 })
13381 }
13382}
13383
13384fn snippet_completions(
13385 project: &Project,
13386 buffer: &Model<Buffer>,
13387 buffer_position: text::Anchor,
13388 cx: &mut AppContext,
13389) -> Task<Result<Vec<Completion>>> {
13390 let language = buffer.read(cx).language_at(buffer_position);
13391 let language_name = language.as_ref().map(|language| language.lsp_id());
13392 let snippet_store = project.snippets().read(cx);
13393 let snippets = snippet_store.snippets_for(language_name, cx);
13394
13395 if snippets.is_empty() {
13396 return Task::ready(Ok(vec![]));
13397 }
13398 let snapshot = buffer.read(cx).text_snapshot();
13399 let chars: String = snapshot
13400 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13401 .collect();
13402
13403 let scope = language.map(|language| language.default_scope());
13404 let executor = cx.background_executor().clone();
13405
13406 cx.background_executor().spawn(async move {
13407 let classifier = CharClassifier::new(scope).for_completion(true);
13408 let mut last_word = chars
13409 .chars()
13410 .take_while(|c| classifier.is_word(*c))
13411 .collect::<String>();
13412 last_word = last_word.chars().rev().collect();
13413
13414 if last_word.is_empty() {
13415 return Ok(vec![]);
13416 }
13417
13418 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13419 let to_lsp = |point: &text::Anchor| {
13420 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13421 point_to_lsp(end)
13422 };
13423 let lsp_end = to_lsp(&buffer_position);
13424
13425 let candidates = snippets
13426 .iter()
13427 .enumerate()
13428 .flat_map(|(ix, snippet)| {
13429 snippet
13430 .prefix
13431 .iter()
13432 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13433 })
13434 .collect::<Vec<StringMatchCandidate>>();
13435
13436 let mut matches = fuzzy::match_strings(
13437 &candidates,
13438 &last_word,
13439 last_word.chars().any(|c| c.is_uppercase()),
13440 100,
13441 &Default::default(),
13442 executor,
13443 )
13444 .await;
13445
13446 // Remove all candidates where the query's start does not match the start of any word in the candidate
13447 if let Some(query_start) = last_word.chars().next() {
13448 matches.retain(|string_match| {
13449 split_words(&string_match.string).any(|word| {
13450 // Check that the first codepoint of the word as lowercase matches the first
13451 // codepoint of the query as lowercase
13452 word.chars()
13453 .flat_map(|codepoint| codepoint.to_lowercase())
13454 .zip(query_start.to_lowercase())
13455 .all(|(word_cp, query_cp)| word_cp == query_cp)
13456 })
13457 });
13458 }
13459
13460 let matched_strings = matches
13461 .into_iter()
13462 .map(|m| m.string)
13463 .collect::<HashSet<_>>();
13464
13465 let result: Vec<Completion> = snippets
13466 .into_iter()
13467 .filter_map(|snippet| {
13468 let matching_prefix = snippet
13469 .prefix
13470 .iter()
13471 .find(|prefix| matched_strings.contains(*prefix))?;
13472 let start = as_offset - last_word.len();
13473 let start = snapshot.anchor_before(start);
13474 let range = start..buffer_position;
13475 let lsp_start = to_lsp(&start);
13476 let lsp_range = lsp::Range {
13477 start: lsp_start,
13478 end: lsp_end,
13479 };
13480 Some(Completion {
13481 old_range: range,
13482 new_text: snippet.body.clone(),
13483 label: CodeLabel {
13484 text: matching_prefix.clone(),
13485 runs: vec![],
13486 filter_range: 0..matching_prefix.len(),
13487 },
13488 server_id: LanguageServerId(usize::MAX),
13489 documentation: snippet.description.clone().map(Documentation::SingleLine),
13490 lsp_completion: lsp::CompletionItem {
13491 label: snippet.prefix.first().unwrap().clone(),
13492 kind: Some(CompletionItemKind::SNIPPET),
13493 label_details: snippet.description.as_ref().map(|description| {
13494 lsp::CompletionItemLabelDetails {
13495 detail: Some(description.clone()),
13496 description: None,
13497 }
13498 }),
13499 insert_text_format: Some(InsertTextFormat::SNIPPET),
13500 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13501 lsp::InsertReplaceEdit {
13502 new_text: snippet.body.clone(),
13503 insert: lsp_range,
13504 replace: lsp_range,
13505 },
13506 )),
13507 filter_text: Some(snippet.body.clone()),
13508 sort_text: Some(char::MAX.to_string()),
13509 ..Default::default()
13510 },
13511 confirm: None,
13512 })
13513 })
13514 .collect();
13515
13516 Ok(result)
13517 })
13518}
13519
13520impl CompletionProvider for Model<Project> {
13521 fn completions(
13522 &self,
13523 buffer: &Model<Buffer>,
13524 buffer_position: text::Anchor,
13525 options: CompletionContext,
13526 cx: &mut ViewContext<Editor>,
13527 ) -> Task<Result<Vec<Completion>>> {
13528 self.update(cx, |project, cx| {
13529 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13530 let project_completions = project.completions(buffer, buffer_position, options, cx);
13531 cx.background_executor().spawn(async move {
13532 let mut completions = project_completions.await?;
13533 let snippets_completions = snippets.await?;
13534 completions.extend(snippets_completions);
13535 Ok(completions)
13536 })
13537 })
13538 }
13539
13540 fn resolve_completions(
13541 &self,
13542 buffer: Model<Buffer>,
13543 completion_indices: Vec<usize>,
13544 completions: Rc<RefCell<Box<[Completion]>>>,
13545 cx: &mut ViewContext<Editor>,
13546 ) -> Task<Result<bool>> {
13547 self.update(cx, |project, cx| {
13548 project.resolve_completions(buffer, completion_indices, completions, cx)
13549 })
13550 }
13551
13552 fn apply_additional_edits_for_completion(
13553 &self,
13554 buffer: Model<Buffer>,
13555 completion: Completion,
13556 push_to_history: bool,
13557 cx: &mut ViewContext<Editor>,
13558 ) -> Task<Result<Option<language::Transaction>>> {
13559 self.update(cx, |project, cx| {
13560 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13561 })
13562 }
13563
13564 fn is_completion_trigger(
13565 &self,
13566 buffer: &Model<Buffer>,
13567 position: language::Anchor,
13568 text: &str,
13569 trigger_in_words: bool,
13570 cx: &mut ViewContext<Editor>,
13571 ) -> bool {
13572 let mut chars = text.chars();
13573 let char = if let Some(char) = chars.next() {
13574 char
13575 } else {
13576 return false;
13577 };
13578 if chars.next().is_some() {
13579 return false;
13580 }
13581
13582 let buffer = buffer.read(cx);
13583 let snapshot = buffer.snapshot();
13584 if !snapshot.settings_at(position, cx).show_completions_on_input {
13585 return false;
13586 }
13587 let classifier = snapshot.char_classifier_at(position).for_completion(true);
13588 if trigger_in_words && classifier.is_word(char) {
13589 return true;
13590 }
13591
13592 buffer.completion_triggers().contains(text)
13593 }
13594}
13595
13596impl SemanticsProvider for Model<Project> {
13597 fn hover(
13598 &self,
13599 buffer: &Model<Buffer>,
13600 position: text::Anchor,
13601 cx: &mut AppContext,
13602 ) -> Option<Task<Vec<project::Hover>>> {
13603 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13604 }
13605
13606 fn document_highlights(
13607 &self,
13608 buffer: &Model<Buffer>,
13609 position: text::Anchor,
13610 cx: &mut AppContext,
13611 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13612 Some(self.update(cx, |project, cx| {
13613 project.document_highlights(buffer, position, cx)
13614 }))
13615 }
13616
13617 fn definitions(
13618 &self,
13619 buffer: &Model<Buffer>,
13620 position: text::Anchor,
13621 kind: GotoDefinitionKind,
13622 cx: &mut AppContext,
13623 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13624 Some(self.update(cx, |project, cx| match kind {
13625 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13626 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13627 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13628 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13629 }))
13630 }
13631
13632 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13633 // TODO: make this work for remote projects
13634 self.read(cx)
13635 .language_servers_for_local_buffer(buffer.read(cx), cx)
13636 .any(
13637 |(_, server)| match server.capabilities().inlay_hint_provider {
13638 Some(lsp::OneOf::Left(enabled)) => enabled,
13639 Some(lsp::OneOf::Right(_)) => true,
13640 None => false,
13641 },
13642 )
13643 }
13644
13645 fn inlay_hints(
13646 &self,
13647 buffer_handle: Model<Buffer>,
13648 range: Range<text::Anchor>,
13649 cx: &mut AppContext,
13650 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13651 Some(self.update(cx, |project, cx| {
13652 project.inlay_hints(buffer_handle, range, cx)
13653 }))
13654 }
13655
13656 fn resolve_inlay_hint(
13657 &self,
13658 hint: InlayHint,
13659 buffer_handle: Model<Buffer>,
13660 server_id: LanguageServerId,
13661 cx: &mut AppContext,
13662 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13663 Some(self.update(cx, |project, cx| {
13664 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13665 }))
13666 }
13667
13668 fn range_for_rename(
13669 &self,
13670 buffer: &Model<Buffer>,
13671 position: text::Anchor,
13672 cx: &mut AppContext,
13673 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13674 Some(self.update(cx, |project, cx| {
13675 project.prepare_rename(buffer.clone(), position, cx)
13676 }))
13677 }
13678
13679 fn perform_rename(
13680 &self,
13681 buffer: &Model<Buffer>,
13682 position: text::Anchor,
13683 new_name: String,
13684 cx: &mut AppContext,
13685 ) -> Option<Task<Result<ProjectTransaction>>> {
13686 Some(self.update(cx, |project, cx| {
13687 project.perform_rename(buffer.clone(), position, new_name, cx)
13688 }))
13689 }
13690}
13691
13692fn inlay_hint_settings(
13693 location: Anchor,
13694 snapshot: &MultiBufferSnapshot,
13695 cx: &mut ViewContext<'_, Editor>,
13696) -> InlayHintSettings {
13697 let file = snapshot.file_at(location);
13698 let language = snapshot.language_at(location).map(|l| l.name());
13699 language_settings(language, file, cx).inlay_hints
13700}
13701
13702fn consume_contiguous_rows(
13703 contiguous_row_selections: &mut Vec<Selection<Point>>,
13704 selection: &Selection<Point>,
13705 display_map: &DisplaySnapshot,
13706 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13707) -> (MultiBufferRow, MultiBufferRow) {
13708 contiguous_row_selections.push(selection.clone());
13709 let start_row = MultiBufferRow(selection.start.row);
13710 let mut end_row = ending_row(selection, display_map);
13711
13712 while let Some(next_selection) = selections.peek() {
13713 if next_selection.start.row <= end_row.0 {
13714 end_row = ending_row(next_selection, display_map);
13715 contiguous_row_selections.push(selections.next().unwrap().clone());
13716 } else {
13717 break;
13718 }
13719 }
13720 (start_row, end_row)
13721}
13722
13723fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13724 if next_selection.end.column > 0 || next_selection.is_empty() {
13725 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13726 } else {
13727 MultiBufferRow(next_selection.end.row)
13728 }
13729}
13730
13731impl EditorSnapshot {
13732 pub fn remote_selections_in_range<'a>(
13733 &'a self,
13734 range: &'a Range<Anchor>,
13735 collaboration_hub: &dyn CollaborationHub,
13736 cx: &'a AppContext,
13737 ) -> impl 'a + Iterator<Item = RemoteSelection> {
13738 let participant_names = collaboration_hub.user_names(cx);
13739 let participant_indices = collaboration_hub.user_participant_indices(cx);
13740 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13741 let collaborators_by_replica_id = collaborators_by_peer_id
13742 .iter()
13743 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13744 .collect::<HashMap<_, _>>();
13745 self.buffer_snapshot
13746 .selections_in_range(range, false)
13747 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13748 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13749 let participant_index = participant_indices.get(&collaborator.user_id).copied();
13750 let user_name = participant_names.get(&collaborator.user_id).cloned();
13751 Some(RemoteSelection {
13752 replica_id,
13753 selection,
13754 cursor_shape,
13755 line_mode,
13756 participant_index,
13757 peer_id: collaborator.peer_id,
13758 user_name,
13759 })
13760 })
13761 }
13762
13763 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13764 self.display_snapshot.buffer_snapshot.language_at(position)
13765 }
13766
13767 pub fn is_focused(&self) -> bool {
13768 self.is_focused
13769 }
13770
13771 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13772 self.placeholder_text.as_ref()
13773 }
13774
13775 pub fn scroll_position(&self) -> gpui::Point<f32> {
13776 self.scroll_anchor.scroll_position(&self.display_snapshot)
13777 }
13778
13779 fn gutter_dimensions(
13780 &self,
13781 font_id: FontId,
13782 font_size: Pixels,
13783 em_width: Pixels,
13784 em_advance: Pixels,
13785 max_line_number_width: Pixels,
13786 cx: &AppContext,
13787 ) -> GutterDimensions {
13788 if !self.show_gutter {
13789 return GutterDimensions::default();
13790 }
13791 let descent = cx.text_system().descent(font_id, font_size);
13792
13793 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13794 matches!(
13795 ProjectSettings::get_global(cx).git.git_gutter,
13796 Some(GitGutterSetting::TrackedFiles)
13797 )
13798 });
13799 let gutter_settings = EditorSettings::get_global(cx).gutter;
13800 let show_line_numbers = self
13801 .show_line_numbers
13802 .unwrap_or(gutter_settings.line_numbers);
13803 let line_gutter_width = if show_line_numbers {
13804 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13805 let min_width_for_number_on_gutter = em_advance * 4.0;
13806 max_line_number_width.max(min_width_for_number_on_gutter)
13807 } else {
13808 0.0.into()
13809 };
13810
13811 let show_code_actions = self
13812 .show_code_actions
13813 .unwrap_or(gutter_settings.code_actions);
13814
13815 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13816
13817 let git_blame_entries_width =
13818 self.git_blame_gutter_max_author_length
13819 .map(|max_author_length| {
13820 // Length of the author name, but also space for the commit hash,
13821 // the spacing and the timestamp.
13822 let max_char_count = max_author_length
13823 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13824 + 7 // length of commit sha
13825 + 14 // length of max relative timestamp ("60 minutes ago")
13826 + 4; // gaps and margins
13827
13828 em_advance * max_char_count
13829 });
13830
13831 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13832 left_padding += if show_code_actions || show_runnables {
13833 em_width * 3.0
13834 } else if show_git_gutter && show_line_numbers {
13835 em_width * 2.0
13836 } else if show_git_gutter || show_line_numbers {
13837 em_width
13838 } else {
13839 px(0.)
13840 };
13841
13842 let right_padding = if gutter_settings.folds && show_line_numbers {
13843 em_width * 4.0
13844 } else if gutter_settings.folds {
13845 em_width * 3.0
13846 } else if show_line_numbers {
13847 em_width
13848 } else {
13849 px(0.)
13850 };
13851
13852 GutterDimensions {
13853 left_padding,
13854 right_padding,
13855 width: line_gutter_width + left_padding + right_padding,
13856 margin: -descent,
13857 git_blame_entries_width,
13858 }
13859 }
13860
13861 pub fn render_crease_toggle(
13862 &self,
13863 buffer_row: MultiBufferRow,
13864 row_contains_cursor: bool,
13865 editor: View<Editor>,
13866 cx: &mut WindowContext,
13867 ) -> Option<AnyElement> {
13868 let folded = self.is_line_folded(buffer_row);
13869 let mut is_foldable = false;
13870
13871 if let Some(crease) = self
13872 .crease_snapshot
13873 .query_row(buffer_row, &self.buffer_snapshot)
13874 {
13875 is_foldable = true;
13876 match crease {
13877 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
13878 if let Some(render_toggle) = render_toggle {
13879 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13880 if folded {
13881 editor.update(cx, |editor, cx| {
13882 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13883 });
13884 } else {
13885 editor.update(cx, |editor, cx| {
13886 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13887 });
13888 }
13889 });
13890 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
13891 }
13892 }
13893 }
13894 }
13895
13896 is_foldable |= self.starts_indent(buffer_row);
13897
13898 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
13899 Some(
13900 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
13901 .toggle_state(folded)
13902 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13903 if folded {
13904 this.unfold_at(&UnfoldAt { buffer_row }, cx);
13905 } else {
13906 this.fold_at(&FoldAt { buffer_row }, cx);
13907 }
13908 }))
13909 .into_any_element(),
13910 )
13911 } else {
13912 None
13913 }
13914 }
13915
13916 pub fn render_crease_trailer(
13917 &self,
13918 buffer_row: MultiBufferRow,
13919 cx: &mut WindowContext,
13920 ) -> Option<AnyElement> {
13921 let folded = self.is_line_folded(buffer_row);
13922 if let Crease::Inline { render_trailer, .. } = self
13923 .crease_snapshot
13924 .query_row(buffer_row, &self.buffer_snapshot)?
13925 {
13926 let render_trailer = render_trailer.as_ref()?;
13927 Some(render_trailer(buffer_row, folded, cx))
13928 } else {
13929 None
13930 }
13931 }
13932}
13933
13934impl Deref for EditorSnapshot {
13935 type Target = DisplaySnapshot;
13936
13937 fn deref(&self) -> &Self::Target {
13938 &self.display_snapshot
13939 }
13940}
13941
13942#[derive(Clone, Debug, PartialEq, Eq)]
13943pub enum EditorEvent {
13944 InputIgnored {
13945 text: Arc<str>,
13946 },
13947 InputHandled {
13948 utf16_range_to_replace: Option<Range<isize>>,
13949 text: Arc<str>,
13950 },
13951 ExcerptsAdded {
13952 buffer: Model<Buffer>,
13953 predecessor: ExcerptId,
13954 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13955 },
13956 ExcerptsRemoved {
13957 ids: Vec<ExcerptId>,
13958 },
13959 BufferFoldToggled {
13960 ids: Vec<ExcerptId>,
13961 folded: bool,
13962 },
13963 ExcerptsEdited {
13964 ids: Vec<ExcerptId>,
13965 },
13966 ExcerptsExpanded {
13967 ids: Vec<ExcerptId>,
13968 },
13969 BufferEdited,
13970 Edited {
13971 transaction_id: clock::Lamport,
13972 },
13973 Reparsed(BufferId),
13974 Focused,
13975 FocusedIn,
13976 Blurred,
13977 DirtyChanged,
13978 Saved,
13979 TitleChanged,
13980 DiffBaseChanged,
13981 SelectionsChanged {
13982 local: bool,
13983 },
13984 ScrollPositionChanged {
13985 local: bool,
13986 autoscroll: bool,
13987 },
13988 Closed,
13989 TransactionUndone {
13990 transaction_id: clock::Lamport,
13991 },
13992 TransactionBegun {
13993 transaction_id: clock::Lamport,
13994 },
13995 Reloaded,
13996 CursorShapeChanged,
13997}
13998
13999impl EventEmitter<EditorEvent> for Editor {}
14000
14001impl FocusableView for Editor {
14002 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14003 self.focus_handle.clone()
14004 }
14005}
14006
14007impl Render for Editor {
14008 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14009 let settings = ThemeSettings::get_global(cx);
14010
14011 let mut text_style = match self.mode {
14012 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14013 color: cx.theme().colors().editor_foreground,
14014 font_family: settings.ui_font.family.clone(),
14015 font_features: settings.ui_font.features.clone(),
14016 font_fallbacks: settings.ui_font.fallbacks.clone(),
14017 font_size: rems(0.875).into(),
14018 font_weight: settings.ui_font.weight,
14019 line_height: relative(settings.buffer_line_height.value()),
14020 ..Default::default()
14021 },
14022 EditorMode::Full => TextStyle {
14023 color: cx.theme().colors().editor_foreground,
14024 font_family: settings.buffer_font.family.clone(),
14025 font_features: settings.buffer_font.features.clone(),
14026 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14027 font_size: settings.buffer_font_size(cx).into(),
14028 font_weight: settings.buffer_font.weight,
14029 line_height: relative(settings.buffer_line_height.value()),
14030 ..Default::default()
14031 },
14032 };
14033 if let Some(text_style_refinement) = &self.text_style_refinement {
14034 text_style.refine(text_style_refinement)
14035 }
14036
14037 let background = match self.mode {
14038 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14039 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14040 EditorMode::Full => cx.theme().colors().editor_background,
14041 };
14042
14043 EditorElement::new(
14044 cx.view(),
14045 EditorStyle {
14046 background,
14047 local_player: cx.theme().players().local(),
14048 text: text_style,
14049 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14050 syntax: cx.theme().syntax().clone(),
14051 status: cx.theme().status().clone(),
14052 inlay_hints_style: make_inlay_hints_style(cx),
14053 inline_completion_styles: make_suggestion_styles(cx),
14054 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14055 },
14056 )
14057 }
14058}
14059
14060impl ViewInputHandler for Editor {
14061 fn text_for_range(
14062 &mut self,
14063 range_utf16: Range<usize>,
14064 adjusted_range: &mut Option<Range<usize>>,
14065 cx: &mut ViewContext<Self>,
14066 ) -> Option<String> {
14067 let snapshot = self.buffer.read(cx).read(cx);
14068 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14069 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14070 if (start.0..end.0) != range_utf16 {
14071 adjusted_range.replace(start.0..end.0);
14072 }
14073 Some(snapshot.text_for_range(start..end).collect())
14074 }
14075
14076 fn selected_text_range(
14077 &mut self,
14078 ignore_disabled_input: bool,
14079 cx: &mut ViewContext<Self>,
14080 ) -> Option<UTF16Selection> {
14081 // Prevent the IME menu from appearing when holding down an alphabetic key
14082 // while input is disabled.
14083 if !ignore_disabled_input && !self.input_enabled {
14084 return None;
14085 }
14086
14087 let selection = self.selections.newest::<OffsetUtf16>(cx);
14088 let range = selection.range();
14089
14090 Some(UTF16Selection {
14091 range: range.start.0..range.end.0,
14092 reversed: selection.reversed,
14093 })
14094 }
14095
14096 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14097 let snapshot = self.buffer.read(cx).read(cx);
14098 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14099 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14100 }
14101
14102 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14103 self.clear_highlights::<InputComposition>(cx);
14104 self.ime_transaction.take();
14105 }
14106
14107 fn replace_text_in_range(
14108 &mut self,
14109 range_utf16: Option<Range<usize>>,
14110 text: &str,
14111 cx: &mut ViewContext<Self>,
14112 ) {
14113 if !self.input_enabled {
14114 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14115 return;
14116 }
14117
14118 self.transact(cx, |this, cx| {
14119 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14120 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14121 Some(this.selection_replacement_ranges(range_utf16, cx))
14122 } else {
14123 this.marked_text_ranges(cx)
14124 };
14125
14126 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14127 let newest_selection_id = this.selections.newest_anchor().id;
14128 this.selections
14129 .all::<OffsetUtf16>(cx)
14130 .iter()
14131 .zip(ranges_to_replace.iter())
14132 .find_map(|(selection, range)| {
14133 if selection.id == newest_selection_id {
14134 Some(
14135 (range.start.0 as isize - selection.head().0 as isize)
14136 ..(range.end.0 as isize - selection.head().0 as isize),
14137 )
14138 } else {
14139 None
14140 }
14141 })
14142 });
14143
14144 cx.emit(EditorEvent::InputHandled {
14145 utf16_range_to_replace: range_to_replace,
14146 text: text.into(),
14147 });
14148
14149 if let Some(new_selected_ranges) = new_selected_ranges {
14150 this.change_selections(None, cx, |selections| {
14151 selections.select_ranges(new_selected_ranges)
14152 });
14153 this.backspace(&Default::default(), cx);
14154 }
14155
14156 this.handle_input(text, cx);
14157 });
14158
14159 if let Some(transaction) = self.ime_transaction {
14160 self.buffer.update(cx, |buffer, cx| {
14161 buffer.group_until_transaction(transaction, cx);
14162 });
14163 }
14164
14165 self.unmark_text(cx);
14166 }
14167
14168 fn replace_and_mark_text_in_range(
14169 &mut self,
14170 range_utf16: Option<Range<usize>>,
14171 text: &str,
14172 new_selected_range_utf16: Option<Range<usize>>,
14173 cx: &mut ViewContext<Self>,
14174 ) {
14175 if !self.input_enabled {
14176 return;
14177 }
14178
14179 let transaction = self.transact(cx, |this, cx| {
14180 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14181 let snapshot = this.buffer.read(cx).read(cx);
14182 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14183 for marked_range in &mut marked_ranges {
14184 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14185 marked_range.start.0 += relative_range_utf16.start;
14186 marked_range.start =
14187 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14188 marked_range.end =
14189 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14190 }
14191 }
14192 Some(marked_ranges)
14193 } else if let Some(range_utf16) = range_utf16 {
14194 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14195 Some(this.selection_replacement_ranges(range_utf16, cx))
14196 } else {
14197 None
14198 };
14199
14200 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14201 let newest_selection_id = this.selections.newest_anchor().id;
14202 this.selections
14203 .all::<OffsetUtf16>(cx)
14204 .iter()
14205 .zip(ranges_to_replace.iter())
14206 .find_map(|(selection, range)| {
14207 if selection.id == newest_selection_id {
14208 Some(
14209 (range.start.0 as isize - selection.head().0 as isize)
14210 ..(range.end.0 as isize - selection.head().0 as isize),
14211 )
14212 } else {
14213 None
14214 }
14215 })
14216 });
14217
14218 cx.emit(EditorEvent::InputHandled {
14219 utf16_range_to_replace: range_to_replace,
14220 text: text.into(),
14221 });
14222
14223 if let Some(ranges) = ranges_to_replace {
14224 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14225 }
14226
14227 let marked_ranges = {
14228 let snapshot = this.buffer.read(cx).read(cx);
14229 this.selections
14230 .disjoint_anchors()
14231 .iter()
14232 .map(|selection| {
14233 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14234 })
14235 .collect::<Vec<_>>()
14236 };
14237
14238 if text.is_empty() {
14239 this.unmark_text(cx);
14240 } else {
14241 this.highlight_text::<InputComposition>(
14242 marked_ranges.clone(),
14243 HighlightStyle {
14244 underline: Some(UnderlineStyle {
14245 thickness: px(1.),
14246 color: None,
14247 wavy: false,
14248 }),
14249 ..Default::default()
14250 },
14251 cx,
14252 );
14253 }
14254
14255 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14256 let use_autoclose = this.use_autoclose;
14257 let use_auto_surround = this.use_auto_surround;
14258 this.set_use_autoclose(false);
14259 this.set_use_auto_surround(false);
14260 this.handle_input(text, cx);
14261 this.set_use_autoclose(use_autoclose);
14262 this.set_use_auto_surround(use_auto_surround);
14263
14264 if let Some(new_selected_range) = new_selected_range_utf16 {
14265 let snapshot = this.buffer.read(cx).read(cx);
14266 let new_selected_ranges = marked_ranges
14267 .into_iter()
14268 .map(|marked_range| {
14269 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14270 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14271 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14272 snapshot.clip_offset_utf16(new_start, Bias::Left)
14273 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14274 })
14275 .collect::<Vec<_>>();
14276
14277 drop(snapshot);
14278 this.change_selections(None, cx, |selections| {
14279 selections.select_ranges(new_selected_ranges)
14280 });
14281 }
14282 });
14283
14284 self.ime_transaction = self.ime_transaction.or(transaction);
14285 if let Some(transaction) = self.ime_transaction {
14286 self.buffer.update(cx, |buffer, cx| {
14287 buffer.group_until_transaction(transaction, cx);
14288 });
14289 }
14290
14291 if self.text_highlights::<InputComposition>(cx).is_none() {
14292 self.ime_transaction.take();
14293 }
14294 }
14295
14296 fn bounds_for_range(
14297 &mut self,
14298 range_utf16: Range<usize>,
14299 element_bounds: gpui::Bounds<Pixels>,
14300 cx: &mut ViewContext<Self>,
14301 ) -> Option<gpui::Bounds<Pixels>> {
14302 let text_layout_details = self.text_layout_details(cx);
14303 let gpui::Point {
14304 x: em_width,
14305 y: line_height,
14306 } = self.character_size(cx);
14307
14308 let snapshot = self.snapshot(cx);
14309 let scroll_position = snapshot.scroll_position();
14310 let scroll_left = scroll_position.x * em_width;
14311
14312 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14313 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14314 + self.gutter_dimensions.width
14315 + self.gutter_dimensions.margin;
14316 let y = line_height * (start.row().as_f32() - scroll_position.y);
14317
14318 Some(Bounds {
14319 origin: element_bounds.origin + point(x, y),
14320 size: size(em_width, line_height),
14321 })
14322 }
14323}
14324
14325trait SelectionExt {
14326 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14327 fn spanned_rows(
14328 &self,
14329 include_end_if_at_line_start: bool,
14330 map: &DisplaySnapshot,
14331 ) -> Range<MultiBufferRow>;
14332}
14333
14334impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14335 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14336 let start = self
14337 .start
14338 .to_point(&map.buffer_snapshot)
14339 .to_display_point(map);
14340 let end = self
14341 .end
14342 .to_point(&map.buffer_snapshot)
14343 .to_display_point(map);
14344 if self.reversed {
14345 end..start
14346 } else {
14347 start..end
14348 }
14349 }
14350
14351 fn spanned_rows(
14352 &self,
14353 include_end_if_at_line_start: bool,
14354 map: &DisplaySnapshot,
14355 ) -> Range<MultiBufferRow> {
14356 let start = self.start.to_point(&map.buffer_snapshot);
14357 let mut end = self.end.to_point(&map.buffer_snapshot);
14358 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14359 end.row -= 1;
14360 }
14361
14362 let buffer_start = map.prev_line_boundary(start).0;
14363 let buffer_end = map.next_line_boundary(end).0;
14364 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14365 }
14366}
14367
14368impl<T: InvalidationRegion> InvalidationStack<T> {
14369 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14370 where
14371 S: Clone + ToOffset,
14372 {
14373 while let Some(region) = self.last() {
14374 let all_selections_inside_invalidation_ranges =
14375 if selections.len() == region.ranges().len() {
14376 selections
14377 .iter()
14378 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14379 .all(|(selection, invalidation_range)| {
14380 let head = selection.head().to_offset(buffer);
14381 invalidation_range.start <= head && invalidation_range.end >= head
14382 })
14383 } else {
14384 false
14385 };
14386
14387 if all_selections_inside_invalidation_ranges {
14388 break;
14389 } else {
14390 self.pop();
14391 }
14392 }
14393 }
14394}
14395
14396impl<T> Default for InvalidationStack<T> {
14397 fn default() -> Self {
14398 Self(Default::default())
14399 }
14400}
14401
14402impl<T> Deref for InvalidationStack<T> {
14403 type Target = Vec<T>;
14404
14405 fn deref(&self) -> &Self::Target {
14406 &self.0
14407 }
14408}
14409
14410impl<T> DerefMut for InvalidationStack<T> {
14411 fn deref_mut(&mut self) -> &mut Self::Target {
14412 &mut self.0
14413 }
14414}
14415
14416impl InvalidationRegion for SnippetState {
14417 fn ranges(&self) -> &[Range<Anchor>] {
14418 &self.ranges[self.active_index]
14419 }
14420}
14421
14422pub fn diagnostic_block_renderer(
14423 diagnostic: Diagnostic,
14424 max_message_rows: Option<u8>,
14425 allow_closing: bool,
14426 _is_valid: bool,
14427) -> RenderBlock {
14428 let (text_without_backticks, code_ranges) =
14429 highlight_diagnostic_message(&diagnostic, max_message_rows);
14430
14431 Arc::new(move |cx: &mut BlockContext| {
14432 let group_id: SharedString = cx.block_id.to_string().into();
14433
14434 let mut text_style = cx.text_style().clone();
14435 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14436 let theme_settings = ThemeSettings::get_global(cx);
14437 text_style.font_family = theme_settings.buffer_font.family.clone();
14438 text_style.font_style = theme_settings.buffer_font.style;
14439 text_style.font_features = theme_settings.buffer_font.features.clone();
14440 text_style.font_weight = theme_settings.buffer_font.weight;
14441
14442 let multi_line_diagnostic = diagnostic.message.contains('\n');
14443
14444 let buttons = |diagnostic: &Diagnostic| {
14445 if multi_line_diagnostic {
14446 v_flex()
14447 } else {
14448 h_flex()
14449 }
14450 .when(allow_closing, |div| {
14451 div.children(diagnostic.is_primary.then(|| {
14452 IconButton::new("close-block", IconName::XCircle)
14453 .icon_color(Color::Muted)
14454 .size(ButtonSize::Compact)
14455 .style(ButtonStyle::Transparent)
14456 .visible_on_hover(group_id.clone())
14457 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14458 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14459 }))
14460 })
14461 .child(
14462 IconButton::new("copy-block", IconName::Copy)
14463 .icon_color(Color::Muted)
14464 .size(ButtonSize::Compact)
14465 .style(ButtonStyle::Transparent)
14466 .visible_on_hover(group_id.clone())
14467 .on_click({
14468 let message = diagnostic.message.clone();
14469 move |_click, cx| {
14470 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14471 }
14472 })
14473 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14474 )
14475 };
14476
14477 let icon_size = buttons(&diagnostic)
14478 .into_any_element()
14479 .layout_as_root(AvailableSpace::min_size(), cx);
14480
14481 h_flex()
14482 .id(cx.block_id)
14483 .group(group_id.clone())
14484 .relative()
14485 .size_full()
14486 .block_mouse_down()
14487 .pl(cx.gutter_dimensions.width)
14488 .w(cx.max_width - cx.gutter_dimensions.full_width())
14489 .child(
14490 div()
14491 .flex()
14492 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14493 .flex_shrink(),
14494 )
14495 .child(buttons(&diagnostic))
14496 .child(div().flex().flex_shrink_0().child(
14497 StyledText::new(text_without_backticks.clone()).with_highlights(
14498 &text_style,
14499 code_ranges.iter().map(|range| {
14500 (
14501 range.clone(),
14502 HighlightStyle {
14503 font_weight: Some(FontWeight::BOLD),
14504 ..Default::default()
14505 },
14506 )
14507 }),
14508 ),
14509 ))
14510 .into_any_element()
14511 })
14512}
14513
14514pub fn highlight_diagnostic_message(
14515 diagnostic: &Diagnostic,
14516 mut max_message_rows: Option<u8>,
14517) -> (SharedString, Vec<Range<usize>>) {
14518 let mut text_without_backticks = String::new();
14519 let mut code_ranges = Vec::new();
14520
14521 if let Some(source) = &diagnostic.source {
14522 text_without_backticks.push_str(source);
14523 code_ranges.push(0..source.len());
14524 text_without_backticks.push_str(": ");
14525 }
14526
14527 let mut prev_offset = 0;
14528 let mut in_code_block = false;
14529 let has_row_limit = max_message_rows.is_some();
14530 let mut newline_indices = diagnostic
14531 .message
14532 .match_indices('\n')
14533 .filter(|_| has_row_limit)
14534 .map(|(ix, _)| ix)
14535 .fuse()
14536 .peekable();
14537
14538 for (quote_ix, _) in diagnostic
14539 .message
14540 .match_indices('`')
14541 .chain([(diagnostic.message.len(), "")])
14542 {
14543 let mut first_newline_ix = None;
14544 let mut last_newline_ix = None;
14545 while let Some(newline_ix) = newline_indices.peek() {
14546 if *newline_ix < quote_ix {
14547 if first_newline_ix.is_none() {
14548 first_newline_ix = Some(*newline_ix);
14549 }
14550 last_newline_ix = Some(*newline_ix);
14551
14552 if let Some(rows_left) = &mut max_message_rows {
14553 if *rows_left == 0 {
14554 break;
14555 } else {
14556 *rows_left -= 1;
14557 }
14558 }
14559 let _ = newline_indices.next();
14560 } else {
14561 break;
14562 }
14563 }
14564 let prev_len = text_without_backticks.len();
14565 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14566 text_without_backticks.push_str(new_text);
14567 if in_code_block {
14568 code_ranges.push(prev_len..text_without_backticks.len());
14569 }
14570 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14571 in_code_block = !in_code_block;
14572 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14573 text_without_backticks.push_str("...");
14574 break;
14575 }
14576 }
14577
14578 (text_without_backticks.into(), code_ranges)
14579}
14580
14581fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14582 match severity {
14583 DiagnosticSeverity::ERROR => colors.error,
14584 DiagnosticSeverity::WARNING => colors.warning,
14585 DiagnosticSeverity::INFORMATION => colors.info,
14586 DiagnosticSeverity::HINT => colors.info,
14587 _ => colors.ignored,
14588 }
14589}
14590
14591pub fn styled_runs_for_code_label<'a>(
14592 label: &'a CodeLabel,
14593 syntax_theme: &'a theme::SyntaxTheme,
14594) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14595 let fade_out = HighlightStyle {
14596 fade_out: Some(0.35),
14597 ..Default::default()
14598 };
14599
14600 let mut prev_end = label.filter_range.end;
14601 label
14602 .runs
14603 .iter()
14604 .enumerate()
14605 .flat_map(move |(ix, (range, highlight_id))| {
14606 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14607 style
14608 } else {
14609 return Default::default();
14610 };
14611 let mut muted_style = style;
14612 muted_style.highlight(fade_out);
14613
14614 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14615 if range.start >= label.filter_range.end {
14616 if range.start > prev_end {
14617 runs.push((prev_end..range.start, fade_out));
14618 }
14619 runs.push((range.clone(), muted_style));
14620 } else if range.end <= label.filter_range.end {
14621 runs.push((range.clone(), style));
14622 } else {
14623 runs.push((range.start..label.filter_range.end, style));
14624 runs.push((label.filter_range.end..range.end, muted_style));
14625 }
14626 prev_end = cmp::max(prev_end, range.end);
14627
14628 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14629 runs.push((prev_end..label.text.len(), fade_out));
14630 }
14631
14632 runs
14633 })
14634}
14635
14636pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14637 let mut prev_index = 0;
14638 let mut prev_codepoint: Option<char> = None;
14639 text.char_indices()
14640 .chain([(text.len(), '\0')])
14641 .filter_map(move |(index, codepoint)| {
14642 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14643 let is_boundary = index == text.len()
14644 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14645 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14646 if is_boundary {
14647 let chunk = &text[prev_index..index];
14648 prev_index = index;
14649 Some(chunk)
14650 } else {
14651 None
14652 }
14653 })
14654}
14655
14656pub trait RangeToAnchorExt: Sized {
14657 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14658
14659 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14660 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14661 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14662 }
14663}
14664
14665impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14666 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14667 let start_offset = self.start.to_offset(snapshot);
14668 let end_offset = self.end.to_offset(snapshot);
14669 if start_offset == end_offset {
14670 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14671 } else {
14672 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14673 }
14674 }
14675}
14676
14677pub trait RowExt {
14678 fn as_f32(&self) -> f32;
14679
14680 fn next_row(&self) -> Self;
14681
14682 fn previous_row(&self) -> Self;
14683
14684 fn minus(&self, other: Self) -> u32;
14685}
14686
14687impl RowExt for DisplayRow {
14688 fn as_f32(&self) -> f32 {
14689 self.0 as f32
14690 }
14691
14692 fn next_row(&self) -> Self {
14693 Self(self.0 + 1)
14694 }
14695
14696 fn previous_row(&self) -> Self {
14697 Self(self.0.saturating_sub(1))
14698 }
14699
14700 fn minus(&self, other: Self) -> u32 {
14701 self.0 - other.0
14702 }
14703}
14704
14705impl RowExt for MultiBufferRow {
14706 fn as_f32(&self) -> f32 {
14707 self.0 as f32
14708 }
14709
14710 fn next_row(&self) -> Self {
14711 Self(self.0 + 1)
14712 }
14713
14714 fn previous_row(&self) -> Self {
14715 Self(self.0.saturating_sub(1))
14716 }
14717
14718 fn minus(&self, other: Self) -> u32 {
14719 self.0 - other.0
14720 }
14721}
14722
14723trait RowRangeExt {
14724 type Row;
14725
14726 fn len(&self) -> usize;
14727
14728 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14729}
14730
14731impl RowRangeExt for Range<MultiBufferRow> {
14732 type Row = MultiBufferRow;
14733
14734 fn len(&self) -> usize {
14735 (self.end.0 - self.start.0) as usize
14736 }
14737
14738 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14739 (self.start.0..self.end.0).map(MultiBufferRow)
14740 }
14741}
14742
14743impl RowRangeExt for Range<DisplayRow> {
14744 type Row = DisplayRow;
14745
14746 fn len(&self) -> usize {
14747 (self.end.0 - self.start.0) as usize
14748 }
14749
14750 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14751 (self.start.0..self.end.0).map(DisplayRow)
14752 }
14753}
14754
14755fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14756 if hunk.diff_base_byte_range.is_empty() {
14757 DiffHunkStatus::Added
14758 } else if hunk.row_range.is_empty() {
14759 DiffHunkStatus::Removed
14760 } else {
14761 DiffHunkStatus::Modified
14762 }
14763}
14764
14765/// If select range has more than one line, we
14766/// just point the cursor to range.start.
14767fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14768 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14769 range
14770 } else {
14771 range.start..range.start
14772 }
14773}
14774
14775pub struct KillRing(ClipboardItem);
14776impl Global for KillRing {}
14777
14778const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);