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(), Default::default(), 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 let had_active_inline_completion = this.has_active_inline_completion();
2847 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
2848 s.select(new_selections)
2849 });
2850
2851 if !bracket_inserted {
2852 if let Some(on_type_format_task) =
2853 this.trigger_on_type_formatting(text.to_string(), cx)
2854 {
2855 on_type_format_task.detach_and_log_err(cx);
2856 }
2857 }
2858
2859 let editor_settings = EditorSettings::get_global(cx);
2860 if bracket_inserted
2861 && (editor_settings.auto_signature_help
2862 || editor_settings.show_signature_help_after_edits)
2863 {
2864 this.show_signature_help(&ShowSignatureHelp, cx);
2865 }
2866
2867 let trigger_in_words = !had_active_inline_completion;
2868 this.trigger_completion_on_input(&text, trigger_in_words, cx);
2869 linked_editing_ranges::refresh_linked_ranges(this, cx);
2870 this.refresh_inline_completion(true, false, cx);
2871 });
2872 }
2873
2874 fn find_possible_emoji_shortcode_at_position(
2875 snapshot: &MultiBufferSnapshot,
2876 position: Point,
2877 ) -> Option<String> {
2878 let mut chars = Vec::new();
2879 let mut found_colon = false;
2880 for char in snapshot.reversed_chars_at(position).take(100) {
2881 // Found a possible emoji shortcode in the middle of the buffer
2882 if found_colon {
2883 if char.is_whitespace() {
2884 chars.reverse();
2885 return Some(chars.iter().collect());
2886 }
2887 // If the previous character is not a whitespace, we are in the middle of a word
2888 // and we only want to complete the shortcode if the word is made up of other emojis
2889 let mut containing_word = String::new();
2890 for ch in snapshot
2891 .reversed_chars_at(position)
2892 .skip(chars.len() + 1)
2893 .take(100)
2894 {
2895 if ch.is_whitespace() {
2896 break;
2897 }
2898 containing_word.push(ch);
2899 }
2900 let containing_word = containing_word.chars().rev().collect::<String>();
2901 if util::word_consists_of_emojis(containing_word.as_str()) {
2902 chars.reverse();
2903 return Some(chars.iter().collect());
2904 }
2905 }
2906
2907 if char.is_whitespace() || !char.is_ascii() {
2908 return None;
2909 }
2910 if char == ':' {
2911 found_colon = true;
2912 } else {
2913 chars.push(char);
2914 }
2915 }
2916 // Found a possible emoji shortcode at the beginning of the buffer
2917 chars.reverse();
2918 Some(chars.iter().collect())
2919 }
2920
2921 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
2922 self.transact(cx, |this, cx| {
2923 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
2924 let selections = this.selections.all::<usize>(cx);
2925 let multi_buffer = this.buffer.read(cx);
2926 let buffer = multi_buffer.snapshot(cx);
2927 selections
2928 .iter()
2929 .map(|selection| {
2930 let start_point = selection.start.to_point(&buffer);
2931 let mut indent =
2932 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
2933 indent.len = cmp::min(indent.len, start_point.column);
2934 let start = selection.start;
2935 let end = selection.end;
2936 let selection_is_empty = start == end;
2937 let language_scope = buffer.language_scope_at(start);
2938 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
2939 &language_scope
2940 {
2941 let leading_whitespace_len = buffer
2942 .reversed_chars_at(start)
2943 .take_while(|c| c.is_whitespace() && *c != '\n')
2944 .map(|c| c.len_utf8())
2945 .sum::<usize>();
2946
2947 let trailing_whitespace_len = buffer
2948 .chars_at(end)
2949 .take_while(|c| c.is_whitespace() && *c != '\n')
2950 .map(|c| c.len_utf8())
2951 .sum::<usize>();
2952
2953 let insert_extra_newline =
2954 language.brackets().any(|(pair, enabled)| {
2955 let pair_start = pair.start.trim_end();
2956 let pair_end = pair.end.trim_start();
2957
2958 enabled
2959 && pair.newline
2960 && buffer.contains_str_at(
2961 end + trailing_whitespace_len,
2962 pair_end,
2963 )
2964 && buffer.contains_str_at(
2965 (start - leading_whitespace_len)
2966 .saturating_sub(pair_start.len()),
2967 pair_start,
2968 )
2969 });
2970
2971 // Comment extension on newline is allowed only for cursor selections
2972 let comment_delimiter = maybe!({
2973 if !selection_is_empty {
2974 return None;
2975 }
2976
2977 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
2978 return None;
2979 }
2980
2981 let delimiters = language.line_comment_prefixes();
2982 let max_len_of_delimiter =
2983 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
2984 let (snapshot, range) =
2985 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
2986
2987 let mut index_of_first_non_whitespace = 0;
2988 let comment_candidate = snapshot
2989 .chars_for_range(range)
2990 .skip_while(|c| {
2991 let should_skip = c.is_whitespace();
2992 if should_skip {
2993 index_of_first_non_whitespace += 1;
2994 }
2995 should_skip
2996 })
2997 .take(max_len_of_delimiter)
2998 .collect::<String>();
2999 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3000 comment_candidate.starts_with(comment_prefix.as_ref())
3001 })?;
3002 let cursor_is_placed_after_comment_marker =
3003 index_of_first_non_whitespace + comment_prefix.len()
3004 <= start_point.column as usize;
3005 if cursor_is_placed_after_comment_marker {
3006 Some(comment_prefix.clone())
3007 } else {
3008 None
3009 }
3010 });
3011 (comment_delimiter, insert_extra_newline)
3012 } else {
3013 (None, false)
3014 };
3015
3016 let capacity_for_delimiter = comment_delimiter
3017 .as_deref()
3018 .map(str::len)
3019 .unwrap_or_default();
3020 let mut new_text =
3021 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3022 new_text.push('\n');
3023 new_text.extend(indent.chars());
3024 if let Some(delimiter) = &comment_delimiter {
3025 new_text.push_str(delimiter);
3026 }
3027 if insert_extra_newline {
3028 new_text = new_text.repeat(2);
3029 }
3030
3031 let anchor = buffer.anchor_after(end);
3032 let new_selection = selection.map(|_| anchor);
3033 (
3034 (start..end, new_text),
3035 (insert_extra_newline, new_selection),
3036 )
3037 })
3038 .unzip()
3039 };
3040
3041 this.edit_with_autoindent(edits, cx);
3042 let buffer = this.buffer.read(cx).snapshot(cx);
3043 let new_selections = selection_fixup_info
3044 .into_iter()
3045 .map(|(extra_newline_inserted, new_selection)| {
3046 let mut cursor = new_selection.end.to_point(&buffer);
3047 if extra_newline_inserted {
3048 cursor.row -= 1;
3049 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3050 }
3051 new_selection.map(|_| cursor)
3052 })
3053 .collect();
3054
3055 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3056 this.refresh_inline_completion(true, false, cx);
3057 });
3058 }
3059
3060 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3061 let buffer = self.buffer.read(cx);
3062 let snapshot = buffer.snapshot(cx);
3063
3064 let mut edits = Vec::new();
3065 let mut rows = Vec::new();
3066
3067 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3068 let cursor = selection.head();
3069 let row = cursor.row;
3070
3071 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3072
3073 let newline = "\n".to_string();
3074 edits.push((start_of_line..start_of_line, newline));
3075
3076 rows.push(row + rows_inserted as u32);
3077 }
3078
3079 self.transact(cx, |editor, cx| {
3080 editor.edit(edits, cx);
3081
3082 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3083 let mut index = 0;
3084 s.move_cursors_with(|map, _, _| {
3085 let row = rows[index];
3086 index += 1;
3087
3088 let point = Point::new(row, 0);
3089 let boundary = map.next_line_boundary(point).1;
3090 let clipped = map.clip_point(boundary, Bias::Left);
3091
3092 (clipped, SelectionGoal::None)
3093 });
3094 });
3095
3096 let mut indent_edits = Vec::new();
3097 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3098 for row in rows {
3099 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3100 for (row, indent) in indents {
3101 if indent.len == 0 {
3102 continue;
3103 }
3104
3105 let text = match indent.kind {
3106 IndentKind::Space => " ".repeat(indent.len as usize),
3107 IndentKind::Tab => "\t".repeat(indent.len as usize),
3108 };
3109 let point = Point::new(row.0, 0);
3110 indent_edits.push((point..point, text));
3111 }
3112 }
3113 editor.edit(indent_edits, cx);
3114 });
3115 }
3116
3117 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3118 let buffer = self.buffer.read(cx);
3119 let snapshot = buffer.snapshot(cx);
3120
3121 let mut edits = Vec::new();
3122 let mut rows = Vec::new();
3123 let mut rows_inserted = 0;
3124
3125 for selection in self.selections.all_adjusted(cx) {
3126 let cursor = selection.head();
3127 let row = cursor.row;
3128
3129 let point = Point::new(row + 1, 0);
3130 let start_of_line = snapshot.clip_point(point, Bias::Left);
3131
3132 let newline = "\n".to_string();
3133 edits.push((start_of_line..start_of_line, newline));
3134
3135 rows_inserted += 1;
3136 rows.push(row + rows_inserted);
3137 }
3138
3139 self.transact(cx, |editor, cx| {
3140 editor.edit(edits, cx);
3141
3142 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3143 let mut index = 0;
3144 s.move_cursors_with(|map, _, _| {
3145 let row = rows[index];
3146 index += 1;
3147
3148 let point = Point::new(row, 0);
3149 let boundary = map.next_line_boundary(point).1;
3150 let clipped = map.clip_point(boundary, Bias::Left);
3151
3152 (clipped, SelectionGoal::None)
3153 });
3154 });
3155
3156 let mut indent_edits = Vec::new();
3157 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3158 for row in rows {
3159 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3160 for (row, indent) in indents {
3161 if indent.len == 0 {
3162 continue;
3163 }
3164
3165 let text = match indent.kind {
3166 IndentKind::Space => " ".repeat(indent.len as usize),
3167 IndentKind::Tab => "\t".repeat(indent.len as usize),
3168 };
3169 let point = Point::new(row.0, 0);
3170 indent_edits.push((point..point, text));
3171 }
3172 }
3173 editor.edit(indent_edits, cx);
3174 });
3175 }
3176
3177 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3178 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3179 original_indent_columns: Vec::new(),
3180 });
3181 self.insert_with_autoindent_mode(text, autoindent, cx);
3182 }
3183
3184 fn insert_with_autoindent_mode(
3185 &mut self,
3186 text: &str,
3187 autoindent_mode: Option<AutoindentMode>,
3188 cx: &mut ViewContext<Self>,
3189 ) {
3190 if self.read_only(cx) {
3191 return;
3192 }
3193
3194 let text: Arc<str> = text.into();
3195 self.transact(cx, |this, cx| {
3196 let old_selections = this.selections.all_adjusted(cx);
3197 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3198 let anchors = {
3199 let snapshot = buffer.read(cx);
3200 old_selections
3201 .iter()
3202 .map(|s| {
3203 let anchor = snapshot.anchor_after(s.head());
3204 s.map(|_| anchor)
3205 })
3206 .collect::<Vec<_>>()
3207 };
3208 buffer.edit(
3209 old_selections
3210 .iter()
3211 .map(|s| (s.start..s.end, text.clone())),
3212 autoindent_mode,
3213 cx,
3214 );
3215 anchors
3216 });
3217
3218 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3219 s.select_anchors(selection_anchors);
3220 })
3221 });
3222 }
3223
3224 fn trigger_completion_on_input(
3225 &mut self,
3226 text: &str,
3227 trigger_in_words: bool,
3228 cx: &mut ViewContext<Self>,
3229 ) {
3230 if self.is_completion_trigger(text, trigger_in_words, cx) {
3231 self.show_completions(
3232 &ShowCompletions {
3233 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3234 },
3235 cx,
3236 );
3237 } else {
3238 self.hide_context_menu(cx);
3239 }
3240 }
3241
3242 fn is_completion_trigger(
3243 &self,
3244 text: &str,
3245 trigger_in_words: bool,
3246 cx: &mut ViewContext<Self>,
3247 ) -> bool {
3248 let position = self.selections.newest_anchor().head();
3249 let multibuffer = self.buffer.read(cx);
3250 let Some(buffer) = position
3251 .buffer_id
3252 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3253 else {
3254 return false;
3255 };
3256
3257 if let Some(completion_provider) = &self.completion_provider {
3258 completion_provider.is_completion_trigger(
3259 &buffer,
3260 position.text_anchor,
3261 text,
3262 trigger_in_words,
3263 cx,
3264 )
3265 } else {
3266 false
3267 }
3268 }
3269
3270 /// If any empty selections is touching the start of its innermost containing autoclose
3271 /// region, expand it to select the brackets.
3272 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3273 let selections = self.selections.all::<usize>(cx);
3274 let buffer = self.buffer.read(cx).read(cx);
3275 let new_selections = self
3276 .selections_with_autoclose_regions(selections, &buffer)
3277 .map(|(mut selection, region)| {
3278 if !selection.is_empty() {
3279 return selection;
3280 }
3281
3282 if let Some(region) = region {
3283 let mut range = region.range.to_offset(&buffer);
3284 if selection.start == range.start && range.start >= region.pair.start.len() {
3285 range.start -= region.pair.start.len();
3286 if buffer.contains_str_at(range.start, ®ion.pair.start)
3287 && buffer.contains_str_at(range.end, ®ion.pair.end)
3288 {
3289 range.end += region.pair.end.len();
3290 selection.start = range.start;
3291 selection.end = range.end;
3292
3293 return selection;
3294 }
3295 }
3296 }
3297
3298 let always_treat_brackets_as_autoclosed = buffer
3299 .settings_at(selection.start, cx)
3300 .always_treat_brackets_as_autoclosed;
3301
3302 if !always_treat_brackets_as_autoclosed {
3303 return selection;
3304 }
3305
3306 if let Some(scope) = buffer.language_scope_at(selection.start) {
3307 for (pair, enabled) in scope.brackets() {
3308 if !enabled || !pair.close {
3309 continue;
3310 }
3311
3312 if buffer.contains_str_at(selection.start, &pair.end) {
3313 let pair_start_len = pair.start.len();
3314 if buffer.contains_str_at(
3315 selection.start.saturating_sub(pair_start_len),
3316 &pair.start,
3317 ) {
3318 selection.start -= pair_start_len;
3319 selection.end += pair.end.len();
3320
3321 return selection;
3322 }
3323 }
3324 }
3325 }
3326
3327 selection
3328 })
3329 .collect();
3330
3331 drop(buffer);
3332 self.change_selections(None, cx, |selections| selections.select(new_selections));
3333 }
3334
3335 /// Iterate the given selections, and for each one, find the smallest surrounding
3336 /// autoclose region. This uses the ordering of the selections and the autoclose
3337 /// regions to avoid repeated comparisons.
3338 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3339 &'a self,
3340 selections: impl IntoIterator<Item = Selection<D>>,
3341 buffer: &'a MultiBufferSnapshot,
3342 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3343 let mut i = 0;
3344 let mut regions = self.autoclose_regions.as_slice();
3345 selections.into_iter().map(move |selection| {
3346 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3347
3348 let mut enclosing = None;
3349 while let Some(pair_state) = regions.get(i) {
3350 if pair_state.range.end.to_offset(buffer) < range.start {
3351 regions = ®ions[i + 1..];
3352 i = 0;
3353 } else if pair_state.range.start.to_offset(buffer) > range.end {
3354 break;
3355 } else {
3356 if pair_state.selection_id == selection.id {
3357 enclosing = Some(pair_state);
3358 }
3359 i += 1;
3360 }
3361 }
3362
3363 (selection, enclosing)
3364 })
3365 }
3366
3367 /// Remove any autoclose regions that no longer contain their selection.
3368 fn invalidate_autoclose_regions(
3369 &mut self,
3370 mut selections: &[Selection<Anchor>],
3371 buffer: &MultiBufferSnapshot,
3372 ) {
3373 self.autoclose_regions.retain(|state| {
3374 let mut i = 0;
3375 while let Some(selection) = selections.get(i) {
3376 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3377 selections = &selections[1..];
3378 continue;
3379 }
3380 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3381 break;
3382 }
3383 if selection.id == state.selection_id {
3384 return true;
3385 } else {
3386 i += 1;
3387 }
3388 }
3389 false
3390 });
3391 }
3392
3393 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3394 let offset = position.to_offset(buffer);
3395 let (word_range, kind) = buffer.surrounding_word(offset, true);
3396 if offset > word_range.start && kind == Some(CharKind::Word) {
3397 Some(
3398 buffer
3399 .text_for_range(word_range.start..offset)
3400 .collect::<String>(),
3401 )
3402 } else {
3403 None
3404 }
3405 }
3406
3407 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3408 self.refresh_inlay_hints(
3409 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3410 cx,
3411 );
3412 }
3413
3414 pub fn inlay_hints_enabled(&self) -> bool {
3415 self.inlay_hint_cache.enabled
3416 }
3417
3418 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3419 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3420 return;
3421 }
3422
3423 let reason_description = reason.description();
3424 let ignore_debounce = matches!(
3425 reason,
3426 InlayHintRefreshReason::SettingsChange(_)
3427 | InlayHintRefreshReason::Toggle(_)
3428 | InlayHintRefreshReason::ExcerptsRemoved(_)
3429 );
3430 let (invalidate_cache, required_languages) = match reason {
3431 InlayHintRefreshReason::Toggle(enabled) => {
3432 self.inlay_hint_cache.enabled = enabled;
3433 if enabled {
3434 (InvalidationStrategy::RefreshRequested, None)
3435 } else {
3436 self.inlay_hint_cache.clear();
3437 self.splice_inlays(
3438 self.visible_inlay_hints(cx)
3439 .iter()
3440 .map(|inlay| inlay.id)
3441 .collect(),
3442 Vec::new(),
3443 cx,
3444 );
3445 return;
3446 }
3447 }
3448 InlayHintRefreshReason::SettingsChange(new_settings) => {
3449 match self.inlay_hint_cache.update_settings(
3450 &self.buffer,
3451 new_settings,
3452 self.visible_inlay_hints(cx),
3453 cx,
3454 ) {
3455 ControlFlow::Break(Some(InlaySplice {
3456 to_remove,
3457 to_insert,
3458 })) => {
3459 self.splice_inlays(to_remove, to_insert, cx);
3460 return;
3461 }
3462 ControlFlow::Break(None) => return,
3463 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3464 }
3465 }
3466 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3467 if let Some(InlaySplice {
3468 to_remove,
3469 to_insert,
3470 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3471 {
3472 self.splice_inlays(to_remove, to_insert, cx);
3473 }
3474 return;
3475 }
3476 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3477 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3478 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3479 }
3480 InlayHintRefreshReason::RefreshRequested => {
3481 (InvalidationStrategy::RefreshRequested, None)
3482 }
3483 };
3484
3485 if let Some(InlaySplice {
3486 to_remove,
3487 to_insert,
3488 }) = self.inlay_hint_cache.spawn_hint_refresh(
3489 reason_description,
3490 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3491 invalidate_cache,
3492 ignore_debounce,
3493 cx,
3494 ) {
3495 self.splice_inlays(to_remove, to_insert, cx);
3496 }
3497 }
3498
3499 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
3500 self.display_map
3501 .read(cx)
3502 .current_inlays()
3503 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3504 .cloned()
3505 .collect()
3506 }
3507
3508 pub fn excerpts_for_inlay_hints_query(
3509 &self,
3510 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3511 cx: &mut ViewContext<Editor>,
3512 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3513 let Some(project) = self.project.as_ref() else {
3514 return HashMap::default();
3515 };
3516 let project = project.read(cx);
3517 let multi_buffer = self.buffer().read(cx);
3518 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3519 let multi_buffer_visible_start = self
3520 .scroll_manager
3521 .anchor()
3522 .anchor
3523 .to_point(&multi_buffer_snapshot);
3524 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3525 multi_buffer_visible_start
3526 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3527 Bias::Left,
3528 );
3529 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3530 multi_buffer
3531 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
3532 .into_iter()
3533 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3534 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
3535 let buffer = buffer_handle.read(cx);
3536 let buffer_file = project::File::from_dyn(buffer.file())?;
3537 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3538 let worktree_entry = buffer_worktree
3539 .read(cx)
3540 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3541 if worktree_entry.is_ignored {
3542 return None;
3543 }
3544
3545 let language = buffer.language()?;
3546 if let Some(restrict_to_languages) = restrict_to_languages {
3547 if !restrict_to_languages.contains(language) {
3548 return None;
3549 }
3550 }
3551 Some((
3552 excerpt_id,
3553 (
3554 buffer_handle,
3555 buffer.version().clone(),
3556 excerpt_visible_range,
3557 ),
3558 ))
3559 })
3560 .collect()
3561 }
3562
3563 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3564 TextLayoutDetails {
3565 text_system: cx.text_system().clone(),
3566 editor_style: self.style.clone().unwrap(),
3567 rem_size: cx.rem_size(),
3568 scroll_anchor: self.scroll_manager.anchor(),
3569 visible_rows: self.visible_line_count(),
3570 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3571 }
3572 }
3573
3574 fn splice_inlays(
3575 &self,
3576 to_remove: Vec<InlayId>,
3577 to_insert: Vec<Inlay>,
3578 cx: &mut ViewContext<Self>,
3579 ) {
3580 self.display_map.update(cx, |display_map, cx| {
3581 display_map.splice_inlays(to_remove, to_insert, cx)
3582 });
3583 cx.notify();
3584 }
3585
3586 fn trigger_on_type_formatting(
3587 &self,
3588 input: String,
3589 cx: &mut ViewContext<Self>,
3590 ) -> Option<Task<Result<()>>> {
3591 if input.len() != 1 {
3592 return None;
3593 }
3594
3595 let project = self.project.as_ref()?;
3596 let position = self.selections.newest_anchor().head();
3597 let (buffer, buffer_position) = self
3598 .buffer
3599 .read(cx)
3600 .text_anchor_for_position(position, cx)?;
3601
3602 let settings = language_settings::language_settings(
3603 buffer
3604 .read(cx)
3605 .language_at(buffer_position)
3606 .map(|l| l.name()),
3607 buffer.read(cx).file(),
3608 cx,
3609 );
3610 if !settings.use_on_type_format {
3611 return None;
3612 }
3613
3614 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3615 // hence we do LSP request & edit on host side only — add formats to host's history.
3616 let push_to_lsp_host_history = true;
3617 // If this is not the host, append its history with new edits.
3618 let push_to_client_history = project.read(cx).is_via_collab();
3619
3620 let on_type_formatting = project.update(cx, |project, cx| {
3621 project.on_type_format(
3622 buffer.clone(),
3623 buffer_position,
3624 input,
3625 push_to_lsp_host_history,
3626 cx,
3627 )
3628 });
3629 Some(cx.spawn(|editor, mut cx| async move {
3630 if let Some(transaction) = on_type_formatting.await? {
3631 if push_to_client_history {
3632 buffer
3633 .update(&mut cx, |buffer, _| {
3634 buffer.push_transaction(transaction, Instant::now());
3635 })
3636 .ok();
3637 }
3638 editor.update(&mut cx, |editor, cx| {
3639 editor.refresh_document_highlights(cx);
3640 })?;
3641 }
3642 Ok(())
3643 }))
3644 }
3645
3646 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
3647 if self.pending_rename.is_some() {
3648 return;
3649 }
3650
3651 let Some(provider) = self.completion_provider.as_ref() else {
3652 return;
3653 };
3654
3655 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3656 return;
3657 }
3658
3659 let position = self.selections.newest_anchor().head();
3660 let (buffer, buffer_position) =
3661 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3662 output
3663 } else {
3664 return;
3665 };
3666 let show_completion_documentation = buffer
3667 .read(cx)
3668 .snapshot()
3669 .settings_at(buffer_position, cx)
3670 .show_completion_documentation;
3671
3672 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3673
3674 let aside_was_displayed = match self.context_menu.borrow().deref() {
3675 Some(CodeContextMenu::Completions(menu)) => menu.aside_was_displayed.get(),
3676 _ => false,
3677 };
3678 let trigger_kind = match &options.trigger {
3679 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3680 CompletionTriggerKind::TRIGGER_CHARACTER
3681 }
3682 _ => CompletionTriggerKind::INVOKED,
3683 };
3684 let completion_context = CompletionContext {
3685 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3686 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3687 Some(String::from(trigger))
3688 } else {
3689 None
3690 }
3691 }),
3692 trigger_kind,
3693 };
3694 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
3695 let sort_completions = provider.sort_completions();
3696
3697 let id = post_inc(&mut self.next_completion_id);
3698 let task = cx.spawn(|editor, mut cx| {
3699 async move {
3700 editor.update(&mut cx, |this, _| {
3701 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3702 })?;
3703 let completions = completions.await.log_err();
3704 let menu = if let Some(completions) = completions {
3705 let mut menu = CompletionsMenu::new(
3706 id,
3707 sort_completions,
3708 show_completion_documentation,
3709 position,
3710 buffer.clone(),
3711 completions.into(),
3712 aside_was_displayed,
3713 );
3714 menu.filter(query.as_deref(), cx.background_executor().clone())
3715 .await;
3716
3717 if menu.matches.is_empty() {
3718 None
3719 } else {
3720 Some(menu)
3721 }
3722 } else {
3723 None
3724 };
3725
3726 editor.update(&mut cx, |editor, cx| {
3727 let mut context_menu = editor.context_menu.borrow_mut();
3728 match context_menu.as_ref() {
3729 None => {}
3730 Some(CodeContextMenu::Completions(prev_menu)) => {
3731 if prev_menu.id > id {
3732 return;
3733 }
3734 }
3735 _ => return,
3736 }
3737
3738 if editor.focus_handle.is_focused(cx) && menu.is_some() {
3739 let mut menu = menu.unwrap();
3740 menu.resolve_selected_completion(editor.completion_provider.as_deref(), cx);
3741 *context_menu = Some(CodeContextMenu::Completions(menu));
3742 drop(context_menu);
3743 cx.notify();
3744 } else if editor.completion_tasks.len() <= 1 {
3745 // If there are no more completion tasks and the last menu was
3746 // empty, we should hide it. If it was already hidden, we should
3747 // also show the copilot completion when available.
3748 drop(context_menu);
3749 editor.hide_context_menu(cx);
3750 }
3751 })?;
3752
3753 Ok::<_, anyhow::Error>(())
3754 }
3755 .log_err()
3756 });
3757
3758 self.completion_tasks.push((id, task));
3759 }
3760
3761 pub fn confirm_completion(
3762 &mut self,
3763 action: &ConfirmCompletion,
3764 cx: &mut ViewContext<Self>,
3765 ) -> Option<Task<Result<()>>> {
3766 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
3767 }
3768
3769 pub fn compose_completion(
3770 &mut self,
3771 action: &ComposeCompletion,
3772 cx: &mut ViewContext<Self>,
3773 ) -> Option<Task<Result<()>>> {
3774 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
3775 }
3776
3777 fn do_completion(
3778 &mut self,
3779 item_ix: Option<usize>,
3780 intent: CompletionIntent,
3781 cx: &mut ViewContext<Editor>,
3782 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3783 use language::ToOffset as _;
3784
3785 self.discard_inline_completion(true, cx);
3786 let completions_menu =
3787 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3788 menu
3789 } else {
3790 return None;
3791 };
3792
3793 let mat = completions_menu
3794 .matches
3795 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
3796 let buffer_handle = completions_menu.buffer;
3797 let completions = completions_menu.completions.borrow_mut();
3798 let completion = completions.get(mat.candidate_id)?;
3799 cx.stop_propagation();
3800
3801 let snippet;
3802 let text;
3803
3804 if completion.is_snippet() {
3805 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3806 text = snippet.as_ref().unwrap().text.clone();
3807 } else {
3808 snippet = None;
3809 text = completion.new_text.clone();
3810 };
3811 let selections = self.selections.all::<usize>(cx);
3812 let buffer = buffer_handle.read(cx);
3813 let old_range = completion.old_range.to_offset(buffer);
3814 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3815
3816 let newest_selection = self.selections.newest_anchor();
3817 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3818 return None;
3819 }
3820
3821 let lookbehind = newest_selection
3822 .start
3823 .text_anchor
3824 .to_offset(buffer)
3825 .saturating_sub(old_range.start);
3826 let lookahead = old_range
3827 .end
3828 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3829 let mut common_prefix_len = old_text
3830 .bytes()
3831 .zip(text.bytes())
3832 .take_while(|(a, b)| a == b)
3833 .count();
3834
3835 let snapshot = self.buffer.read(cx).snapshot(cx);
3836 let mut range_to_replace: Option<Range<isize>> = None;
3837 let mut ranges = Vec::new();
3838 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3839 for selection in &selections {
3840 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3841 let start = selection.start.saturating_sub(lookbehind);
3842 let end = selection.end + lookahead;
3843 if selection.id == newest_selection.id {
3844 range_to_replace = Some(
3845 ((start + common_prefix_len) as isize - selection.start as isize)
3846 ..(end as isize - selection.start as isize),
3847 );
3848 }
3849 ranges.push(start + common_prefix_len..end);
3850 } else {
3851 common_prefix_len = 0;
3852 ranges.clear();
3853 ranges.extend(selections.iter().map(|s| {
3854 if s.id == newest_selection.id {
3855 range_to_replace = Some(
3856 old_range.start.to_offset_utf16(&snapshot).0 as isize
3857 - selection.start as isize
3858 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3859 - selection.start as isize,
3860 );
3861 old_range.clone()
3862 } else {
3863 s.start..s.end
3864 }
3865 }));
3866 break;
3867 }
3868 if !self.linked_edit_ranges.is_empty() {
3869 let start_anchor = snapshot.anchor_before(selection.head());
3870 let end_anchor = snapshot.anchor_after(selection.tail());
3871 if let Some(ranges) = self
3872 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
3873 {
3874 for (buffer, edits) in ranges {
3875 linked_edits.entry(buffer.clone()).or_default().extend(
3876 edits
3877 .into_iter()
3878 .map(|range| (range, text[common_prefix_len..].to_owned())),
3879 );
3880 }
3881 }
3882 }
3883 }
3884 let text = &text[common_prefix_len..];
3885
3886 cx.emit(EditorEvent::InputHandled {
3887 utf16_range_to_replace: range_to_replace,
3888 text: text.into(),
3889 });
3890
3891 self.transact(cx, |this, cx| {
3892 if let Some(mut snippet) = snippet {
3893 snippet.text = text.to_string();
3894 for tabstop in snippet
3895 .tabstops
3896 .iter_mut()
3897 .flat_map(|tabstop| tabstop.ranges.iter_mut())
3898 {
3899 tabstop.start -= common_prefix_len as isize;
3900 tabstop.end -= common_prefix_len as isize;
3901 }
3902
3903 this.insert_snippet(&ranges, snippet, cx).log_err();
3904 } else {
3905 this.buffer.update(cx, |buffer, cx| {
3906 buffer.edit(
3907 ranges.iter().map(|range| (range.clone(), text)),
3908 this.autoindent_mode.clone(),
3909 cx,
3910 );
3911 });
3912 }
3913 for (buffer, edits) in linked_edits {
3914 buffer.update(cx, |buffer, cx| {
3915 let snapshot = buffer.snapshot();
3916 let edits = edits
3917 .into_iter()
3918 .map(|(range, text)| {
3919 use text::ToPoint as TP;
3920 let end_point = TP::to_point(&range.end, &snapshot);
3921 let start_point = TP::to_point(&range.start, &snapshot);
3922 (start_point..end_point, text)
3923 })
3924 .sorted_by_key(|(range, _)| range.start)
3925 .collect::<Vec<_>>();
3926 buffer.edit(edits, None, cx);
3927 })
3928 }
3929
3930 this.refresh_inline_completion(true, false, cx);
3931 });
3932
3933 let show_new_completions_on_confirm = completion
3934 .confirm
3935 .as_ref()
3936 .map_or(false, |confirm| confirm(intent, cx));
3937 if show_new_completions_on_confirm {
3938 self.show_completions(&ShowCompletions { trigger: None }, cx);
3939 }
3940
3941 let provider = self.completion_provider.as_ref()?;
3942 let apply_edits = provider.apply_additional_edits_for_completion(
3943 buffer_handle,
3944 completion.clone(),
3945 true,
3946 cx,
3947 );
3948
3949 let editor_settings = EditorSettings::get_global(cx);
3950 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
3951 // After the code completion is finished, users often want to know what signatures are needed.
3952 // so we should automatically call signature_help
3953 self.show_signature_help(&ShowSignatureHelp, cx);
3954 }
3955
3956 Some(cx.foreground_executor().spawn(async move {
3957 apply_edits.await?;
3958 Ok(())
3959 }))
3960 }
3961
3962 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
3963 let mut context_menu = self.context_menu.borrow_mut();
3964 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
3965 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
3966 // Toggle if we're selecting the same one
3967 *context_menu = None;
3968 cx.notify();
3969 return;
3970 } else {
3971 // Otherwise, clear it and start a new one
3972 *context_menu = None;
3973 cx.notify();
3974 }
3975 }
3976 drop(context_menu);
3977 let snapshot = self.snapshot(cx);
3978 let deployed_from_indicator = action.deployed_from_indicator;
3979 let mut task = self.code_actions_task.take();
3980 let action = action.clone();
3981 cx.spawn(|editor, mut cx| async move {
3982 while let Some(prev_task) = task {
3983 prev_task.await.log_err();
3984 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
3985 }
3986
3987 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
3988 if editor.focus_handle.is_focused(cx) {
3989 let multibuffer_point = action
3990 .deployed_from_indicator
3991 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
3992 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
3993 let (buffer, buffer_row) = snapshot
3994 .buffer_snapshot
3995 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
3996 .and_then(|(buffer_snapshot, range)| {
3997 editor
3998 .buffer
3999 .read(cx)
4000 .buffer(buffer_snapshot.remote_id())
4001 .map(|buffer| (buffer, range.start.row))
4002 })?;
4003 let (_, code_actions) = editor
4004 .available_code_actions
4005 .clone()
4006 .and_then(|(location, code_actions)| {
4007 let snapshot = location.buffer.read(cx).snapshot();
4008 let point_range = location.range.to_point(&snapshot);
4009 let point_range = point_range.start.row..=point_range.end.row;
4010 if point_range.contains(&buffer_row) {
4011 Some((location, code_actions))
4012 } else {
4013 None
4014 }
4015 })
4016 .unzip();
4017 let buffer_id = buffer.read(cx).remote_id();
4018 let tasks = editor
4019 .tasks
4020 .get(&(buffer_id, buffer_row))
4021 .map(|t| Arc::new(t.to_owned()));
4022 if tasks.is_none() && code_actions.is_none() {
4023 return None;
4024 }
4025
4026 editor.completion_tasks.clear();
4027 editor.discard_inline_completion(false, cx);
4028 let task_context =
4029 tasks
4030 .as_ref()
4031 .zip(editor.project.clone())
4032 .map(|(tasks, project)| {
4033 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4034 });
4035
4036 Some(cx.spawn(|editor, mut cx| async move {
4037 let task_context = match task_context {
4038 Some(task_context) => task_context.await,
4039 None => None,
4040 };
4041 let resolved_tasks =
4042 tasks.zip(task_context).map(|(tasks, task_context)| {
4043 Rc::new(ResolvedTasks {
4044 templates: tasks.resolve(&task_context).collect(),
4045 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4046 multibuffer_point.row,
4047 tasks.column,
4048 )),
4049 })
4050 });
4051 let spawn_straight_away = resolved_tasks
4052 .as_ref()
4053 .map_or(false, |tasks| tasks.templates.len() == 1)
4054 && code_actions
4055 .as_ref()
4056 .map_or(true, |actions| actions.is_empty());
4057 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4058 *editor.context_menu.borrow_mut() =
4059 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4060 buffer,
4061 actions: CodeActionContents {
4062 tasks: resolved_tasks,
4063 actions: code_actions,
4064 },
4065 selected_item: Default::default(),
4066 scroll_handle: UniformListScrollHandle::default(),
4067 deployed_from_indicator,
4068 }));
4069 if spawn_straight_away {
4070 if let Some(task) = editor.confirm_code_action(
4071 &ConfirmCodeAction { item_ix: Some(0) },
4072 cx,
4073 ) {
4074 cx.notify();
4075 return task;
4076 }
4077 }
4078 cx.notify();
4079 Task::ready(Ok(()))
4080 }) {
4081 task.await
4082 } else {
4083 Ok(())
4084 }
4085 }))
4086 } else {
4087 Some(Task::ready(Ok(())))
4088 }
4089 })?;
4090 if let Some(task) = spawned_test_task {
4091 task.await?;
4092 }
4093
4094 Ok::<_, anyhow::Error>(())
4095 })
4096 .detach_and_log_err(cx);
4097 }
4098
4099 pub fn confirm_code_action(
4100 &mut self,
4101 action: &ConfirmCodeAction,
4102 cx: &mut ViewContext<Self>,
4103 ) -> Option<Task<Result<()>>> {
4104 let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4105 menu
4106 } else {
4107 return None;
4108 };
4109 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4110 let action = actions_menu.actions.get(action_ix)?;
4111 let title = action.label();
4112 let buffer = actions_menu.buffer;
4113 let workspace = self.workspace()?;
4114
4115 match action {
4116 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4117 workspace.update(cx, |workspace, cx| {
4118 workspace::tasks::schedule_resolved_task(
4119 workspace,
4120 task_source_kind,
4121 resolved_task,
4122 false,
4123 cx,
4124 );
4125
4126 Some(Task::ready(Ok(())))
4127 })
4128 }
4129 CodeActionsItem::CodeAction {
4130 excerpt_id,
4131 action,
4132 provider,
4133 } => {
4134 let apply_code_action =
4135 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4136 let workspace = workspace.downgrade();
4137 Some(cx.spawn(|editor, cx| async move {
4138 let project_transaction = apply_code_action.await?;
4139 Self::open_project_transaction(
4140 &editor,
4141 workspace,
4142 project_transaction,
4143 title,
4144 cx,
4145 )
4146 .await
4147 }))
4148 }
4149 }
4150 }
4151
4152 pub async fn open_project_transaction(
4153 this: &WeakView<Editor>,
4154 workspace: WeakView<Workspace>,
4155 transaction: ProjectTransaction,
4156 title: String,
4157 mut cx: AsyncWindowContext,
4158 ) -> Result<()> {
4159 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4160 cx.update(|cx| {
4161 entries.sort_unstable_by_key(|(buffer, _)| {
4162 buffer.read(cx).file().map(|f| f.path().clone())
4163 });
4164 })?;
4165
4166 // If the project transaction's edits are all contained within this editor, then
4167 // avoid opening a new editor to display them.
4168
4169 if let Some((buffer, transaction)) = entries.first() {
4170 if entries.len() == 1 {
4171 let excerpt = this.update(&mut cx, |editor, cx| {
4172 editor
4173 .buffer()
4174 .read(cx)
4175 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4176 })?;
4177 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4178 if excerpted_buffer == *buffer {
4179 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4180 let excerpt_range = excerpt_range.to_offset(buffer);
4181 buffer
4182 .edited_ranges_for_transaction::<usize>(transaction)
4183 .all(|range| {
4184 excerpt_range.start <= range.start
4185 && excerpt_range.end >= range.end
4186 })
4187 })?;
4188
4189 if all_edits_within_excerpt {
4190 return Ok(());
4191 }
4192 }
4193 }
4194 }
4195 } else {
4196 return Ok(());
4197 }
4198
4199 let mut ranges_to_highlight = Vec::new();
4200 let excerpt_buffer = cx.new_model(|cx| {
4201 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4202 for (buffer_handle, transaction) in &entries {
4203 let buffer = buffer_handle.read(cx);
4204 ranges_to_highlight.extend(
4205 multibuffer.push_excerpts_with_context_lines(
4206 buffer_handle.clone(),
4207 buffer
4208 .edited_ranges_for_transaction::<usize>(transaction)
4209 .collect(),
4210 DEFAULT_MULTIBUFFER_CONTEXT,
4211 cx,
4212 ),
4213 );
4214 }
4215 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4216 multibuffer
4217 })?;
4218
4219 workspace.update(&mut cx, |workspace, cx| {
4220 let project = workspace.project().clone();
4221 let editor =
4222 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4223 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4224 editor.update(cx, |editor, cx| {
4225 editor.highlight_background::<Self>(
4226 &ranges_to_highlight,
4227 |theme| theme.editor_highlighted_line_background,
4228 cx,
4229 );
4230 });
4231 })?;
4232
4233 Ok(())
4234 }
4235
4236 pub fn clear_code_action_providers(&mut self) {
4237 self.code_action_providers.clear();
4238 self.available_code_actions.take();
4239 }
4240
4241 pub fn push_code_action_provider(
4242 &mut self,
4243 provider: Rc<dyn CodeActionProvider>,
4244 cx: &mut ViewContext<Self>,
4245 ) {
4246 self.code_action_providers.push(provider);
4247 self.refresh_code_actions(cx);
4248 }
4249
4250 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4251 let buffer = self.buffer.read(cx);
4252 let newest_selection = self.selections.newest_anchor().clone();
4253 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4254 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4255 if start_buffer != end_buffer {
4256 return None;
4257 }
4258
4259 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4260 cx.background_executor()
4261 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4262 .await;
4263
4264 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4265 let providers = this.code_action_providers.clone();
4266 let tasks = this
4267 .code_action_providers
4268 .iter()
4269 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4270 .collect::<Vec<_>>();
4271 (providers, tasks)
4272 })?;
4273
4274 let mut actions = Vec::new();
4275 for (provider, provider_actions) in
4276 providers.into_iter().zip(future::join_all(tasks).await)
4277 {
4278 if let Some(provider_actions) = provider_actions.log_err() {
4279 actions.extend(provider_actions.into_iter().map(|action| {
4280 AvailableCodeAction {
4281 excerpt_id: newest_selection.start.excerpt_id,
4282 action,
4283 provider: provider.clone(),
4284 }
4285 }));
4286 }
4287 }
4288
4289 this.update(&mut cx, |this, cx| {
4290 this.available_code_actions = if actions.is_empty() {
4291 None
4292 } else {
4293 Some((
4294 Location {
4295 buffer: start_buffer,
4296 range: start..end,
4297 },
4298 actions.into(),
4299 ))
4300 };
4301 cx.notify();
4302 })
4303 }));
4304 None
4305 }
4306
4307 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4308 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4309 self.show_git_blame_inline = false;
4310
4311 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4312 cx.background_executor().timer(delay).await;
4313
4314 this.update(&mut cx, |this, cx| {
4315 this.show_git_blame_inline = true;
4316 cx.notify();
4317 })
4318 .log_err();
4319 }));
4320 }
4321 }
4322
4323 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4324 if self.pending_rename.is_some() {
4325 return None;
4326 }
4327
4328 let provider = self.semantics_provider.clone()?;
4329 let buffer = self.buffer.read(cx);
4330 let newest_selection = self.selections.newest_anchor().clone();
4331 let cursor_position = newest_selection.head();
4332 let (cursor_buffer, cursor_buffer_position) =
4333 buffer.text_anchor_for_position(cursor_position, cx)?;
4334 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4335 if cursor_buffer != tail_buffer {
4336 return None;
4337 }
4338 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4339 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4340 cx.background_executor()
4341 .timer(Duration::from_millis(debounce))
4342 .await;
4343
4344 let highlights = if let Some(highlights) = cx
4345 .update(|cx| {
4346 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4347 })
4348 .ok()
4349 .flatten()
4350 {
4351 highlights.await.log_err()
4352 } else {
4353 None
4354 };
4355
4356 if let Some(highlights) = highlights {
4357 this.update(&mut cx, |this, cx| {
4358 if this.pending_rename.is_some() {
4359 return;
4360 }
4361
4362 let buffer_id = cursor_position.buffer_id;
4363 let buffer = this.buffer.read(cx);
4364 if !buffer
4365 .text_anchor_for_position(cursor_position, cx)
4366 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4367 {
4368 return;
4369 }
4370
4371 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4372 let mut write_ranges = Vec::new();
4373 let mut read_ranges = Vec::new();
4374 for highlight in highlights {
4375 for (excerpt_id, excerpt_range) in
4376 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4377 {
4378 let start = highlight
4379 .range
4380 .start
4381 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4382 let end = highlight
4383 .range
4384 .end
4385 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4386 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4387 continue;
4388 }
4389
4390 let range = Anchor {
4391 buffer_id,
4392 excerpt_id,
4393 text_anchor: start,
4394 }..Anchor {
4395 buffer_id,
4396 excerpt_id,
4397 text_anchor: end,
4398 };
4399 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4400 write_ranges.push(range);
4401 } else {
4402 read_ranges.push(range);
4403 }
4404 }
4405 }
4406
4407 this.highlight_background::<DocumentHighlightRead>(
4408 &read_ranges,
4409 |theme| theme.editor_document_highlight_read_background,
4410 cx,
4411 );
4412 this.highlight_background::<DocumentHighlightWrite>(
4413 &write_ranges,
4414 |theme| theme.editor_document_highlight_write_background,
4415 cx,
4416 );
4417 cx.notify();
4418 })
4419 .log_err();
4420 }
4421 }));
4422 None
4423 }
4424
4425 pub fn refresh_inline_completion(
4426 &mut self,
4427 debounce: bool,
4428 user_requested: bool,
4429 cx: &mut ViewContext<Self>,
4430 ) -> Option<()> {
4431 let provider = self.inline_completion_provider()?;
4432 let cursor = self.selections.newest_anchor().head();
4433 let (buffer, cursor_buffer_position) =
4434 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4435
4436 if !user_requested
4437 && (!self.enable_inline_completions
4438 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4439 || !self.is_focused(cx))
4440 {
4441 self.discard_inline_completion(false, cx);
4442 return None;
4443 }
4444
4445 self.update_visible_inline_completion(cx);
4446 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4447 Some(())
4448 }
4449
4450 fn cycle_inline_completion(
4451 &mut self,
4452 direction: Direction,
4453 cx: &mut ViewContext<Self>,
4454 ) -> Option<()> {
4455 let provider = self.inline_completion_provider()?;
4456 let cursor = self.selections.newest_anchor().head();
4457 let (buffer, cursor_buffer_position) =
4458 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4459 if !self.enable_inline_completions
4460 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4461 {
4462 return None;
4463 }
4464
4465 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4466 self.update_visible_inline_completion(cx);
4467
4468 Some(())
4469 }
4470
4471 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4472 if !self.has_active_inline_completion() {
4473 self.refresh_inline_completion(false, true, cx);
4474 return;
4475 }
4476
4477 self.update_visible_inline_completion(cx);
4478 }
4479
4480 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4481 self.show_cursor_names(cx);
4482 }
4483
4484 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4485 self.show_cursor_names = true;
4486 cx.notify();
4487 cx.spawn(|this, mut cx| async move {
4488 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4489 this.update(&mut cx, |this, cx| {
4490 this.show_cursor_names = false;
4491 cx.notify()
4492 })
4493 .ok()
4494 })
4495 .detach();
4496 }
4497
4498 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4499 if self.has_active_inline_completion() {
4500 self.cycle_inline_completion(Direction::Next, cx);
4501 } else {
4502 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4503 if is_copilot_disabled {
4504 cx.propagate();
4505 }
4506 }
4507 }
4508
4509 pub fn previous_inline_completion(
4510 &mut self,
4511 _: &PreviousInlineCompletion,
4512 cx: &mut ViewContext<Self>,
4513 ) {
4514 if self.has_active_inline_completion() {
4515 self.cycle_inline_completion(Direction::Prev, cx);
4516 } else {
4517 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4518 if is_copilot_disabled {
4519 cx.propagate();
4520 }
4521 }
4522 }
4523
4524 pub fn accept_inline_completion(
4525 &mut self,
4526 _: &AcceptInlineCompletion,
4527 cx: &mut ViewContext<Self>,
4528 ) {
4529 self.hide_context_menu(cx);
4530
4531 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4532 return;
4533 };
4534
4535 self.report_inline_completion_event(true, cx);
4536
4537 match &active_inline_completion.completion {
4538 InlineCompletion::Move(position) => {
4539 let position = *position;
4540 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4541 selections.select_anchor_ranges([position..position]);
4542 });
4543 }
4544 InlineCompletion::Edit(edits) => {
4545 if let Some(provider) = self.inline_completion_provider() {
4546 provider.accept(cx);
4547 }
4548
4549 let snapshot = self.buffer.read(cx).snapshot(cx);
4550 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4551
4552 self.buffer.update(cx, |buffer, cx| {
4553 buffer.edit(edits.iter().cloned(), None, cx)
4554 });
4555
4556 self.change_selections(None, cx, |s| {
4557 s.select_anchor_ranges([last_edit_end..last_edit_end])
4558 });
4559
4560 self.update_visible_inline_completion(cx);
4561 if self.active_inline_completion.is_none() {
4562 self.refresh_inline_completion(true, true, cx);
4563 }
4564
4565 cx.notify();
4566 }
4567 }
4568 }
4569
4570 pub fn accept_partial_inline_completion(
4571 &mut self,
4572 _: &AcceptPartialInlineCompletion,
4573 cx: &mut ViewContext<Self>,
4574 ) {
4575 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4576 return;
4577 };
4578 if self.selections.count() != 1 {
4579 return;
4580 }
4581
4582 self.report_inline_completion_event(true, cx);
4583
4584 match &active_inline_completion.completion {
4585 InlineCompletion::Move(position) => {
4586 let position = *position;
4587 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4588 selections.select_anchor_ranges([position..position]);
4589 });
4590 }
4591 InlineCompletion::Edit(edits) => {
4592 if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
4593 let text = edits[0].1.as_str();
4594 let mut partial_completion = text
4595 .chars()
4596 .by_ref()
4597 .take_while(|c| c.is_alphabetic())
4598 .collect::<String>();
4599 if partial_completion.is_empty() {
4600 partial_completion = text
4601 .chars()
4602 .by_ref()
4603 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4604 .collect::<String>();
4605 }
4606
4607 cx.emit(EditorEvent::InputHandled {
4608 utf16_range_to_replace: None,
4609 text: partial_completion.clone().into(),
4610 });
4611
4612 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4613
4614 self.refresh_inline_completion(true, true, cx);
4615 cx.notify();
4616 }
4617 }
4618 }
4619 }
4620
4621 fn discard_inline_completion(
4622 &mut self,
4623 should_report_inline_completion_event: bool,
4624 cx: &mut ViewContext<Self>,
4625 ) -> bool {
4626 if should_report_inline_completion_event {
4627 self.report_inline_completion_event(false, cx);
4628 }
4629
4630 if let Some(provider) = self.inline_completion_provider() {
4631 provider.discard(cx);
4632 }
4633
4634 self.take_active_inline_completion(cx).is_some()
4635 }
4636
4637 fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
4638 let Some(provider) = self.inline_completion_provider() else {
4639 return;
4640 };
4641 let Some(project) = self.project.as_ref() else {
4642 return;
4643 };
4644 let Some((_, buffer, _)) = self
4645 .buffer
4646 .read(cx)
4647 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4648 else {
4649 return;
4650 };
4651
4652 let project = project.read(cx);
4653 let extension = buffer
4654 .read(cx)
4655 .file()
4656 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4657 project.client().telemetry().report_inline_completion_event(
4658 provider.name().into(),
4659 accepted,
4660 extension,
4661 );
4662 }
4663
4664 pub fn has_active_inline_completion(&self) -> bool {
4665 self.active_inline_completion.is_some()
4666 }
4667
4668 fn take_active_inline_completion(
4669 &mut self,
4670 cx: &mut ViewContext<Self>,
4671 ) -> Option<InlineCompletion> {
4672 let active_inline_completion = self.active_inline_completion.take()?;
4673 self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
4674 self.clear_highlights::<InlineCompletionHighlight>(cx);
4675 Some(active_inline_completion.completion)
4676 }
4677
4678 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4679 let selection = self.selections.newest_anchor();
4680 let cursor = selection.head();
4681 let multibuffer = self.buffer.read(cx).snapshot(cx);
4682 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
4683 let excerpt_id = cursor.excerpt_id;
4684
4685 if !offset_selection.is_empty()
4686 || self
4687 .active_inline_completion
4688 .as_ref()
4689 .map_or(false, |completion| {
4690 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
4691 let invalidation_range = invalidation_range.start..=invalidation_range.end;
4692 !invalidation_range.contains(&offset_selection.head())
4693 })
4694 {
4695 self.discard_inline_completion(false, cx);
4696 return None;
4697 }
4698
4699 self.take_active_inline_completion(cx);
4700 let provider = self.inline_completion_provider()?;
4701
4702 let (buffer, cursor_buffer_position) =
4703 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4704
4705 let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
4706 let edits = completion
4707 .edits
4708 .into_iter()
4709 .map(|(range, new_text)| {
4710 (
4711 multibuffer
4712 .anchor_in_excerpt(excerpt_id, range.start)
4713 .unwrap()
4714 ..multibuffer
4715 .anchor_in_excerpt(excerpt_id, range.end)
4716 .unwrap(),
4717 new_text,
4718 )
4719 })
4720 .collect::<Vec<_>>();
4721 if edits.is_empty() {
4722 return None;
4723 }
4724
4725 let first_edit_start = edits.first().unwrap().0.start;
4726 let edit_start_row = first_edit_start
4727 .to_point(&multibuffer)
4728 .row
4729 .saturating_sub(2);
4730
4731 let last_edit_end = edits.last().unwrap().0.end;
4732 let edit_end_row = cmp::min(
4733 multibuffer.max_point().row,
4734 last_edit_end.to_point(&multibuffer).row + 2,
4735 );
4736
4737 let cursor_row = cursor.to_point(&multibuffer).row;
4738
4739 let mut inlay_ids = Vec::new();
4740 let invalidation_row_range;
4741 let completion;
4742 if cursor_row < edit_start_row {
4743 invalidation_row_range = cursor_row..edit_end_row;
4744 completion = InlineCompletion::Move(first_edit_start);
4745 } else if cursor_row > edit_end_row {
4746 invalidation_row_range = edit_start_row..cursor_row;
4747 completion = InlineCompletion::Move(first_edit_start);
4748 } else {
4749 if edits
4750 .iter()
4751 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
4752 {
4753 let mut inlays = Vec::new();
4754 for (range, new_text) in &edits {
4755 let inlay = Inlay::inline_completion(
4756 post_inc(&mut self.next_inlay_id),
4757 range.start,
4758 new_text.as_str(),
4759 );
4760 inlay_ids.push(inlay.id);
4761 inlays.push(inlay);
4762 }
4763
4764 self.splice_inlays(vec![], inlays, cx);
4765 } else {
4766 let background_color = cx.theme().status().deleted_background;
4767 self.highlight_text::<InlineCompletionHighlight>(
4768 edits.iter().map(|(range, _)| range.clone()).collect(),
4769 HighlightStyle {
4770 background_color: Some(background_color),
4771 ..Default::default()
4772 },
4773 cx,
4774 );
4775 }
4776
4777 invalidation_row_range = edit_start_row..edit_end_row;
4778 completion = InlineCompletion::Edit(edits);
4779 };
4780
4781 let invalidation_range = multibuffer
4782 .anchor_before(Point::new(invalidation_row_range.start, 0))
4783 ..multibuffer.anchor_after(Point::new(
4784 invalidation_row_range.end,
4785 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
4786 ));
4787
4788 self.active_inline_completion = Some(InlineCompletionState {
4789 inlay_ids,
4790 completion,
4791 invalidation_range,
4792 });
4793 cx.notify();
4794
4795 Some(())
4796 }
4797
4798 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
4799 Some(self.inline_completion_provider.as_ref()?.provider.clone())
4800 }
4801
4802 fn render_code_actions_indicator(
4803 &self,
4804 _style: &EditorStyle,
4805 row: DisplayRow,
4806 is_active: bool,
4807 cx: &mut ViewContext<Self>,
4808 ) -> Option<IconButton> {
4809 if self.available_code_actions.is_some() {
4810 Some(
4811 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
4812 .shape(ui::IconButtonShape::Square)
4813 .icon_size(IconSize::XSmall)
4814 .icon_color(Color::Muted)
4815 .toggle_state(is_active)
4816 .tooltip({
4817 let focus_handle = self.focus_handle.clone();
4818 move |cx| {
4819 Tooltip::for_action_in(
4820 "Toggle Code Actions",
4821 &ToggleCodeActions {
4822 deployed_from_indicator: None,
4823 },
4824 &focus_handle,
4825 cx,
4826 )
4827 }
4828 })
4829 .on_click(cx.listener(move |editor, _e, cx| {
4830 editor.focus(cx);
4831 editor.toggle_code_actions(
4832 &ToggleCodeActions {
4833 deployed_from_indicator: Some(row),
4834 },
4835 cx,
4836 );
4837 })),
4838 )
4839 } else {
4840 None
4841 }
4842 }
4843
4844 fn clear_tasks(&mut self) {
4845 self.tasks.clear()
4846 }
4847
4848 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
4849 if self.tasks.insert(key, value).is_some() {
4850 // This case should hopefully be rare, but just in case...
4851 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
4852 }
4853 }
4854
4855 fn build_tasks_context(
4856 project: &Model<Project>,
4857 buffer: &Model<Buffer>,
4858 buffer_row: u32,
4859 tasks: &Arc<RunnableTasks>,
4860 cx: &mut ViewContext<Self>,
4861 ) -> Task<Option<task::TaskContext>> {
4862 let position = Point::new(buffer_row, tasks.column);
4863 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4864 let location = Location {
4865 buffer: buffer.clone(),
4866 range: range_start..range_start,
4867 };
4868 // Fill in the environmental variables from the tree-sitter captures
4869 let mut captured_task_variables = TaskVariables::default();
4870 for (capture_name, value) in tasks.extra_variables.clone() {
4871 captured_task_variables.insert(
4872 task::VariableName::Custom(capture_name.into()),
4873 value.clone(),
4874 );
4875 }
4876 project.update(cx, |project, cx| {
4877 project.task_store().update(cx, |task_store, cx| {
4878 task_store.task_context_for_location(captured_task_variables, location, cx)
4879 })
4880 })
4881 }
4882
4883 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
4884 let Some((workspace, _)) = self.workspace.clone() else {
4885 return;
4886 };
4887 let Some(project) = self.project.clone() else {
4888 return;
4889 };
4890
4891 // Try to find a closest, enclosing node using tree-sitter that has a
4892 // task
4893 let Some((buffer, buffer_row, tasks)) = self
4894 .find_enclosing_node_task(cx)
4895 // Or find the task that's closest in row-distance.
4896 .or_else(|| self.find_closest_task(cx))
4897 else {
4898 return;
4899 };
4900
4901 let reveal_strategy = action.reveal;
4902 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
4903 cx.spawn(|_, mut cx| async move {
4904 let context = task_context.await?;
4905 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
4906
4907 let resolved = resolved_task.resolved.as_mut()?;
4908 resolved.reveal = reveal_strategy;
4909
4910 workspace
4911 .update(&mut cx, |workspace, cx| {
4912 workspace::tasks::schedule_resolved_task(
4913 workspace,
4914 task_source_kind,
4915 resolved_task,
4916 false,
4917 cx,
4918 );
4919 })
4920 .ok()
4921 })
4922 .detach();
4923 }
4924
4925 fn find_closest_task(
4926 &mut self,
4927 cx: &mut ViewContext<Self>,
4928 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
4929 let cursor_row = self.selections.newest_adjusted(cx).head().row;
4930
4931 let ((buffer_id, row), tasks) = self
4932 .tasks
4933 .iter()
4934 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
4935
4936 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
4937 let tasks = Arc::new(tasks.to_owned());
4938 Some((buffer, *row, tasks))
4939 }
4940
4941 fn find_enclosing_node_task(
4942 &mut self,
4943 cx: &mut ViewContext<Self>,
4944 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
4945 let snapshot = self.buffer.read(cx).snapshot(cx);
4946 let offset = self.selections.newest::<usize>(cx).head();
4947 let excerpt = snapshot.excerpt_containing(offset..offset)?;
4948 let buffer_id = excerpt.buffer().remote_id();
4949
4950 let layer = excerpt.buffer().syntax_layer_at(offset)?;
4951 let mut cursor = layer.node().walk();
4952
4953 while cursor.goto_first_child_for_byte(offset).is_some() {
4954 if cursor.node().end_byte() == offset {
4955 cursor.goto_next_sibling();
4956 }
4957 }
4958
4959 // Ascend to the smallest ancestor that contains the range and has a task.
4960 loop {
4961 let node = cursor.node();
4962 let node_range = node.byte_range();
4963 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
4964
4965 // Check if this node contains our offset
4966 if node_range.start <= offset && node_range.end >= offset {
4967 // If it contains offset, check for task
4968 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
4969 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
4970 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
4971 }
4972 }
4973
4974 if !cursor.goto_parent() {
4975 break;
4976 }
4977 }
4978 None
4979 }
4980
4981 fn render_run_indicator(
4982 &self,
4983 _style: &EditorStyle,
4984 is_active: bool,
4985 row: DisplayRow,
4986 cx: &mut ViewContext<Self>,
4987 ) -> IconButton {
4988 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
4989 .shape(ui::IconButtonShape::Square)
4990 .icon_size(IconSize::XSmall)
4991 .icon_color(Color::Muted)
4992 .toggle_state(is_active)
4993 .on_click(cx.listener(move |editor, _e, cx| {
4994 editor.focus(cx);
4995 editor.toggle_code_actions(
4996 &ToggleCodeActions {
4997 deployed_from_indicator: Some(row),
4998 },
4999 cx,
5000 );
5001 }))
5002 }
5003
5004 pub fn context_menu_visible(&self) -> bool {
5005 self.context_menu
5006 .borrow()
5007 .as_ref()
5008 .map_or(false, |menu| menu.visible())
5009 }
5010
5011 fn render_context_menu(
5012 &self,
5013 cursor_position: DisplayPoint,
5014 style: &EditorStyle,
5015 max_height: Pixels,
5016 cx: &mut ViewContext<Editor>,
5017 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5018 self.context_menu.borrow().as_ref().map(|menu| {
5019 menu.render(
5020 cursor_position,
5021 style,
5022 max_height,
5023 self.workspace.as_ref().map(|(w, _)| w.clone()),
5024 cx,
5025 )
5026 })
5027 }
5028
5029 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
5030 cx.notify();
5031 self.completion_tasks.clear();
5032 self.context_menu.borrow_mut().take()
5033 }
5034
5035 fn show_snippet_choices(
5036 &mut self,
5037 choices: &Vec<String>,
5038 selection: Range<Anchor>,
5039 cx: &mut ViewContext<Self>,
5040 ) {
5041 if selection.start.buffer_id.is_none() {
5042 return;
5043 }
5044 let buffer_id = selection.start.buffer_id.unwrap();
5045 let buffer = self.buffer().read(cx).buffer(buffer_id);
5046 let id = post_inc(&mut self.next_completion_id);
5047
5048 if let Some(buffer) = buffer {
5049 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5050 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5051 ));
5052 }
5053 }
5054
5055 pub fn insert_snippet(
5056 &mut self,
5057 insertion_ranges: &[Range<usize>],
5058 snippet: Snippet,
5059 cx: &mut ViewContext<Self>,
5060 ) -> Result<()> {
5061 struct Tabstop<T> {
5062 is_end_tabstop: bool,
5063 ranges: Vec<Range<T>>,
5064 choices: Option<Vec<String>>,
5065 }
5066
5067 let tabstops = self.buffer.update(cx, |buffer, cx| {
5068 let snippet_text: Arc<str> = snippet.text.clone().into();
5069 buffer.edit(
5070 insertion_ranges
5071 .iter()
5072 .cloned()
5073 .map(|range| (range, snippet_text.clone())),
5074 Some(AutoindentMode::EachLine),
5075 cx,
5076 );
5077
5078 let snapshot = &*buffer.read(cx);
5079 let snippet = &snippet;
5080 snippet
5081 .tabstops
5082 .iter()
5083 .map(|tabstop| {
5084 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5085 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5086 });
5087 let mut tabstop_ranges = tabstop
5088 .ranges
5089 .iter()
5090 .flat_map(|tabstop_range| {
5091 let mut delta = 0_isize;
5092 insertion_ranges.iter().map(move |insertion_range| {
5093 let insertion_start = insertion_range.start as isize + delta;
5094 delta +=
5095 snippet.text.len() as isize - insertion_range.len() as isize;
5096
5097 let start = ((insertion_start + tabstop_range.start) as usize)
5098 .min(snapshot.len());
5099 let end = ((insertion_start + tabstop_range.end) as usize)
5100 .min(snapshot.len());
5101 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5102 })
5103 })
5104 .collect::<Vec<_>>();
5105 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5106
5107 Tabstop {
5108 is_end_tabstop,
5109 ranges: tabstop_ranges,
5110 choices: tabstop.choices.clone(),
5111 }
5112 })
5113 .collect::<Vec<_>>()
5114 });
5115 if let Some(tabstop) = tabstops.first() {
5116 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5117 s.select_ranges(tabstop.ranges.iter().cloned());
5118 });
5119
5120 if let Some(choices) = &tabstop.choices {
5121 if let Some(selection) = tabstop.ranges.first() {
5122 self.show_snippet_choices(choices, selection.clone(), cx)
5123 }
5124 }
5125
5126 // If we're already at the last tabstop and it's at the end of the snippet,
5127 // we're done, we don't need to keep the state around.
5128 if !tabstop.is_end_tabstop {
5129 let choices = tabstops
5130 .iter()
5131 .map(|tabstop| tabstop.choices.clone())
5132 .collect();
5133
5134 let ranges = tabstops
5135 .into_iter()
5136 .map(|tabstop| tabstop.ranges)
5137 .collect::<Vec<_>>();
5138
5139 self.snippet_stack.push(SnippetState {
5140 active_index: 0,
5141 ranges,
5142 choices,
5143 });
5144 }
5145
5146 // Check whether the just-entered snippet ends with an auto-closable bracket.
5147 if self.autoclose_regions.is_empty() {
5148 let snapshot = self.buffer.read(cx).snapshot(cx);
5149 for selection in &mut self.selections.all::<Point>(cx) {
5150 let selection_head = selection.head();
5151 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5152 continue;
5153 };
5154
5155 let mut bracket_pair = None;
5156 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5157 let prev_chars = snapshot
5158 .reversed_chars_at(selection_head)
5159 .collect::<String>();
5160 for (pair, enabled) in scope.brackets() {
5161 if enabled
5162 && pair.close
5163 && prev_chars.starts_with(pair.start.as_str())
5164 && next_chars.starts_with(pair.end.as_str())
5165 {
5166 bracket_pair = Some(pair.clone());
5167 break;
5168 }
5169 }
5170 if let Some(pair) = bracket_pair {
5171 let start = snapshot.anchor_after(selection_head);
5172 let end = snapshot.anchor_after(selection_head);
5173 self.autoclose_regions.push(AutocloseRegion {
5174 selection_id: selection.id,
5175 range: start..end,
5176 pair,
5177 });
5178 }
5179 }
5180 }
5181 }
5182 Ok(())
5183 }
5184
5185 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5186 self.move_to_snippet_tabstop(Bias::Right, cx)
5187 }
5188
5189 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5190 self.move_to_snippet_tabstop(Bias::Left, cx)
5191 }
5192
5193 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5194 if let Some(mut snippet) = self.snippet_stack.pop() {
5195 match bias {
5196 Bias::Left => {
5197 if snippet.active_index > 0 {
5198 snippet.active_index -= 1;
5199 } else {
5200 self.snippet_stack.push(snippet);
5201 return false;
5202 }
5203 }
5204 Bias::Right => {
5205 if snippet.active_index + 1 < snippet.ranges.len() {
5206 snippet.active_index += 1;
5207 } else {
5208 self.snippet_stack.push(snippet);
5209 return false;
5210 }
5211 }
5212 }
5213 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5214 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5215 s.select_anchor_ranges(current_ranges.iter().cloned())
5216 });
5217
5218 if let Some(choices) = &snippet.choices[snippet.active_index] {
5219 if let Some(selection) = current_ranges.first() {
5220 self.show_snippet_choices(&choices, selection.clone(), cx);
5221 }
5222 }
5223
5224 // If snippet state is not at the last tabstop, push it back on the stack
5225 if snippet.active_index + 1 < snippet.ranges.len() {
5226 self.snippet_stack.push(snippet);
5227 }
5228 return true;
5229 }
5230 }
5231
5232 false
5233 }
5234
5235 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5236 self.transact(cx, |this, cx| {
5237 this.select_all(&SelectAll, cx);
5238 this.insert("", cx);
5239 });
5240 }
5241
5242 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5243 self.transact(cx, |this, cx| {
5244 this.select_autoclose_pair(cx);
5245 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5246 if !this.linked_edit_ranges.is_empty() {
5247 let selections = this.selections.all::<MultiBufferPoint>(cx);
5248 let snapshot = this.buffer.read(cx).snapshot(cx);
5249
5250 for selection in selections.iter() {
5251 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5252 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5253 if selection_start.buffer_id != selection_end.buffer_id {
5254 continue;
5255 }
5256 if let Some(ranges) =
5257 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5258 {
5259 for (buffer, entries) in ranges {
5260 linked_ranges.entry(buffer).or_default().extend(entries);
5261 }
5262 }
5263 }
5264 }
5265
5266 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5267 if !this.selections.line_mode {
5268 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5269 for selection in &mut selections {
5270 if selection.is_empty() {
5271 let old_head = selection.head();
5272 let mut new_head =
5273 movement::left(&display_map, old_head.to_display_point(&display_map))
5274 .to_point(&display_map);
5275 if let Some((buffer, line_buffer_range)) = display_map
5276 .buffer_snapshot
5277 .buffer_line_for_row(MultiBufferRow(old_head.row))
5278 {
5279 let indent_size =
5280 buffer.indent_size_for_line(line_buffer_range.start.row);
5281 let indent_len = match indent_size.kind {
5282 IndentKind::Space => {
5283 buffer.settings_at(line_buffer_range.start, cx).tab_size
5284 }
5285 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5286 };
5287 if old_head.column <= indent_size.len && old_head.column > 0 {
5288 let indent_len = indent_len.get();
5289 new_head = cmp::min(
5290 new_head,
5291 MultiBufferPoint::new(
5292 old_head.row,
5293 ((old_head.column - 1) / indent_len) * indent_len,
5294 ),
5295 );
5296 }
5297 }
5298
5299 selection.set_head(new_head, SelectionGoal::None);
5300 }
5301 }
5302 }
5303
5304 this.signature_help_state.set_backspace_pressed(true);
5305 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5306 this.insert("", cx);
5307 let empty_str: Arc<str> = Arc::from("");
5308 for (buffer, edits) in linked_ranges {
5309 let snapshot = buffer.read(cx).snapshot();
5310 use text::ToPoint as TP;
5311
5312 let edits = edits
5313 .into_iter()
5314 .map(|range| {
5315 let end_point = TP::to_point(&range.end, &snapshot);
5316 let mut start_point = TP::to_point(&range.start, &snapshot);
5317
5318 if end_point == start_point {
5319 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5320 .saturating_sub(1);
5321 start_point = TP::to_point(&offset, &snapshot);
5322 };
5323
5324 (start_point..end_point, empty_str.clone())
5325 })
5326 .sorted_by_key(|(range, _)| range.start)
5327 .collect::<Vec<_>>();
5328 buffer.update(cx, |this, cx| {
5329 this.edit(edits, None, cx);
5330 })
5331 }
5332 this.refresh_inline_completion(true, false, cx);
5333 linked_editing_ranges::refresh_linked_ranges(this, cx);
5334 });
5335 }
5336
5337 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5338 self.transact(cx, |this, cx| {
5339 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5340 let line_mode = s.line_mode;
5341 s.move_with(|map, selection| {
5342 if selection.is_empty() && !line_mode {
5343 let cursor = movement::right(map, selection.head());
5344 selection.end = cursor;
5345 selection.reversed = true;
5346 selection.goal = SelectionGoal::None;
5347 }
5348 })
5349 });
5350 this.insert("", cx);
5351 this.refresh_inline_completion(true, false, cx);
5352 });
5353 }
5354
5355 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5356 if self.move_to_prev_snippet_tabstop(cx) {
5357 return;
5358 }
5359
5360 self.outdent(&Outdent, cx);
5361 }
5362
5363 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5364 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5365 return;
5366 }
5367
5368 let mut selections = self.selections.all_adjusted(cx);
5369 let buffer = self.buffer.read(cx);
5370 let snapshot = buffer.snapshot(cx);
5371 let rows_iter = selections.iter().map(|s| s.head().row);
5372 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5373
5374 let mut edits = Vec::new();
5375 let mut prev_edited_row = 0;
5376 let mut row_delta = 0;
5377 for selection in &mut selections {
5378 if selection.start.row != prev_edited_row {
5379 row_delta = 0;
5380 }
5381 prev_edited_row = selection.end.row;
5382
5383 // If the selection is non-empty, then increase the indentation of the selected lines.
5384 if !selection.is_empty() {
5385 row_delta =
5386 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5387 continue;
5388 }
5389
5390 // If the selection is empty and the cursor is in the leading whitespace before the
5391 // suggested indentation, then auto-indent the line.
5392 let cursor = selection.head();
5393 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5394 if let Some(suggested_indent) =
5395 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5396 {
5397 if cursor.column < suggested_indent.len
5398 && cursor.column <= current_indent.len
5399 && current_indent.len <= suggested_indent.len
5400 {
5401 selection.start = Point::new(cursor.row, suggested_indent.len);
5402 selection.end = selection.start;
5403 if row_delta == 0 {
5404 edits.extend(Buffer::edit_for_indent_size_adjustment(
5405 cursor.row,
5406 current_indent,
5407 suggested_indent,
5408 ));
5409 row_delta = suggested_indent.len - current_indent.len;
5410 }
5411 continue;
5412 }
5413 }
5414
5415 // Otherwise, insert a hard or soft tab.
5416 let settings = buffer.settings_at(cursor, cx);
5417 let tab_size = if settings.hard_tabs {
5418 IndentSize::tab()
5419 } else {
5420 let tab_size = settings.tab_size.get();
5421 let char_column = snapshot
5422 .text_for_range(Point::new(cursor.row, 0)..cursor)
5423 .flat_map(str::chars)
5424 .count()
5425 + row_delta as usize;
5426 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5427 IndentSize::spaces(chars_to_next_tab_stop)
5428 };
5429 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5430 selection.end = selection.start;
5431 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5432 row_delta += tab_size.len;
5433 }
5434
5435 self.transact(cx, |this, cx| {
5436 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5437 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5438 this.refresh_inline_completion(true, false, cx);
5439 });
5440 }
5441
5442 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5443 if self.read_only(cx) {
5444 return;
5445 }
5446 let mut selections = self.selections.all::<Point>(cx);
5447 let mut prev_edited_row = 0;
5448 let mut row_delta = 0;
5449 let mut edits = Vec::new();
5450 let buffer = self.buffer.read(cx);
5451 let snapshot = buffer.snapshot(cx);
5452 for selection in &mut selections {
5453 if selection.start.row != prev_edited_row {
5454 row_delta = 0;
5455 }
5456 prev_edited_row = selection.end.row;
5457
5458 row_delta =
5459 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5460 }
5461
5462 self.transact(cx, |this, cx| {
5463 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5464 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5465 });
5466 }
5467
5468 fn indent_selection(
5469 buffer: &MultiBuffer,
5470 snapshot: &MultiBufferSnapshot,
5471 selection: &mut Selection<Point>,
5472 edits: &mut Vec<(Range<Point>, String)>,
5473 delta_for_start_row: u32,
5474 cx: &AppContext,
5475 ) -> u32 {
5476 let settings = buffer.settings_at(selection.start, cx);
5477 let tab_size = settings.tab_size.get();
5478 let indent_kind = if settings.hard_tabs {
5479 IndentKind::Tab
5480 } else {
5481 IndentKind::Space
5482 };
5483 let mut start_row = selection.start.row;
5484 let mut end_row = selection.end.row + 1;
5485
5486 // If a selection ends at the beginning of a line, don't indent
5487 // that last line.
5488 if selection.end.column == 0 && selection.end.row > selection.start.row {
5489 end_row -= 1;
5490 }
5491
5492 // Avoid re-indenting a row that has already been indented by a
5493 // previous selection, but still update this selection's column
5494 // to reflect that indentation.
5495 if delta_for_start_row > 0 {
5496 start_row += 1;
5497 selection.start.column += delta_for_start_row;
5498 if selection.end.row == selection.start.row {
5499 selection.end.column += delta_for_start_row;
5500 }
5501 }
5502
5503 let mut delta_for_end_row = 0;
5504 let has_multiple_rows = start_row + 1 != end_row;
5505 for row in start_row..end_row {
5506 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5507 let indent_delta = match (current_indent.kind, indent_kind) {
5508 (IndentKind::Space, IndentKind::Space) => {
5509 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5510 IndentSize::spaces(columns_to_next_tab_stop)
5511 }
5512 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5513 (_, IndentKind::Tab) => IndentSize::tab(),
5514 };
5515
5516 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5517 0
5518 } else {
5519 selection.start.column
5520 };
5521 let row_start = Point::new(row, start);
5522 edits.push((
5523 row_start..row_start,
5524 indent_delta.chars().collect::<String>(),
5525 ));
5526
5527 // Update this selection's endpoints to reflect the indentation.
5528 if row == selection.start.row {
5529 selection.start.column += indent_delta.len;
5530 }
5531 if row == selection.end.row {
5532 selection.end.column += indent_delta.len;
5533 delta_for_end_row = indent_delta.len;
5534 }
5535 }
5536
5537 if selection.start.row == selection.end.row {
5538 delta_for_start_row + delta_for_end_row
5539 } else {
5540 delta_for_end_row
5541 }
5542 }
5543
5544 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5545 if self.read_only(cx) {
5546 return;
5547 }
5548 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5549 let selections = self.selections.all::<Point>(cx);
5550 let mut deletion_ranges = Vec::new();
5551 let mut last_outdent = None;
5552 {
5553 let buffer = self.buffer.read(cx);
5554 let snapshot = buffer.snapshot(cx);
5555 for selection in &selections {
5556 let settings = buffer.settings_at(selection.start, cx);
5557 let tab_size = settings.tab_size.get();
5558 let mut rows = selection.spanned_rows(false, &display_map);
5559
5560 // Avoid re-outdenting a row that has already been outdented by a
5561 // previous selection.
5562 if let Some(last_row) = last_outdent {
5563 if last_row == rows.start {
5564 rows.start = rows.start.next_row();
5565 }
5566 }
5567 let has_multiple_rows = rows.len() > 1;
5568 for row in rows.iter_rows() {
5569 let indent_size = snapshot.indent_size_for_line(row);
5570 if indent_size.len > 0 {
5571 let deletion_len = match indent_size.kind {
5572 IndentKind::Space => {
5573 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5574 if columns_to_prev_tab_stop == 0 {
5575 tab_size
5576 } else {
5577 columns_to_prev_tab_stop
5578 }
5579 }
5580 IndentKind::Tab => 1,
5581 };
5582 let start = if has_multiple_rows
5583 || deletion_len > selection.start.column
5584 || indent_size.len < selection.start.column
5585 {
5586 0
5587 } else {
5588 selection.start.column - deletion_len
5589 };
5590 deletion_ranges.push(
5591 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5592 );
5593 last_outdent = Some(row);
5594 }
5595 }
5596 }
5597 }
5598
5599 self.transact(cx, |this, cx| {
5600 this.buffer.update(cx, |buffer, cx| {
5601 let empty_str: Arc<str> = Arc::default();
5602 buffer.edit(
5603 deletion_ranges
5604 .into_iter()
5605 .map(|range| (range, empty_str.clone())),
5606 None,
5607 cx,
5608 );
5609 });
5610 let selections = this.selections.all::<usize>(cx);
5611 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5612 });
5613 }
5614
5615 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
5616 if self.read_only(cx) {
5617 return;
5618 }
5619 let selections = self
5620 .selections
5621 .all::<usize>(cx)
5622 .into_iter()
5623 .map(|s| s.range());
5624
5625 self.transact(cx, |this, cx| {
5626 this.buffer.update(cx, |buffer, cx| {
5627 buffer.autoindent_ranges(selections, cx);
5628 });
5629 let selections = this.selections.all::<usize>(cx);
5630 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5631 });
5632 }
5633
5634 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5635 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5636 let selections = self.selections.all::<Point>(cx);
5637
5638 let mut new_cursors = Vec::new();
5639 let mut edit_ranges = Vec::new();
5640 let mut selections = selections.iter().peekable();
5641 while let Some(selection) = selections.next() {
5642 let mut rows = selection.spanned_rows(false, &display_map);
5643 let goal_display_column = selection.head().to_display_point(&display_map).column();
5644
5645 // Accumulate contiguous regions of rows that we want to delete.
5646 while let Some(next_selection) = selections.peek() {
5647 let next_rows = next_selection.spanned_rows(false, &display_map);
5648 if next_rows.start <= rows.end {
5649 rows.end = next_rows.end;
5650 selections.next().unwrap();
5651 } else {
5652 break;
5653 }
5654 }
5655
5656 let buffer = &display_map.buffer_snapshot;
5657 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5658 let edit_end;
5659 let cursor_buffer_row;
5660 if buffer.max_point().row >= rows.end.0 {
5661 // If there's a line after the range, delete the \n from the end of the row range
5662 // and position the cursor on the next line.
5663 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5664 cursor_buffer_row = rows.end;
5665 } else {
5666 // If there isn't a line after the range, delete the \n from the line before the
5667 // start of the row range and position the cursor there.
5668 edit_start = edit_start.saturating_sub(1);
5669 edit_end = buffer.len();
5670 cursor_buffer_row = rows.start.previous_row();
5671 }
5672
5673 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5674 *cursor.column_mut() =
5675 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5676
5677 new_cursors.push((
5678 selection.id,
5679 buffer.anchor_after(cursor.to_point(&display_map)),
5680 ));
5681 edit_ranges.push(edit_start..edit_end);
5682 }
5683
5684 self.transact(cx, |this, cx| {
5685 let buffer = this.buffer.update(cx, |buffer, cx| {
5686 let empty_str: Arc<str> = Arc::default();
5687 buffer.edit(
5688 edit_ranges
5689 .into_iter()
5690 .map(|range| (range, empty_str.clone())),
5691 None,
5692 cx,
5693 );
5694 buffer.snapshot(cx)
5695 });
5696 let new_selections = new_cursors
5697 .into_iter()
5698 .map(|(id, cursor)| {
5699 let cursor = cursor.to_point(&buffer);
5700 Selection {
5701 id,
5702 start: cursor,
5703 end: cursor,
5704 reversed: false,
5705 goal: SelectionGoal::None,
5706 }
5707 })
5708 .collect();
5709
5710 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5711 s.select(new_selections);
5712 });
5713 });
5714 }
5715
5716 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5717 if self.read_only(cx) {
5718 return;
5719 }
5720 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5721 for selection in self.selections.all::<Point>(cx) {
5722 let start = MultiBufferRow(selection.start.row);
5723 // Treat single line selections as if they include the next line. Otherwise this action
5724 // would do nothing for single line selections individual cursors.
5725 let end = if selection.start.row == selection.end.row {
5726 MultiBufferRow(selection.start.row + 1)
5727 } else {
5728 MultiBufferRow(selection.end.row)
5729 };
5730
5731 if let Some(last_row_range) = row_ranges.last_mut() {
5732 if start <= last_row_range.end {
5733 last_row_range.end = end;
5734 continue;
5735 }
5736 }
5737 row_ranges.push(start..end);
5738 }
5739
5740 let snapshot = self.buffer.read(cx).snapshot(cx);
5741 let mut cursor_positions = Vec::new();
5742 for row_range in &row_ranges {
5743 let anchor = snapshot.anchor_before(Point::new(
5744 row_range.end.previous_row().0,
5745 snapshot.line_len(row_range.end.previous_row()),
5746 ));
5747 cursor_positions.push(anchor..anchor);
5748 }
5749
5750 self.transact(cx, |this, cx| {
5751 for row_range in row_ranges.into_iter().rev() {
5752 for row in row_range.iter_rows().rev() {
5753 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5754 let next_line_row = row.next_row();
5755 let indent = snapshot.indent_size_for_line(next_line_row);
5756 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5757
5758 let replace = if snapshot.line_len(next_line_row) > indent.len {
5759 " "
5760 } else {
5761 ""
5762 };
5763
5764 this.buffer.update(cx, |buffer, cx| {
5765 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5766 });
5767 }
5768 }
5769
5770 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5771 s.select_anchor_ranges(cursor_positions)
5772 });
5773 });
5774 }
5775
5776 pub fn sort_lines_case_sensitive(
5777 &mut self,
5778 _: &SortLinesCaseSensitive,
5779 cx: &mut ViewContext<Self>,
5780 ) {
5781 self.manipulate_lines(cx, |lines| lines.sort())
5782 }
5783
5784 pub fn sort_lines_case_insensitive(
5785 &mut self,
5786 _: &SortLinesCaseInsensitive,
5787 cx: &mut ViewContext<Self>,
5788 ) {
5789 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5790 }
5791
5792 pub fn unique_lines_case_insensitive(
5793 &mut self,
5794 _: &UniqueLinesCaseInsensitive,
5795 cx: &mut ViewContext<Self>,
5796 ) {
5797 self.manipulate_lines(cx, |lines| {
5798 let mut seen = HashSet::default();
5799 lines.retain(|line| seen.insert(line.to_lowercase()));
5800 })
5801 }
5802
5803 pub fn unique_lines_case_sensitive(
5804 &mut self,
5805 _: &UniqueLinesCaseSensitive,
5806 cx: &mut ViewContext<Self>,
5807 ) {
5808 self.manipulate_lines(cx, |lines| {
5809 let mut seen = HashSet::default();
5810 lines.retain(|line| seen.insert(*line));
5811 })
5812 }
5813
5814 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
5815 let mut revert_changes = HashMap::default();
5816 let snapshot = self.snapshot(cx);
5817 for hunk in hunks_for_ranges(
5818 Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
5819 &snapshot,
5820 ) {
5821 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
5822 }
5823 if !revert_changes.is_empty() {
5824 self.transact(cx, |editor, cx| {
5825 editor.revert(revert_changes, cx);
5826 });
5827 }
5828 }
5829
5830 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
5831 let Some(project) = self.project.clone() else {
5832 return;
5833 };
5834 self.reload(project, cx).detach_and_notify_err(cx);
5835 }
5836
5837 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
5838 let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
5839 if !revert_changes.is_empty() {
5840 self.transact(cx, |editor, cx| {
5841 editor.revert(revert_changes, cx);
5842 });
5843 }
5844 }
5845
5846 fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
5847 let snapshot = self.buffer.read(cx).read(cx);
5848 if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
5849 drop(snapshot);
5850 let mut revert_changes = HashMap::default();
5851 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
5852 if !revert_changes.is_empty() {
5853 self.revert(revert_changes, cx)
5854 }
5855 }
5856 }
5857
5858 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
5859 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
5860 let project_path = buffer.read(cx).project_path(cx)?;
5861 let project = self.project.as_ref()?.read(cx);
5862 let entry = project.entry_for_path(&project_path, cx)?;
5863 let parent = match &entry.canonical_path {
5864 Some(canonical_path) => canonical_path.to_path_buf(),
5865 None => project.absolute_path(&project_path, cx)?,
5866 }
5867 .parent()?
5868 .to_path_buf();
5869 Some(parent)
5870 }) {
5871 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
5872 }
5873 }
5874
5875 fn gather_revert_changes(
5876 &mut self,
5877 selections: &[Selection<Point>],
5878 cx: &mut ViewContext<'_, Editor>,
5879 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
5880 let mut revert_changes = HashMap::default();
5881 let snapshot = self.snapshot(cx);
5882 for hunk in hunks_for_selections(&snapshot, selections) {
5883 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
5884 }
5885 revert_changes
5886 }
5887
5888 pub fn prepare_revert_change(
5889 &mut self,
5890 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
5891 hunk: &MultiBufferDiffHunk,
5892 cx: &AppContext,
5893 ) -> Option<()> {
5894 let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
5895 let buffer = buffer.read(cx);
5896 let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
5897 let original_text = change_set
5898 .read(cx)
5899 .base_text
5900 .as_ref()?
5901 .read(cx)
5902 .as_rope()
5903 .slice(hunk.diff_base_byte_range.clone());
5904 let buffer_snapshot = buffer.snapshot();
5905 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
5906 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
5907 probe
5908 .0
5909 .start
5910 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
5911 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
5912 }) {
5913 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
5914 Some(())
5915 } else {
5916 None
5917 }
5918 }
5919
5920 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
5921 self.manipulate_lines(cx, |lines| lines.reverse())
5922 }
5923
5924 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
5925 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
5926 }
5927
5928 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
5929 where
5930 Fn: FnMut(&mut Vec<&str>),
5931 {
5932 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5933 let buffer = self.buffer.read(cx).snapshot(cx);
5934
5935 let mut edits = Vec::new();
5936
5937 let selections = self.selections.all::<Point>(cx);
5938 let mut selections = selections.iter().peekable();
5939 let mut contiguous_row_selections = Vec::new();
5940 let mut new_selections = Vec::new();
5941 let mut added_lines = 0;
5942 let mut removed_lines = 0;
5943
5944 while let Some(selection) = selections.next() {
5945 let (start_row, end_row) = consume_contiguous_rows(
5946 &mut contiguous_row_selections,
5947 selection,
5948 &display_map,
5949 &mut selections,
5950 );
5951
5952 let start_point = Point::new(start_row.0, 0);
5953 let end_point = Point::new(
5954 end_row.previous_row().0,
5955 buffer.line_len(end_row.previous_row()),
5956 );
5957 let text = buffer
5958 .text_for_range(start_point..end_point)
5959 .collect::<String>();
5960
5961 let mut lines = text.split('\n').collect_vec();
5962
5963 let lines_before = lines.len();
5964 callback(&mut lines);
5965 let lines_after = lines.len();
5966
5967 edits.push((start_point..end_point, lines.join("\n")));
5968
5969 // Selections must change based on added and removed line count
5970 let start_row =
5971 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
5972 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
5973 new_selections.push(Selection {
5974 id: selection.id,
5975 start: start_row,
5976 end: end_row,
5977 goal: SelectionGoal::None,
5978 reversed: selection.reversed,
5979 });
5980
5981 if lines_after > lines_before {
5982 added_lines += lines_after - lines_before;
5983 } else if lines_before > lines_after {
5984 removed_lines += lines_before - lines_after;
5985 }
5986 }
5987
5988 self.transact(cx, |this, cx| {
5989 let buffer = this.buffer.update(cx, |buffer, cx| {
5990 buffer.edit(edits, None, cx);
5991 buffer.snapshot(cx)
5992 });
5993
5994 // Recalculate offsets on newly edited buffer
5995 let new_selections = new_selections
5996 .iter()
5997 .map(|s| {
5998 let start_point = Point::new(s.start.0, 0);
5999 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6000 Selection {
6001 id: s.id,
6002 start: buffer.point_to_offset(start_point),
6003 end: buffer.point_to_offset(end_point),
6004 goal: s.goal,
6005 reversed: s.reversed,
6006 }
6007 })
6008 .collect();
6009
6010 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6011 s.select(new_selections);
6012 });
6013
6014 this.request_autoscroll(Autoscroll::fit(), cx);
6015 });
6016 }
6017
6018 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6019 self.manipulate_text(cx, |text| text.to_uppercase())
6020 }
6021
6022 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6023 self.manipulate_text(cx, |text| text.to_lowercase())
6024 }
6025
6026 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6027 self.manipulate_text(cx, |text| {
6028 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6029 // https://github.com/rutrum/convert-case/issues/16
6030 text.split('\n')
6031 .map(|line| line.to_case(Case::Title))
6032 .join("\n")
6033 })
6034 }
6035
6036 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6037 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6038 }
6039
6040 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6041 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6042 }
6043
6044 pub fn convert_to_upper_camel_case(
6045 &mut self,
6046 _: &ConvertToUpperCamelCase,
6047 cx: &mut ViewContext<Self>,
6048 ) {
6049 self.manipulate_text(cx, |text| {
6050 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6051 // https://github.com/rutrum/convert-case/issues/16
6052 text.split('\n')
6053 .map(|line| line.to_case(Case::UpperCamel))
6054 .join("\n")
6055 })
6056 }
6057
6058 pub fn convert_to_lower_camel_case(
6059 &mut self,
6060 _: &ConvertToLowerCamelCase,
6061 cx: &mut ViewContext<Self>,
6062 ) {
6063 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6064 }
6065
6066 pub fn convert_to_opposite_case(
6067 &mut self,
6068 _: &ConvertToOppositeCase,
6069 cx: &mut ViewContext<Self>,
6070 ) {
6071 self.manipulate_text(cx, |text| {
6072 text.chars()
6073 .fold(String::with_capacity(text.len()), |mut t, c| {
6074 if c.is_uppercase() {
6075 t.extend(c.to_lowercase());
6076 } else {
6077 t.extend(c.to_uppercase());
6078 }
6079 t
6080 })
6081 })
6082 }
6083
6084 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6085 where
6086 Fn: FnMut(&str) -> String,
6087 {
6088 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6089 let buffer = self.buffer.read(cx).snapshot(cx);
6090
6091 let mut new_selections = Vec::new();
6092 let mut edits = Vec::new();
6093 let mut selection_adjustment = 0i32;
6094
6095 for selection in self.selections.all::<usize>(cx) {
6096 let selection_is_empty = selection.is_empty();
6097
6098 let (start, end) = if selection_is_empty {
6099 let word_range = movement::surrounding_word(
6100 &display_map,
6101 selection.start.to_display_point(&display_map),
6102 );
6103 let start = word_range.start.to_offset(&display_map, Bias::Left);
6104 let end = word_range.end.to_offset(&display_map, Bias::Left);
6105 (start, end)
6106 } else {
6107 (selection.start, selection.end)
6108 };
6109
6110 let text = buffer.text_for_range(start..end).collect::<String>();
6111 let old_length = text.len() as i32;
6112 let text = callback(&text);
6113
6114 new_selections.push(Selection {
6115 start: (start as i32 - selection_adjustment) as usize,
6116 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6117 goal: SelectionGoal::None,
6118 ..selection
6119 });
6120
6121 selection_adjustment += old_length - text.len() as i32;
6122
6123 edits.push((start..end, text));
6124 }
6125
6126 self.transact(cx, |this, cx| {
6127 this.buffer.update(cx, |buffer, cx| {
6128 buffer.edit(edits, None, cx);
6129 });
6130
6131 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6132 s.select(new_selections);
6133 });
6134
6135 this.request_autoscroll(Autoscroll::fit(), cx);
6136 });
6137 }
6138
6139 pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
6140 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6141 let buffer = &display_map.buffer_snapshot;
6142 let selections = self.selections.all::<Point>(cx);
6143
6144 let mut edits = Vec::new();
6145 let mut selections_iter = selections.iter().peekable();
6146 while let Some(selection) = selections_iter.next() {
6147 let mut rows = selection.spanned_rows(false, &display_map);
6148 // duplicate line-wise
6149 if whole_lines || selection.start == selection.end {
6150 // Avoid duplicating the same lines twice.
6151 while let Some(next_selection) = selections_iter.peek() {
6152 let next_rows = next_selection.spanned_rows(false, &display_map);
6153 if next_rows.start < rows.end {
6154 rows.end = next_rows.end;
6155 selections_iter.next().unwrap();
6156 } else {
6157 break;
6158 }
6159 }
6160
6161 // Copy the text from the selected row region and splice it either at the start
6162 // or end of the region.
6163 let start = Point::new(rows.start.0, 0);
6164 let end = Point::new(
6165 rows.end.previous_row().0,
6166 buffer.line_len(rows.end.previous_row()),
6167 );
6168 let text = buffer
6169 .text_for_range(start..end)
6170 .chain(Some("\n"))
6171 .collect::<String>();
6172 let insert_location = if upwards {
6173 Point::new(rows.end.0, 0)
6174 } else {
6175 start
6176 };
6177 edits.push((insert_location..insert_location, text));
6178 } else {
6179 // duplicate character-wise
6180 let start = selection.start;
6181 let end = selection.end;
6182 let text = buffer.text_for_range(start..end).collect::<String>();
6183 edits.push((selection.end..selection.end, text));
6184 }
6185 }
6186
6187 self.transact(cx, |this, cx| {
6188 this.buffer.update(cx, |buffer, cx| {
6189 buffer.edit(edits, None, cx);
6190 });
6191
6192 this.request_autoscroll(Autoscroll::fit(), cx);
6193 });
6194 }
6195
6196 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6197 self.duplicate(true, true, cx);
6198 }
6199
6200 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6201 self.duplicate(false, true, cx);
6202 }
6203
6204 pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
6205 self.duplicate(false, false, cx);
6206 }
6207
6208 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6209 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6210 let buffer = self.buffer.read(cx).snapshot(cx);
6211
6212 let mut edits = Vec::new();
6213 let mut unfold_ranges = Vec::new();
6214 let mut refold_creases = Vec::new();
6215
6216 let selections = self.selections.all::<Point>(cx);
6217 let mut selections = selections.iter().peekable();
6218 let mut contiguous_row_selections = Vec::new();
6219 let mut new_selections = Vec::new();
6220
6221 while let Some(selection) = selections.next() {
6222 // Find all the selections that span a contiguous row range
6223 let (start_row, end_row) = consume_contiguous_rows(
6224 &mut contiguous_row_selections,
6225 selection,
6226 &display_map,
6227 &mut selections,
6228 );
6229
6230 // Move the text spanned by the row range to be before the line preceding the row range
6231 if start_row.0 > 0 {
6232 let range_to_move = Point::new(
6233 start_row.previous_row().0,
6234 buffer.line_len(start_row.previous_row()),
6235 )
6236 ..Point::new(
6237 end_row.previous_row().0,
6238 buffer.line_len(end_row.previous_row()),
6239 );
6240 let insertion_point = display_map
6241 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6242 .0;
6243
6244 // Don't move lines across excerpts
6245 if buffer
6246 .excerpt_boundaries_in_range((
6247 Bound::Excluded(insertion_point),
6248 Bound::Included(range_to_move.end),
6249 ))
6250 .next()
6251 .is_none()
6252 {
6253 let text = buffer
6254 .text_for_range(range_to_move.clone())
6255 .flat_map(|s| s.chars())
6256 .skip(1)
6257 .chain(['\n'])
6258 .collect::<String>();
6259
6260 edits.push((
6261 buffer.anchor_after(range_to_move.start)
6262 ..buffer.anchor_before(range_to_move.end),
6263 String::new(),
6264 ));
6265 let insertion_anchor = buffer.anchor_after(insertion_point);
6266 edits.push((insertion_anchor..insertion_anchor, text));
6267
6268 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6269
6270 // Move selections up
6271 new_selections.extend(contiguous_row_selections.drain(..).map(
6272 |mut selection| {
6273 selection.start.row -= row_delta;
6274 selection.end.row -= row_delta;
6275 selection
6276 },
6277 ));
6278
6279 // Move folds up
6280 unfold_ranges.push(range_to_move.clone());
6281 for fold in display_map.folds_in_range(
6282 buffer.anchor_before(range_to_move.start)
6283 ..buffer.anchor_after(range_to_move.end),
6284 ) {
6285 let mut start = fold.range.start.to_point(&buffer);
6286 let mut end = fold.range.end.to_point(&buffer);
6287 start.row -= row_delta;
6288 end.row -= row_delta;
6289 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6290 }
6291 }
6292 }
6293
6294 // If we didn't move line(s), preserve the existing selections
6295 new_selections.append(&mut contiguous_row_selections);
6296 }
6297
6298 self.transact(cx, |this, cx| {
6299 this.unfold_ranges(&unfold_ranges, true, true, cx);
6300 this.buffer.update(cx, |buffer, cx| {
6301 for (range, text) in edits {
6302 buffer.edit([(range, text)], None, cx);
6303 }
6304 });
6305 this.fold_creases(refold_creases, true, cx);
6306 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6307 s.select(new_selections);
6308 })
6309 });
6310 }
6311
6312 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6313 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6314 let buffer = self.buffer.read(cx).snapshot(cx);
6315
6316 let mut edits = Vec::new();
6317 let mut unfold_ranges = Vec::new();
6318 let mut refold_creases = Vec::new();
6319
6320 let selections = self.selections.all::<Point>(cx);
6321 let mut selections = selections.iter().peekable();
6322 let mut contiguous_row_selections = Vec::new();
6323 let mut new_selections = Vec::new();
6324
6325 while let Some(selection) = selections.next() {
6326 // Find all the selections that span a contiguous row range
6327 let (start_row, end_row) = consume_contiguous_rows(
6328 &mut contiguous_row_selections,
6329 selection,
6330 &display_map,
6331 &mut selections,
6332 );
6333
6334 // Move the text spanned by the row range to be after the last line of the row range
6335 if end_row.0 <= buffer.max_point().row {
6336 let range_to_move =
6337 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6338 let insertion_point = display_map
6339 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6340 .0;
6341
6342 // Don't move lines across excerpt boundaries
6343 if buffer
6344 .excerpt_boundaries_in_range((
6345 Bound::Excluded(range_to_move.start),
6346 Bound::Included(insertion_point),
6347 ))
6348 .next()
6349 .is_none()
6350 {
6351 let mut text = String::from("\n");
6352 text.extend(buffer.text_for_range(range_to_move.clone()));
6353 text.pop(); // Drop trailing newline
6354 edits.push((
6355 buffer.anchor_after(range_to_move.start)
6356 ..buffer.anchor_before(range_to_move.end),
6357 String::new(),
6358 ));
6359 let insertion_anchor = buffer.anchor_after(insertion_point);
6360 edits.push((insertion_anchor..insertion_anchor, text));
6361
6362 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6363
6364 // Move selections down
6365 new_selections.extend(contiguous_row_selections.drain(..).map(
6366 |mut selection| {
6367 selection.start.row += row_delta;
6368 selection.end.row += row_delta;
6369 selection
6370 },
6371 ));
6372
6373 // Move folds down
6374 unfold_ranges.push(range_to_move.clone());
6375 for fold in display_map.folds_in_range(
6376 buffer.anchor_before(range_to_move.start)
6377 ..buffer.anchor_after(range_to_move.end),
6378 ) {
6379 let mut start = fold.range.start.to_point(&buffer);
6380 let mut end = fold.range.end.to_point(&buffer);
6381 start.row += row_delta;
6382 end.row += row_delta;
6383 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6384 }
6385 }
6386 }
6387
6388 // If we didn't move line(s), preserve the existing selections
6389 new_selections.append(&mut contiguous_row_selections);
6390 }
6391
6392 self.transact(cx, |this, cx| {
6393 this.unfold_ranges(&unfold_ranges, true, true, cx);
6394 this.buffer.update(cx, |buffer, cx| {
6395 for (range, text) in edits {
6396 buffer.edit([(range, text)], None, cx);
6397 }
6398 });
6399 this.fold_creases(refold_creases, true, cx);
6400 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6401 });
6402 }
6403
6404 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6405 let text_layout_details = &self.text_layout_details(cx);
6406 self.transact(cx, |this, cx| {
6407 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6408 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6409 let line_mode = s.line_mode;
6410 s.move_with(|display_map, selection| {
6411 if !selection.is_empty() || line_mode {
6412 return;
6413 }
6414
6415 let mut head = selection.head();
6416 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6417 if head.column() == display_map.line_len(head.row()) {
6418 transpose_offset = display_map
6419 .buffer_snapshot
6420 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6421 }
6422
6423 if transpose_offset == 0 {
6424 return;
6425 }
6426
6427 *head.column_mut() += 1;
6428 head = display_map.clip_point(head, Bias::Right);
6429 let goal = SelectionGoal::HorizontalPosition(
6430 display_map
6431 .x_for_display_point(head, text_layout_details)
6432 .into(),
6433 );
6434 selection.collapse_to(head, goal);
6435
6436 let transpose_start = display_map
6437 .buffer_snapshot
6438 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6439 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6440 let transpose_end = display_map
6441 .buffer_snapshot
6442 .clip_offset(transpose_offset + 1, Bias::Right);
6443 if let Some(ch) =
6444 display_map.buffer_snapshot.chars_at(transpose_start).next()
6445 {
6446 edits.push((transpose_start..transpose_offset, String::new()));
6447 edits.push((transpose_end..transpose_end, ch.to_string()));
6448 }
6449 }
6450 });
6451 edits
6452 });
6453 this.buffer
6454 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6455 let selections = this.selections.all::<usize>(cx);
6456 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6457 s.select(selections);
6458 });
6459 });
6460 }
6461
6462 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6463 self.rewrap_impl(IsVimMode::No, cx)
6464 }
6465
6466 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
6467 let buffer = self.buffer.read(cx).snapshot(cx);
6468 let selections = self.selections.all::<Point>(cx);
6469 let mut selections = selections.iter().peekable();
6470
6471 let mut edits = Vec::new();
6472 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6473
6474 while let Some(selection) = selections.next() {
6475 let mut start_row = selection.start.row;
6476 let mut end_row = selection.end.row;
6477
6478 // Skip selections that overlap with a range that has already been rewrapped.
6479 let selection_range = start_row..end_row;
6480 if rewrapped_row_ranges
6481 .iter()
6482 .any(|range| range.overlaps(&selection_range))
6483 {
6484 continue;
6485 }
6486
6487 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
6488
6489 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6490 match language_scope.language_name().0.as_ref() {
6491 "Markdown" | "Plain Text" => {
6492 should_rewrap = true;
6493 }
6494 _ => {}
6495 }
6496 }
6497
6498 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
6499
6500 // Since not all lines in the selection may be at the same indent
6501 // level, choose the indent size that is the most common between all
6502 // of the lines.
6503 //
6504 // If there is a tie, we use the deepest indent.
6505 let (indent_size, indent_end) = {
6506 let mut indent_size_occurrences = HashMap::default();
6507 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6508
6509 for row in start_row..=end_row {
6510 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6511 rows_by_indent_size.entry(indent).or_default().push(row);
6512 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6513 }
6514
6515 let indent_size = indent_size_occurrences
6516 .into_iter()
6517 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
6518 .map(|(indent, _)| indent)
6519 .unwrap_or_default();
6520 let row = rows_by_indent_size[&indent_size][0];
6521 let indent_end = Point::new(row, indent_size.len);
6522
6523 (indent_size, indent_end)
6524 };
6525
6526 let mut line_prefix = indent_size.chars().collect::<String>();
6527
6528 if let Some(comment_prefix) =
6529 buffer
6530 .language_scope_at(selection.head())
6531 .and_then(|language| {
6532 language
6533 .line_comment_prefixes()
6534 .iter()
6535 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6536 .cloned()
6537 })
6538 {
6539 line_prefix.push_str(&comment_prefix);
6540 should_rewrap = true;
6541 }
6542
6543 if !should_rewrap {
6544 continue;
6545 }
6546
6547 if selection.is_empty() {
6548 'expand_upwards: while start_row > 0 {
6549 let prev_row = start_row - 1;
6550 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6551 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6552 {
6553 start_row = prev_row;
6554 } else {
6555 break 'expand_upwards;
6556 }
6557 }
6558
6559 'expand_downwards: while end_row < buffer.max_point().row {
6560 let next_row = end_row + 1;
6561 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6562 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6563 {
6564 end_row = next_row;
6565 } else {
6566 break 'expand_downwards;
6567 }
6568 }
6569 }
6570
6571 let start = Point::new(start_row, 0);
6572 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6573 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6574 let Some(lines_without_prefixes) = selection_text
6575 .lines()
6576 .map(|line| {
6577 line.strip_prefix(&line_prefix)
6578 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6579 .ok_or_else(|| {
6580 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6581 })
6582 })
6583 .collect::<Result<Vec<_>, _>>()
6584 .log_err()
6585 else {
6586 continue;
6587 };
6588
6589 let wrap_column = buffer
6590 .settings_at(Point::new(start_row, 0), cx)
6591 .preferred_line_length as usize;
6592 let wrapped_text = wrap_with_prefix(
6593 line_prefix,
6594 lines_without_prefixes.join(" "),
6595 wrap_column,
6596 tab_size,
6597 );
6598
6599 // TODO: should always use char-based diff while still supporting cursor behavior that
6600 // matches vim.
6601 let diff = match is_vim_mode {
6602 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
6603 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
6604 };
6605 let mut offset = start.to_offset(&buffer);
6606 let mut moved_since_edit = true;
6607
6608 for change in diff.iter_all_changes() {
6609 let value = change.value();
6610 match change.tag() {
6611 ChangeTag::Equal => {
6612 offset += value.len();
6613 moved_since_edit = true;
6614 }
6615 ChangeTag::Delete => {
6616 let start = buffer.anchor_after(offset);
6617 let end = buffer.anchor_before(offset + value.len());
6618
6619 if moved_since_edit {
6620 edits.push((start..end, String::new()));
6621 } else {
6622 edits.last_mut().unwrap().0.end = end;
6623 }
6624
6625 offset += value.len();
6626 moved_since_edit = false;
6627 }
6628 ChangeTag::Insert => {
6629 if moved_since_edit {
6630 let anchor = buffer.anchor_after(offset);
6631 edits.push((anchor..anchor, value.to_string()));
6632 } else {
6633 edits.last_mut().unwrap().1.push_str(value);
6634 }
6635
6636 moved_since_edit = false;
6637 }
6638 }
6639 }
6640
6641 rewrapped_row_ranges.push(start_row..=end_row);
6642 }
6643
6644 self.buffer
6645 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6646 }
6647
6648 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
6649 let mut text = String::new();
6650 let buffer = self.buffer.read(cx).snapshot(cx);
6651 let mut selections = self.selections.all::<Point>(cx);
6652 let mut clipboard_selections = Vec::with_capacity(selections.len());
6653 {
6654 let max_point = buffer.max_point();
6655 let mut is_first = true;
6656 for selection in &mut selections {
6657 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6658 if is_entire_line {
6659 selection.start = Point::new(selection.start.row, 0);
6660 if !selection.is_empty() && selection.end.column == 0 {
6661 selection.end = cmp::min(max_point, selection.end);
6662 } else {
6663 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6664 }
6665 selection.goal = SelectionGoal::None;
6666 }
6667 if is_first {
6668 is_first = false;
6669 } else {
6670 text += "\n";
6671 }
6672 let mut len = 0;
6673 for chunk in buffer.text_for_range(selection.start..selection.end) {
6674 text.push_str(chunk);
6675 len += chunk.len();
6676 }
6677 clipboard_selections.push(ClipboardSelection {
6678 len,
6679 is_entire_line,
6680 first_line_indent: buffer
6681 .indent_size_for_line(MultiBufferRow(selection.start.row))
6682 .len,
6683 });
6684 }
6685 }
6686
6687 self.transact(cx, |this, cx| {
6688 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6689 s.select(selections);
6690 });
6691 this.insert("", cx);
6692 });
6693 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
6694 }
6695
6696 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6697 let item = self.cut_common(cx);
6698 cx.write_to_clipboard(item);
6699 }
6700
6701 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
6702 self.change_selections(None, cx, |s| {
6703 s.move_with(|snapshot, sel| {
6704 if sel.is_empty() {
6705 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
6706 }
6707 });
6708 });
6709 let item = self.cut_common(cx);
6710 cx.set_global(KillRing(item))
6711 }
6712
6713 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
6714 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
6715 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
6716 (kill_ring.text().to_string(), kill_ring.metadata_json())
6717 } else {
6718 return;
6719 }
6720 } else {
6721 return;
6722 };
6723 self.do_paste(&text, metadata, false, cx);
6724 }
6725
6726 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6727 let selections = self.selections.all::<Point>(cx);
6728 let buffer = self.buffer.read(cx).read(cx);
6729 let mut text = String::new();
6730
6731 let mut clipboard_selections = Vec::with_capacity(selections.len());
6732 {
6733 let max_point = buffer.max_point();
6734 let mut is_first = true;
6735 for selection in selections.iter() {
6736 let mut start = selection.start;
6737 let mut end = selection.end;
6738 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6739 if is_entire_line {
6740 start = Point::new(start.row, 0);
6741 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6742 }
6743 if is_first {
6744 is_first = false;
6745 } else {
6746 text += "\n";
6747 }
6748 let mut len = 0;
6749 for chunk in buffer.text_for_range(start..end) {
6750 text.push_str(chunk);
6751 len += chunk.len();
6752 }
6753 clipboard_selections.push(ClipboardSelection {
6754 len,
6755 is_entire_line,
6756 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6757 });
6758 }
6759 }
6760
6761 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6762 text,
6763 clipboard_selections,
6764 ));
6765 }
6766
6767 pub fn do_paste(
6768 &mut self,
6769 text: &String,
6770 clipboard_selections: Option<Vec<ClipboardSelection>>,
6771 handle_entire_lines: bool,
6772 cx: &mut ViewContext<Self>,
6773 ) {
6774 if self.read_only(cx) {
6775 return;
6776 }
6777
6778 let clipboard_text = Cow::Borrowed(text);
6779
6780 self.transact(cx, |this, cx| {
6781 if let Some(mut clipboard_selections) = clipboard_selections {
6782 let old_selections = this.selections.all::<usize>(cx);
6783 let all_selections_were_entire_line =
6784 clipboard_selections.iter().all(|s| s.is_entire_line);
6785 let first_selection_indent_column =
6786 clipboard_selections.first().map(|s| s.first_line_indent);
6787 if clipboard_selections.len() != old_selections.len() {
6788 clipboard_selections.drain(..);
6789 }
6790 let cursor_offset = this.selections.last::<usize>(cx).head();
6791 let mut auto_indent_on_paste = true;
6792
6793 this.buffer.update(cx, |buffer, cx| {
6794 let snapshot = buffer.read(cx);
6795 auto_indent_on_paste =
6796 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
6797
6798 let mut start_offset = 0;
6799 let mut edits = Vec::new();
6800 let mut original_indent_columns = Vec::new();
6801 for (ix, selection) in old_selections.iter().enumerate() {
6802 let to_insert;
6803 let entire_line;
6804 let original_indent_column;
6805 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6806 let end_offset = start_offset + clipboard_selection.len;
6807 to_insert = &clipboard_text[start_offset..end_offset];
6808 entire_line = clipboard_selection.is_entire_line;
6809 start_offset = end_offset + 1;
6810 original_indent_column = Some(clipboard_selection.first_line_indent);
6811 } else {
6812 to_insert = clipboard_text.as_str();
6813 entire_line = all_selections_were_entire_line;
6814 original_indent_column = first_selection_indent_column
6815 }
6816
6817 // If the corresponding selection was empty when this slice of the
6818 // clipboard text was written, then the entire line containing the
6819 // selection was copied. If this selection is also currently empty,
6820 // then paste the line before the current line of the buffer.
6821 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6822 let column = selection.start.to_point(&snapshot).column as usize;
6823 let line_start = selection.start - column;
6824 line_start..line_start
6825 } else {
6826 selection.range()
6827 };
6828
6829 edits.push((range, to_insert));
6830 original_indent_columns.extend(original_indent_column);
6831 }
6832 drop(snapshot);
6833
6834 buffer.edit(
6835 edits,
6836 if auto_indent_on_paste {
6837 Some(AutoindentMode::Block {
6838 original_indent_columns,
6839 })
6840 } else {
6841 None
6842 },
6843 cx,
6844 );
6845 });
6846
6847 let selections = this.selections.all::<usize>(cx);
6848 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6849 } else {
6850 this.insert(&clipboard_text, cx);
6851 }
6852 });
6853 }
6854
6855 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
6856 if let Some(item) = cx.read_from_clipboard() {
6857 let entries = item.entries();
6858
6859 match entries.first() {
6860 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
6861 // of all the pasted entries.
6862 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
6863 .do_paste(
6864 clipboard_string.text(),
6865 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
6866 true,
6867 cx,
6868 ),
6869 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
6870 }
6871 }
6872 }
6873
6874 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
6875 if self.read_only(cx) {
6876 return;
6877 }
6878
6879 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
6880 if let Some((selections, _)) =
6881 self.selection_history.transaction(transaction_id).cloned()
6882 {
6883 self.change_selections(None, cx, |s| {
6884 s.select_anchors(selections.to_vec());
6885 });
6886 }
6887 self.request_autoscroll(Autoscroll::fit(), cx);
6888 self.unmark_text(cx);
6889 self.refresh_inline_completion(true, false, cx);
6890 cx.emit(EditorEvent::Edited { transaction_id });
6891 cx.emit(EditorEvent::TransactionUndone { transaction_id });
6892 }
6893 }
6894
6895 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
6896 if self.read_only(cx) {
6897 return;
6898 }
6899
6900 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
6901 if let Some((_, Some(selections))) =
6902 self.selection_history.transaction(transaction_id).cloned()
6903 {
6904 self.change_selections(None, cx, |s| {
6905 s.select_anchors(selections.to_vec());
6906 });
6907 }
6908 self.request_autoscroll(Autoscroll::fit(), cx);
6909 self.unmark_text(cx);
6910 self.refresh_inline_completion(true, false, cx);
6911 cx.emit(EditorEvent::Edited { transaction_id });
6912 }
6913 }
6914
6915 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
6916 self.buffer
6917 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
6918 }
6919
6920 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
6921 self.buffer
6922 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
6923 }
6924
6925 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
6926 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6927 let line_mode = s.line_mode;
6928 s.move_with(|map, selection| {
6929 let cursor = if selection.is_empty() && !line_mode {
6930 movement::left(map, selection.start)
6931 } else {
6932 selection.start
6933 };
6934 selection.collapse_to(cursor, SelectionGoal::None);
6935 });
6936 })
6937 }
6938
6939 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
6940 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6941 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
6942 })
6943 }
6944
6945 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
6946 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6947 let line_mode = s.line_mode;
6948 s.move_with(|map, selection| {
6949 let cursor = if selection.is_empty() && !line_mode {
6950 movement::right(map, selection.end)
6951 } else {
6952 selection.end
6953 };
6954 selection.collapse_to(cursor, SelectionGoal::None)
6955 });
6956 })
6957 }
6958
6959 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
6960 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6961 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
6962 })
6963 }
6964
6965 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
6966 if self.take_rename(true, cx).is_some() {
6967 return;
6968 }
6969
6970 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6971 cx.propagate();
6972 return;
6973 }
6974
6975 let text_layout_details = &self.text_layout_details(cx);
6976 let selection_count = self.selections.count();
6977 let first_selection = self.selections.first_anchor();
6978
6979 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6980 let line_mode = s.line_mode;
6981 s.move_with(|map, selection| {
6982 if !selection.is_empty() && !line_mode {
6983 selection.goal = SelectionGoal::None;
6984 }
6985 let (cursor, goal) = movement::up(
6986 map,
6987 selection.start,
6988 selection.goal,
6989 false,
6990 text_layout_details,
6991 );
6992 selection.collapse_to(cursor, goal);
6993 });
6994 });
6995
6996 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
6997 {
6998 cx.propagate();
6999 }
7000 }
7001
7002 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7003 if self.take_rename(true, cx).is_some() {
7004 return;
7005 }
7006
7007 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7008 cx.propagate();
7009 return;
7010 }
7011
7012 let text_layout_details = &self.text_layout_details(cx);
7013
7014 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7015 let line_mode = s.line_mode;
7016 s.move_with(|map, selection| {
7017 if !selection.is_empty() && !line_mode {
7018 selection.goal = SelectionGoal::None;
7019 }
7020 let (cursor, goal) = movement::up_by_rows(
7021 map,
7022 selection.start,
7023 action.lines,
7024 selection.goal,
7025 false,
7026 text_layout_details,
7027 );
7028 selection.collapse_to(cursor, goal);
7029 });
7030 })
7031 }
7032
7033 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7034 if self.take_rename(true, cx).is_some() {
7035 return;
7036 }
7037
7038 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7039 cx.propagate();
7040 return;
7041 }
7042
7043 let text_layout_details = &self.text_layout_details(cx);
7044
7045 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7046 let line_mode = s.line_mode;
7047 s.move_with(|map, selection| {
7048 if !selection.is_empty() && !line_mode {
7049 selection.goal = SelectionGoal::None;
7050 }
7051 let (cursor, goal) = movement::down_by_rows(
7052 map,
7053 selection.start,
7054 action.lines,
7055 selection.goal,
7056 false,
7057 text_layout_details,
7058 );
7059 selection.collapse_to(cursor, goal);
7060 });
7061 })
7062 }
7063
7064 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7065 let text_layout_details = &self.text_layout_details(cx);
7066 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7067 s.move_heads_with(|map, head, goal| {
7068 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7069 })
7070 })
7071 }
7072
7073 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7074 let text_layout_details = &self.text_layout_details(cx);
7075 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7076 s.move_heads_with(|map, head, goal| {
7077 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7078 })
7079 })
7080 }
7081
7082 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7083 let Some(row_count) = self.visible_row_count() else {
7084 return;
7085 };
7086
7087 let text_layout_details = &self.text_layout_details(cx);
7088
7089 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7090 s.move_heads_with(|map, head, goal| {
7091 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7092 })
7093 })
7094 }
7095
7096 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7097 if self.take_rename(true, cx).is_some() {
7098 return;
7099 }
7100
7101 if self
7102 .context_menu
7103 .borrow_mut()
7104 .as_mut()
7105 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7106 .unwrap_or(false)
7107 {
7108 return;
7109 }
7110
7111 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7112 cx.propagate();
7113 return;
7114 }
7115
7116 let Some(row_count) = self.visible_row_count() else {
7117 return;
7118 };
7119
7120 let autoscroll = if action.center_cursor {
7121 Autoscroll::center()
7122 } else {
7123 Autoscroll::fit()
7124 };
7125
7126 let text_layout_details = &self.text_layout_details(cx);
7127
7128 self.change_selections(Some(autoscroll), cx, |s| {
7129 let line_mode = s.line_mode;
7130 s.move_with(|map, selection| {
7131 if !selection.is_empty() && !line_mode {
7132 selection.goal = SelectionGoal::None;
7133 }
7134 let (cursor, goal) = movement::up_by_rows(
7135 map,
7136 selection.end,
7137 row_count,
7138 selection.goal,
7139 false,
7140 text_layout_details,
7141 );
7142 selection.collapse_to(cursor, goal);
7143 });
7144 });
7145 }
7146
7147 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7148 let text_layout_details = &self.text_layout_details(cx);
7149 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7150 s.move_heads_with(|map, head, goal| {
7151 movement::up(map, head, goal, false, text_layout_details)
7152 })
7153 })
7154 }
7155
7156 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7157 self.take_rename(true, cx);
7158
7159 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7160 cx.propagate();
7161 return;
7162 }
7163
7164 let text_layout_details = &self.text_layout_details(cx);
7165 let selection_count = self.selections.count();
7166 let first_selection = self.selections.first_anchor();
7167
7168 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7169 let line_mode = s.line_mode;
7170 s.move_with(|map, selection| {
7171 if !selection.is_empty() && !line_mode {
7172 selection.goal = SelectionGoal::None;
7173 }
7174 let (cursor, goal) = movement::down(
7175 map,
7176 selection.end,
7177 selection.goal,
7178 false,
7179 text_layout_details,
7180 );
7181 selection.collapse_to(cursor, goal);
7182 });
7183 });
7184
7185 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7186 {
7187 cx.propagate();
7188 }
7189 }
7190
7191 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7192 let Some(row_count) = self.visible_row_count() else {
7193 return;
7194 };
7195
7196 let text_layout_details = &self.text_layout_details(cx);
7197
7198 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7199 s.move_heads_with(|map, head, goal| {
7200 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7201 })
7202 })
7203 }
7204
7205 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7206 if self.take_rename(true, cx).is_some() {
7207 return;
7208 }
7209
7210 if self
7211 .context_menu
7212 .borrow_mut()
7213 .as_mut()
7214 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7215 .unwrap_or(false)
7216 {
7217 return;
7218 }
7219
7220 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7221 cx.propagate();
7222 return;
7223 }
7224
7225 let Some(row_count) = self.visible_row_count() else {
7226 return;
7227 };
7228
7229 let autoscroll = if action.center_cursor {
7230 Autoscroll::center()
7231 } else {
7232 Autoscroll::fit()
7233 };
7234
7235 let text_layout_details = &self.text_layout_details(cx);
7236 self.change_selections(Some(autoscroll), cx, |s| {
7237 let line_mode = s.line_mode;
7238 s.move_with(|map, selection| {
7239 if !selection.is_empty() && !line_mode {
7240 selection.goal = SelectionGoal::None;
7241 }
7242 let (cursor, goal) = movement::down_by_rows(
7243 map,
7244 selection.end,
7245 row_count,
7246 selection.goal,
7247 false,
7248 text_layout_details,
7249 );
7250 selection.collapse_to(cursor, goal);
7251 });
7252 });
7253 }
7254
7255 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7256 let text_layout_details = &self.text_layout_details(cx);
7257 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7258 s.move_heads_with(|map, head, goal| {
7259 movement::down(map, head, goal, false, text_layout_details)
7260 })
7261 });
7262 }
7263
7264 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7265 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7266 context_menu.select_first(self.completion_provider.as_deref(), cx);
7267 }
7268 }
7269
7270 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7271 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7272 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7273 }
7274 }
7275
7276 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7277 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7278 context_menu.select_next(self.completion_provider.as_deref(), cx);
7279 }
7280 }
7281
7282 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7283 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7284 context_menu.select_last(self.completion_provider.as_deref(), cx);
7285 }
7286 }
7287
7288 pub fn move_to_previous_word_start(
7289 &mut self,
7290 _: &MoveToPreviousWordStart,
7291 cx: &mut ViewContext<Self>,
7292 ) {
7293 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7294 s.move_cursors_with(|map, head, _| {
7295 (
7296 movement::previous_word_start(map, head),
7297 SelectionGoal::None,
7298 )
7299 });
7300 })
7301 }
7302
7303 pub fn move_to_previous_subword_start(
7304 &mut self,
7305 _: &MoveToPreviousSubwordStart,
7306 cx: &mut ViewContext<Self>,
7307 ) {
7308 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7309 s.move_cursors_with(|map, head, _| {
7310 (
7311 movement::previous_subword_start(map, head),
7312 SelectionGoal::None,
7313 )
7314 });
7315 })
7316 }
7317
7318 pub fn select_to_previous_word_start(
7319 &mut self,
7320 _: &SelectToPreviousWordStart,
7321 cx: &mut ViewContext<Self>,
7322 ) {
7323 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7324 s.move_heads_with(|map, head, _| {
7325 (
7326 movement::previous_word_start(map, head),
7327 SelectionGoal::None,
7328 )
7329 });
7330 })
7331 }
7332
7333 pub fn select_to_previous_subword_start(
7334 &mut self,
7335 _: &SelectToPreviousSubwordStart,
7336 cx: &mut ViewContext<Self>,
7337 ) {
7338 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7339 s.move_heads_with(|map, head, _| {
7340 (
7341 movement::previous_subword_start(map, head),
7342 SelectionGoal::None,
7343 )
7344 });
7345 })
7346 }
7347
7348 pub fn delete_to_previous_word_start(
7349 &mut self,
7350 action: &DeleteToPreviousWordStart,
7351 cx: &mut ViewContext<Self>,
7352 ) {
7353 self.transact(cx, |this, cx| {
7354 this.select_autoclose_pair(cx);
7355 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7356 let line_mode = s.line_mode;
7357 s.move_with(|map, selection| {
7358 if selection.is_empty() && !line_mode {
7359 let cursor = if action.ignore_newlines {
7360 movement::previous_word_start(map, selection.head())
7361 } else {
7362 movement::previous_word_start_or_newline(map, selection.head())
7363 };
7364 selection.set_head(cursor, SelectionGoal::None);
7365 }
7366 });
7367 });
7368 this.insert("", cx);
7369 });
7370 }
7371
7372 pub fn delete_to_previous_subword_start(
7373 &mut self,
7374 _: &DeleteToPreviousSubwordStart,
7375 cx: &mut ViewContext<Self>,
7376 ) {
7377 self.transact(cx, |this, cx| {
7378 this.select_autoclose_pair(cx);
7379 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7380 let line_mode = s.line_mode;
7381 s.move_with(|map, selection| {
7382 if selection.is_empty() && !line_mode {
7383 let cursor = movement::previous_subword_start(map, selection.head());
7384 selection.set_head(cursor, SelectionGoal::None);
7385 }
7386 });
7387 });
7388 this.insert("", cx);
7389 });
7390 }
7391
7392 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7393 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7394 s.move_cursors_with(|map, head, _| {
7395 (movement::next_word_end(map, head), SelectionGoal::None)
7396 });
7397 })
7398 }
7399
7400 pub fn move_to_next_subword_end(
7401 &mut self,
7402 _: &MoveToNextSubwordEnd,
7403 cx: &mut ViewContext<Self>,
7404 ) {
7405 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7406 s.move_cursors_with(|map, head, _| {
7407 (movement::next_subword_end(map, head), SelectionGoal::None)
7408 });
7409 })
7410 }
7411
7412 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7413 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7414 s.move_heads_with(|map, head, _| {
7415 (movement::next_word_end(map, head), SelectionGoal::None)
7416 });
7417 })
7418 }
7419
7420 pub fn select_to_next_subword_end(
7421 &mut self,
7422 _: &SelectToNextSubwordEnd,
7423 cx: &mut ViewContext<Self>,
7424 ) {
7425 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7426 s.move_heads_with(|map, head, _| {
7427 (movement::next_subword_end(map, head), SelectionGoal::None)
7428 });
7429 })
7430 }
7431
7432 pub fn delete_to_next_word_end(
7433 &mut self,
7434 action: &DeleteToNextWordEnd,
7435 cx: &mut ViewContext<Self>,
7436 ) {
7437 self.transact(cx, |this, cx| {
7438 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7439 let line_mode = s.line_mode;
7440 s.move_with(|map, selection| {
7441 if selection.is_empty() && !line_mode {
7442 let cursor = if action.ignore_newlines {
7443 movement::next_word_end(map, selection.head())
7444 } else {
7445 movement::next_word_end_or_newline(map, selection.head())
7446 };
7447 selection.set_head(cursor, SelectionGoal::None);
7448 }
7449 });
7450 });
7451 this.insert("", cx);
7452 });
7453 }
7454
7455 pub fn delete_to_next_subword_end(
7456 &mut self,
7457 _: &DeleteToNextSubwordEnd,
7458 cx: &mut ViewContext<Self>,
7459 ) {
7460 self.transact(cx, |this, cx| {
7461 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7462 s.move_with(|map, selection| {
7463 if selection.is_empty() {
7464 let cursor = movement::next_subword_end(map, selection.head());
7465 selection.set_head(cursor, SelectionGoal::None);
7466 }
7467 });
7468 });
7469 this.insert("", cx);
7470 });
7471 }
7472
7473 pub fn move_to_beginning_of_line(
7474 &mut self,
7475 action: &MoveToBeginningOfLine,
7476 cx: &mut ViewContext<Self>,
7477 ) {
7478 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7479 s.move_cursors_with(|map, head, _| {
7480 (
7481 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7482 SelectionGoal::None,
7483 )
7484 });
7485 })
7486 }
7487
7488 pub fn select_to_beginning_of_line(
7489 &mut self,
7490 action: &SelectToBeginningOfLine,
7491 cx: &mut ViewContext<Self>,
7492 ) {
7493 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7494 s.move_heads_with(|map, head, _| {
7495 (
7496 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7497 SelectionGoal::None,
7498 )
7499 });
7500 });
7501 }
7502
7503 pub fn delete_to_beginning_of_line(
7504 &mut self,
7505 _: &DeleteToBeginningOfLine,
7506 cx: &mut ViewContext<Self>,
7507 ) {
7508 self.transact(cx, |this, cx| {
7509 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7510 s.move_with(|_, selection| {
7511 selection.reversed = true;
7512 });
7513 });
7514
7515 this.select_to_beginning_of_line(
7516 &SelectToBeginningOfLine {
7517 stop_at_soft_wraps: false,
7518 },
7519 cx,
7520 );
7521 this.backspace(&Backspace, cx);
7522 });
7523 }
7524
7525 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7526 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7527 s.move_cursors_with(|map, head, _| {
7528 (
7529 movement::line_end(map, head, action.stop_at_soft_wraps),
7530 SelectionGoal::None,
7531 )
7532 });
7533 })
7534 }
7535
7536 pub fn select_to_end_of_line(
7537 &mut self,
7538 action: &SelectToEndOfLine,
7539 cx: &mut ViewContext<Self>,
7540 ) {
7541 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7542 s.move_heads_with(|map, head, _| {
7543 (
7544 movement::line_end(map, head, action.stop_at_soft_wraps),
7545 SelectionGoal::None,
7546 )
7547 });
7548 })
7549 }
7550
7551 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7552 self.transact(cx, |this, cx| {
7553 this.select_to_end_of_line(
7554 &SelectToEndOfLine {
7555 stop_at_soft_wraps: false,
7556 },
7557 cx,
7558 );
7559 this.delete(&Delete, cx);
7560 });
7561 }
7562
7563 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7564 self.transact(cx, |this, cx| {
7565 this.select_to_end_of_line(
7566 &SelectToEndOfLine {
7567 stop_at_soft_wraps: false,
7568 },
7569 cx,
7570 );
7571 this.cut(&Cut, cx);
7572 });
7573 }
7574
7575 pub fn move_to_start_of_paragraph(
7576 &mut self,
7577 _: &MoveToStartOfParagraph,
7578 cx: &mut ViewContext<Self>,
7579 ) {
7580 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7581 cx.propagate();
7582 return;
7583 }
7584
7585 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7586 s.move_with(|map, selection| {
7587 selection.collapse_to(
7588 movement::start_of_paragraph(map, selection.head(), 1),
7589 SelectionGoal::None,
7590 )
7591 });
7592 })
7593 }
7594
7595 pub fn move_to_end_of_paragraph(
7596 &mut self,
7597 _: &MoveToEndOfParagraph,
7598 cx: &mut ViewContext<Self>,
7599 ) {
7600 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7601 cx.propagate();
7602 return;
7603 }
7604
7605 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7606 s.move_with(|map, selection| {
7607 selection.collapse_to(
7608 movement::end_of_paragraph(map, selection.head(), 1),
7609 SelectionGoal::None,
7610 )
7611 });
7612 })
7613 }
7614
7615 pub fn select_to_start_of_paragraph(
7616 &mut self,
7617 _: &SelectToStartOfParagraph,
7618 cx: &mut ViewContext<Self>,
7619 ) {
7620 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7621 cx.propagate();
7622 return;
7623 }
7624
7625 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7626 s.move_heads_with(|map, head, _| {
7627 (
7628 movement::start_of_paragraph(map, head, 1),
7629 SelectionGoal::None,
7630 )
7631 });
7632 })
7633 }
7634
7635 pub fn select_to_end_of_paragraph(
7636 &mut self,
7637 _: &SelectToEndOfParagraph,
7638 cx: &mut ViewContext<Self>,
7639 ) {
7640 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7641 cx.propagate();
7642 return;
7643 }
7644
7645 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7646 s.move_heads_with(|map, head, _| {
7647 (
7648 movement::end_of_paragraph(map, head, 1),
7649 SelectionGoal::None,
7650 )
7651 });
7652 })
7653 }
7654
7655 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7656 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7657 cx.propagate();
7658 return;
7659 }
7660
7661 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7662 s.select_ranges(vec![0..0]);
7663 });
7664 }
7665
7666 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7667 let mut selection = self.selections.last::<Point>(cx);
7668 selection.set_head(Point::zero(), SelectionGoal::None);
7669
7670 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7671 s.select(vec![selection]);
7672 });
7673 }
7674
7675 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7676 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7677 cx.propagate();
7678 return;
7679 }
7680
7681 let cursor = self.buffer.read(cx).read(cx).len();
7682 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7683 s.select_ranges(vec![cursor..cursor])
7684 });
7685 }
7686
7687 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7688 self.nav_history = nav_history;
7689 }
7690
7691 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7692 self.nav_history.as_ref()
7693 }
7694
7695 fn push_to_nav_history(
7696 &mut self,
7697 cursor_anchor: Anchor,
7698 new_position: Option<Point>,
7699 cx: &mut ViewContext<Self>,
7700 ) {
7701 if let Some(nav_history) = self.nav_history.as_mut() {
7702 let buffer = self.buffer.read(cx).read(cx);
7703 let cursor_position = cursor_anchor.to_point(&buffer);
7704 let scroll_state = self.scroll_manager.anchor();
7705 let scroll_top_row = scroll_state.top_row(&buffer);
7706 drop(buffer);
7707
7708 if let Some(new_position) = new_position {
7709 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7710 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7711 return;
7712 }
7713 }
7714
7715 nav_history.push(
7716 Some(NavigationData {
7717 cursor_anchor,
7718 cursor_position,
7719 scroll_anchor: scroll_state,
7720 scroll_top_row,
7721 }),
7722 cx,
7723 );
7724 }
7725 }
7726
7727 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7728 let buffer = self.buffer.read(cx).snapshot(cx);
7729 let mut selection = self.selections.first::<usize>(cx);
7730 selection.set_head(buffer.len(), SelectionGoal::None);
7731 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7732 s.select(vec![selection]);
7733 });
7734 }
7735
7736 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7737 let end = self.buffer.read(cx).read(cx).len();
7738 self.change_selections(None, cx, |s| {
7739 s.select_ranges(vec![0..end]);
7740 });
7741 }
7742
7743 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7744 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7745 let mut selections = self.selections.all::<Point>(cx);
7746 let max_point = display_map.buffer_snapshot.max_point();
7747 for selection in &mut selections {
7748 let rows = selection.spanned_rows(true, &display_map);
7749 selection.start = Point::new(rows.start.0, 0);
7750 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7751 selection.reversed = false;
7752 }
7753 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7754 s.select(selections);
7755 });
7756 }
7757
7758 pub fn split_selection_into_lines(
7759 &mut self,
7760 _: &SplitSelectionIntoLines,
7761 cx: &mut ViewContext<Self>,
7762 ) {
7763 let mut to_unfold = Vec::new();
7764 let mut new_selection_ranges = Vec::new();
7765 {
7766 let selections = self.selections.all::<Point>(cx);
7767 let buffer = self.buffer.read(cx).read(cx);
7768 for selection in selections {
7769 for row in selection.start.row..selection.end.row {
7770 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7771 new_selection_ranges.push(cursor..cursor);
7772 }
7773 new_selection_ranges.push(selection.end..selection.end);
7774 to_unfold.push(selection.start..selection.end);
7775 }
7776 }
7777 self.unfold_ranges(&to_unfold, true, true, cx);
7778 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7779 s.select_ranges(new_selection_ranges);
7780 });
7781 }
7782
7783 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7784 self.add_selection(true, cx);
7785 }
7786
7787 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7788 self.add_selection(false, cx);
7789 }
7790
7791 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7792 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7793 let mut selections = self.selections.all::<Point>(cx);
7794 let text_layout_details = self.text_layout_details(cx);
7795 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7796 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7797 let range = oldest_selection.display_range(&display_map).sorted();
7798
7799 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7800 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7801 let positions = start_x.min(end_x)..start_x.max(end_x);
7802
7803 selections.clear();
7804 let mut stack = Vec::new();
7805 for row in range.start.row().0..=range.end.row().0 {
7806 if let Some(selection) = self.selections.build_columnar_selection(
7807 &display_map,
7808 DisplayRow(row),
7809 &positions,
7810 oldest_selection.reversed,
7811 &text_layout_details,
7812 ) {
7813 stack.push(selection.id);
7814 selections.push(selection);
7815 }
7816 }
7817
7818 if above {
7819 stack.reverse();
7820 }
7821
7822 AddSelectionsState { above, stack }
7823 });
7824
7825 let last_added_selection = *state.stack.last().unwrap();
7826 let mut new_selections = Vec::new();
7827 if above == state.above {
7828 let end_row = if above {
7829 DisplayRow(0)
7830 } else {
7831 display_map.max_point().row()
7832 };
7833
7834 'outer: for selection in selections {
7835 if selection.id == last_added_selection {
7836 let range = selection.display_range(&display_map).sorted();
7837 debug_assert_eq!(range.start.row(), range.end.row());
7838 let mut row = range.start.row();
7839 let positions =
7840 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7841 px(start)..px(end)
7842 } else {
7843 let start_x =
7844 display_map.x_for_display_point(range.start, &text_layout_details);
7845 let end_x =
7846 display_map.x_for_display_point(range.end, &text_layout_details);
7847 start_x.min(end_x)..start_x.max(end_x)
7848 };
7849
7850 while row != end_row {
7851 if above {
7852 row.0 -= 1;
7853 } else {
7854 row.0 += 1;
7855 }
7856
7857 if let Some(new_selection) = self.selections.build_columnar_selection(
7858 &display_map,
7859 row,
7860 &positions,
7861 selection.reversed,
7862 &text_layout_details,
7863 ) {
7864 state.stack.push(new_selection.id);
7865 if above {
7866 new_selections.push(new_selection);
7867 new_selections.push(selection);
7868 } else {
7869 new_selections.push(selection);
7870 new_selections.push(new_selection);
7871 }
7872
7873 continue 'outer;
7874 }
7875 }
7876 }
7877
7878 new_selections.push(selection);
7879 }
7880 } else {
7881 new_selections = selections;
7882 new_selections.retain(|s| s.id != last_added_selection);
7883 state.stack.pop();
7884 }
7885
7886 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7887 s.select(new_selections);
7888 });
7889 if state.stack.len() > 1 {
7890 self.add_selections_state = Some(state);
7891 }
7892 }
7893
7894 pub fn select_next_match_internal(
7895 &mut self,
7896 display_map: &DisplaySnapshot,
7897 replace_newest: bool,
7898 autoscroll: Option<Autoscroll>,
7899 cx: &mut ViewContext<Self>,
7900 ) -> Result<()> {
7901 fn select_next_match_ranges(
7902 this: &mut Editor,
7903 range: Range<usize>,
7904 replace_newest: bool,
7905 auto_scroll: Option<Autoscroll>,
7906 cx: &mut ViewContext<Editor>,
7907 ) {
7908 this.unfold_ranges(&[range.clone()], false, true, cx);
7909 this.change_selections(auto_scroll, cx, |s| {
7910 if replace_newest {
7911 s.delete(s.newest_anchor().id);
7912 }
7913 s.insert_range(range.clone());
7914 });
7915 }
7916
7917 let buffer = &display_map.buffer_snapshot;
7918 let mut selections = self.selections.all::<usize>(cx);
7919 if let Some(mut select_next_state) = self.select_next_state.take() {
7920 let query = &select_next_state.query;
7921 if !select_next_state.done {
7922 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7923 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7924 let mut next_selected_range = None;
7925
7926 let bytes_after_last_selection =
7927 buffer.bytes_in_range(last_selection.end..buffer.len());
7928 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
7929 let query_matches = query
7930 .stream_find_iter(bytes_after_last_selection)
7931 .map(|result| (last_selection.end, result))
7932 .chain(
7933 query
7934 .stream_find_iter(bytes_before_first_selection)
7935 .map(|result| (0, result)),
7936 );
7937
7938 for (start_offset, query_match) in query_matches {
7939 let query_match = query_match.unwrap(); // can only fail due to I/O
7940 let offset_range =
7941 start_offset + query_match.start()..start_offset + query_match.end();
7942 let display_range = offset_range.start.to_display_point(display_map)
7943 ..offset_range.end.to_display_point(display_map);
7944
7945 if !select_next_state.wordwise
7946 || (!movement::is_inside_word(display_map, display_range.start)
7947 && !movement::is_inside_word(display_map, display_range.end))
7948 {
7949 // TODO: This is n^2, because we might check all the selections
7950 if !selections
7951 .iter()
7952 .any(|selection| selection.range().overlaps(&offset_range))
7953 {
7954 next_selected_range = Some(offset_range);
7955 break;
7956 }
7957 }
7958 }
7959
7960 if let Some(next_selected_range) = next_selected_range {
7961 select_next_match_ranges(
7962 self,
7963 next_selected_range,
7964 replace_newest,
7965 autoscroll,
7966 cx,
7967 );
7968 } else {
7969 select_next_state.done = true;
7970 }
7971 }
7972
7973 self.select_next_state = Some(select_next_state);
7974 } else {
7975 let mut only_carets = true;
7976 let mut same_text_selected = true;
7977 let mut selected_text = None;
7978
7979 let mut selections_iter = selections.iter().peekable();
7980 while let Some(selection) = selections_iter.next() {
7981 if selection.start != selection.end {
7982 only_carets = false;
7983 }
7984
7985 if same_text_selected {
7986 if selected_text.is_none() {
7987 selected_text =
7988 Some(buffer.text_for_range(selection.range()).collect::<String>());
7989 }
7990
7991 if let Some(next_selection) = selections_iter.peek() {
7992 if next_selection.range().len() == selection.range().len() {
7993 let next_selected_text = buffer
7994 .text_for_range(next_selection.range())
7995 .collect::<String>();
7996 if Some(next_selected_text) != selected_text {
7997 same_text_selected = false;
7998 selected_text = None;
7999 }
8000 } else {
8001 same_text_selected = false;
8002 selected_text = None;
8003 }
8004 }
8005 }
8006 }
8007
8008 if only_carets {
8009 for selection in &mut selections {
8010 let word_range = movement::surrounding_word(
8011 display_map,
8012 selection.start.to_display_point(display_map),
8013 );
8014 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8015 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8016 selection.goal = SelectionGoal::None;
8017 selection.reversed = false;
8018 select_next_match_ranges(
8019 self,
8020 selection.start..selection.end,
8021 replace_newest,
8022 autoscroll,
8023 cx,
8024 );
8025 }
8026
8027 if selections.len() == 1 {
8028 let selection = selections
8029 .last()
8030 .expect("ensured that there's only one selection");
8031 let query = buffer
8032 .text_for_range(selection.start..selection.end)
8033 .collect::<String>();
8034 let is_empty = query.is_empty();
8035 let select_state = SelectNextState {
8036 query: AhoCorasick::new(&[query])?,
8037 wordwise: true,
8038 done: is_empty,
8039 };
8040 self.select_next_state = Some(select_state);
8041 } else {
8042 self.select_next_state = None;
8043 }
8044 } else if let Some(selected_text) = selected_text {
8045 self.select_next_state = Some(SelectNextState {
8046 query: AhoCorasick::new(&[selected_text])?,
8047 wordwise: false,
8048 done: false,
8049 });
8050 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8051 }
8052 }
8053 Ok(())
8054 }
8055
8056 pub fn select_all_matches(
8057 &mut self,
8058 _action: &SelectAllMatches,
8059 cx: &mut ViewContext<Self>,
8060 ) -> Result<()> {
8061 self.push_to_selection_history();
8062 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8063
8064 self.select_next_match_internal(&display_map, false, None, cx)?;
8065 let Some(select_next_state) = self.select_next_state.as_mut() else {
8066 return Ok(());
8067 };
8068 if select_next_state.done {
8069 return Ok(());
8070 }
8071
8072 let mut new_selections = self.selections.all::<usize>(cx);
8073
8074 let buffer = &display_map.buffer_snapshot;
8075 let query_matches = select_next_state
8076 .query
8077 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8078
8079 for query_match in query_matches {
8080 let query_match = query_match.unwrap(); // can only fail due to I/O
8081 let offset_range = query_match.start()..query_match.end();
8082 let display_range = offset_range.start.to_display_point(&display_map)
8083 ..offset_range.end.to_display_point(&display_map);
8084
8085 if !select_next_state.wordwise
8086 || (!movement::is_inside_word(&display_map, display_range.start)
8087 && !movement::is_inside_word(&display_map, display_range.end))
8088 {
8089 self.selections.change_with(cx, |selections| {
8090 new_selections.push(Selection {
8091 id: selections.new_selection_id(),
8092 start: offset_range.start,
8093 end: offset_range.end,
8094 reversed: false,
8095 goal: SelectionGoal::None,
8096 });
8097 });
8098 }
8099 }
8100
8101 new_selections.sort_by_key(|selection| selection.start);
8102 let mut ix = 0;
8103 while ix + 1 < new_selections.len() {
8104 let current_selection = &new_selections[ix];
8105 let next_selection = &new_selections[ix + 1];
8106 if current_selection.range().overlaps(&next_selection.range()) {
8107 if current_selection.id < next_selection.id {
8108 new_selections.remove(ix + 1);
8109 } else {
8110 new_selections.remove(ix);
8111 }
8112 } else {
8113 ix += 1;
8114 }
8115 }
8116
8117 select_next_state.done = true;
8118 self.unfold_ranges(
8119 &new_selections
8120 .iter()
8121 .map(|selection| selection.range())
8122 .collect::<Vec<_>>(),
8123 false,
8124 false,
8125 cx,
8126 );
8127 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8128 selections.select(new_selections)
8129 });
8130
8131 Ok(())
8132 }
8133
8134 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8135 self.push_to_selection_history();
8136 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8137 self.select_next_match_internal(
8138 &display_map,
8139 action.replace_newest,
8140 Some(Autoscroll::newest()),
8141 cx,
8142 )?;
8143 Ok(())
8144 }
8145
8146 pub fn select_previous(
8147 &mut self,
8148 action: &SelectPrevious,
8149 cx: &mut ViewContext<Self>,
8150 ) -> Result<()> {
8151 self.push_to_selection_history();
8152 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8153 let buffer = &display_map.buffer_snapshot;
8154 let mut selections = self.selections.all::<usize>(cx);
8155 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8156 let query = &select_prev_state.query;
8157 if !select_prev_state.done {
8158 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8159 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8160 let mut next_selected_range = None;
8161 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8162 let bytes_before_last_selection =
8163 buffer.reversed_bytes_in_range(0..last_selection.start);
8164 let bytes_after_first_selection =
8165 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8166 let query_matches = query
8167 .stream_find_iter(bytes_before_last_selection)
8168 .map(|result| (last_selection.start, result))
8169 .chain(
8170 query
8171 .stream_find_iter(bytes_after_first_selection)
8172 .map(|result| (buffer.len(), result)),
8173 );
8174 for (end_offset, query_match) in query_matches {
8175 let query_match = query_match.unwrap(); // can only fail due to I/O
8176 let offset_range =
8177 end_offset - query_match.end()..end_offset - query_match.start();
8178 let display_range = offset_range.start.to_display_point(&display_map)
8179 ..offset_range.end.to_display_point(&display_map);
8180
8181 if !select_prev_state.wordwise
8182 || (!movement::is_inside_word(&display_map, display_range.start)
8183 && !movement::is_inside_word(&display_map, display_range.end))
8184 {
8185 next_selected_range = Some(offset_range);
8186 break;
8187 }
8188 }
8189
8190 if let Some(next_selected_range) = next_selected_range {
8191 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8192 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8193 if action.replace_newest {
8194 s.delete(s.newest_anchor().id);
8195 }
8196 s.insert_range(next_selected_range);
8197 });
8198 } else {
8199 select_prev_state.done = true;
8200 }
8201 }
8202
8203 self.select_prev_state = Some(select_prev_state);
8204 } else {
8205 let mut only_carets = true;
8206 let mut same_text_selected = true;
8207 let mut selected_text = None;
8208
8209 let mut selections_iter = selections.iter().peekable();
8210 while let Some(selection) = selections_iter.next() {
8211 if selection.start != selection.end {
8212 only_carets = false;
8213 }
8214
8215 if same_text_selected {
8216 if selected_text.is_none() {
8217 selected_text =
8218 Some(buffer.text_for_range(selection.range()).collect::<String>());
8219 }
8220
8221 if let Some(next_selection) = selections_iter.peek() {
8222 if next_selection.range().len() == selection.range().len() {
8223 let next_selected_text = buffer
8224 .text_for_range(next_selection.range())
8225 .collect::<String>();
8226 if Some(next_selected_text) != selected_text {
8227 same_text_selected = false;
8228 selected_text = None;
8229 }
8230 } else {
8231 same_text_selected = false;
8232 selected_text = None;
8233 }
8234 }
8235 }
8236 }
8237
8238 if only_carets {
8239 for selection in &mut selections {
8240 let word_range = movement::surrounding_word(
8241 &display_map,
8242 selection.start.to_display_point(&display_map),
8243 );
8244 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8245 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8246 selection.goal = SelectionGoal::None;
8247 selection.reversed = false;
8248 }
8249 if selections.len() == 1 {
8250 let selection = selections
8251 .last()
8252 .expect("ensured that there's only one selection");
8253 let query = buffer
8254 .text_for_range(selection.start..selection.end)
8255 .collect::<String>();
8256 let is_empty = query.is_empty();
8257 let select_state = SelectNextState {
8258 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8259 wordwise: true,
8260 done: is_empty,
8261 };
8262 self.select_prev_state = Some(select_state);
8263 } else {
8264 self.select_prev_state = None;
8265 }
8266
8267 self.unfold_ranges(
8268 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8269 false,
8270 true,
8271 cx,
8272 );
8273 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8274 s.select(selections);
8275 });
8276 } else if let Some(selected_text) = selected_text {
8277 self.select_prev_state = Some(SelectNextState {
8278 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8279 wordwise: false,
8280 done: false,
8281 });
8282 self.select_previous(action, cx)?;
8283 }
8284 }
8285 Ok(())
8286 }
8287
8288 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8289 if self.read_only(cx) {
8290 return;
8291 }
8292 let text_layout_details = &self.text_layout_details(cx);
8293 self.transact(cx, |this, cx| {
8294 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8295 let mut edits = Vec::new();
8296 let mut selection_edit_ranges = Vec::new();
8297 let mut last_toggled_row = None;
8298 let snapshot = this.buffer.read(cx).read(cx);
8299 let empty_str: Arc<str> = Arc::default();
8300 let mut suffixes_inserted = Vec::new();
8301 let ignore_indent = action.ignore_indent;
8302
8303 fn comment_prefix_range(
8304 snapshot: &MultiBufferSnapshot,
8305 row: MultiBufferRow,
8306 comment_prefix: &str,
8307 comment_prefix_whitespace: &str,
8308 ignore_indent: bool,
8309 ) -> Range<Point> {
8310 let indent_size = if ignore_indent {
8311 0
8312 } else {
8313 snapshot.indent_size_for_line(row).len
8314 };
8315
8316 let start = Point::new(row.0, indent_size);
8317
8318 let mut line_bytes = snapshot
8319 .bytes_in_range(start..snapshot.max_point())
8320 .flatten()
8321 .copied();
8322
8323 // If this line currently begins with the line comment prefix, then record
8324 // the range containing the prefix.
8325 if line_bytes
8326 .by_ref()
8327 .take(comment_prefix.len())
8328 .eq(comment_prefix.bytes())
8329 {
8330 // Include any whitespace that matches the comment prefix.
8331 let matching_whitespace_len = line_bytes
8332 .zip(comment_prefix_whitespace.bytes())
8333 .take_while(|(a, b)| a == b)
8334 .count() as u32;
8335 let end = Point::new(
8336 start.row,
8337 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8338 );
8339 start..end
8340 } else {
8341 start..start
8342 }
8343 }
8344
8345 fn comment_suffix_range(
8346 snapshot: &MultiBufferSnapshot,
8347 row: MultiBufferRow,
8348 comment_suffix: &str,
8349 comment_suffix_has_leading_space: bool,
8350 ) -> Range<Point> {
8351 let end = Point::new(row.0, snapshot.line_len(row));
8352 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8353
8354 let mut line_end_bytes = snapshot
8355 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8356 .flatten()
8357 .copied();
8358
8359 let leading_space_len = if suffix_start_column > 0
8360 && line_end_bytes.next() == Some(b' ')
8361 && comment_suffix_has_leading_space
8362 {
8363 1
8364 } else {
8365 0
8366 };
8367
8368 // If this line currently begins with the line comment prefix, then record
8369 // the range containing the prefix.
8370 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8371 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8372 start..end
8373 } else {
8374 end..end
8375 }
8376 }
8377
8378 // TODO: Handle selections that cross excerpts
8379 for selection in &mut selections {
8380 let start_column = snapshot
8381 .indent_size_for_line(MultiBufferRow(selection.start.row))
8382 .len;
8383 let language = if let Some(language) =
8384 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8385 {
8386 language
8387 } else {
8388 continue;
8389 };
8390
8391 selection_edit_ranges.clear();
8392
8393 // If multiple selections contain a given row, avoid processing that
8394 // row more than once.
8395 let mut start_row = MultiBufferRow(selection.start.row);
8396 if last_toggled_row == Some(start_row) {
8397 start_row = start_row.next_row();
8398 }
8399 let end_row =
8400 if selection.end.row > selection.start.row && selection.end.column == 0 {
8401 MultiBufferRow(selection.end.row - 1)
8402 } else {
8403 MultiBufferRow(selection.end.row)
8404 };
8405 last_toggled_row = Some(end_row);
8406
8407 if start_row > end_row {
8408 continue;
8409 }
8410
8411 // If the language has line comments, toggle those.
8412 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8413
8414 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8415 if ignore_indent {
8416 full_comment_prefixes = full_comment_prefixes
8417 .into_iter()
8418 .map(|s| Arc::from(s.trim_end()))
8419 .collect();
8420 }
8421
8422 if !full_comment_prefixes.is_empty() {
8423 let first_prefix = full_comment_prefixes
8424 .first()
8425 .expect("prefixes is non-empty");
8426 let prefix_trimmed_lengths = full_comment_prefixes
8427 .iter()
8428 .map(|p| p.trim_end_matches(' ').len())
8429 .collect::<SmallVec<[usize; 4]>>();
8430
8431 let mut all_selection_lines_are_comments = true;
8432
8433 for row in start_row.0..=end_row.0 {
8434 let row = MultiBufferRow(row);
8435 if start_row < end_row && snapshot.is_line_blank(row) {
8436 continue;
8437 }
8438
8439 let prefix_range = full_comment_prefixes
8440 .iter()
8441 .zip(prefix_trimmed_lengths.iter().copied())
8442 .map(|(prefix, trimmed_prefix_len)| {
8443 comment_prefix_range(
8444 snapshot.deref(),
8445 row,
8446 &prefix[..trimmed_prefix_len],
8447 &prefix[trimmed_prefix_len..],
8448 ignore_indent,
8449 )
8450 })
8451 .max_by_key(|range| range.end.column - range.start.column)
8452 .expect("prefixes is non-empty");
8453
8454 if prefix_range.is_empty() {
8455 all_selection_lines_are_comments = false;
8456 }
8457
8458 selection_edit_ranges.push(prefix_range);
8459 }
8460
8461 if all_selection_lines_are_comments {
8462 edits.extend(
8463 selection_edit_ranges
8464 .iter()
8465 .cloned()
8466 .map(|range| (range, empty_str.clone())),
8467 );
8468 } else {
8469 let min_column = selection_edit_ranges
8470 .iter()
8471 .map(|range| range.start.column)
8472 .min()
8473 .unwrap_or(0);
8474 edits.extend(selection_edit_ranges.iter().map(|range| {
8475 let position = Point::new(range.start.row, min_column);
8476 (position..position, first_prefix.clone())
8477 }));
8478 }
8479 } else if let Some((full_comment_prefix, comment_suffix)) =
8480 language.block_comment_delimiters()
8481 {
8482 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8483 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8484 let prefix_range = comment_prefix_range(
8485 snapshot.deref(),
8486 start_row,
8487 comment_prefix,
8488 comment_prefix_whitespace,
8489 ignore_indent,
8490 );
8491 let suffix_range = comment_suffix_range(
8492 snapshot.deref(),
8493 end_row,
8494 comment_suffix.trim_start_matches(' '),
8495 comment_suffix.starts_with(' '),
8496 );
8497
8498 if prefix_range.is_empty() || suffix_range.is_empty() {
8499 edits.push((
8500 prefix_range.start..prefix_range.start,
8501 full_comment_prefix.clone(),
8502 ));
8503 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8504 suffixes_inserted.push((end_row, comment_suffix.len()));
8505 } else {
8506 edits.push((prefix_range, empty_str.clone()));
8507 edits.push((suffix_range, empty_str.clone()));
8508 }
8509 } else {
8510 continue;
8511 }
8512 }
8513
8514 drop(snapshot);
8515 this.buffer.update(cx, |buffer, cx| {
8516 buffer.edit(edits, None, cx);
8517 });
8518
8519 // Adjust selections so that they end before any comment suffixes that
8520 // were inserted.
8521 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8522 let mut selections = this.selections.all::<Point>(cx);
8523 let snapshot = this.buffer.read(cx).read(cx);
8524 for selection in &mut selections {
8525 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8526 match row.cmp(&MultiBufferRow(selection.end.row)) {
8527 Ordering::Less => {
8528 suffixes_inserted.next();
8529 continue;
8530 }
8531 Ordering::Greater => break,
8532 Ordering::Equal => {
8533 if selection.end.column == snapshot.line_len(row) {
8534 if selection.is_empty() {
8535 selection.start.column -= suffix_len as u32;
8536 }
8537 selection.end.column -= suffix_len as u32;
8538 }
8539 break;
8540 }
8541 }
8542 }
8543 }
8544
8545 drop(snapshot);
8546 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8547
8548 let selections = this.selections.all::<Point>(cx);
8549 let selections_on_single_row = selections.windows(2).all(|selections| {
8550 selections[0].start.row == selections[1].start.row
8551 && selections[0].end.row == selections[1].end.row
8552 && selections[0].start.row == selections[0].end.row
8553 });
8554 let selections_selecting = selections
8555 .iter()
8556 .any(|selection| selection.start != selection.end);
8557 let advance_downwards = action.advance_downwards
8558 && selections_on_single_row
8559 && !selections_selecting
8560 && !matches!(this.mode, EditorMode::SingleLine { .. });
8561
8562 if advance_downwards {
8563 let snapshot = this.buffer.read(cx).snapshot(cx);
8564
8565 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8566 s.move_cursors_with(|display_snapshot, display_point, _| {
8567 let mut point = display_point.to_point(display_snapshot);
8568 point.row += 1;
8569 point = snapshot.clip_point(point, Bias::Left);
8570 let display_point = point.to_display_point(display_snapshot);
8571 let goal = SelectionGoal::HorizontalPosition(
8572 display_snapshot
8573 .x_for_display_point(display_point, text_layout_details)
8574 .into(),
8575 );
8576 (display_point, goal)
8577 })
8578 });
8579 }
8580 });
8581 }
8582
8583 pub fn select_enclosing_symbol(
8584 &mut self,
8585 _: &SelectEnclosingSymbol,
8586 cx: &mut ViewContext<Self>,
8587 ) {
8588 let buffer = self.buffer.read(cx).snapshot(cx);
8589 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8590
8591 fn update_selection(
8592 selection: &Selection<usize>,
8593 buffer_snap: &MultiBufferSnapshot,
8594 ) -> Option<Selection<usize>> {
8595 let cursor = selection.head();
8596 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8597 for symbol in symbols.iter().rev() {
8598 let start = symbol.range.start.to_offset(buffer_snap);
8599 let end = symbol.range.end.to_offset(buffer_snap);
8600 let new_range = start..end;
8601 if start < selection.start || end > selection.end {
8602 return Some(Selection {
8603 id: selection.id,
8604 start: new_range.start,
8605 end: new_range.end,
8606 goal: SelectionGoal::None,
8607 reversed: selection.reversed,
8608 });
8609 }
8610 }
8611 None
8612 }
8613
8614 let mut selected_larger_symbol = false;
8615 let new_selections = old_selections
8616 .iter()
8617 .map(|selection| match update_selection(selection, &buffer) {
8618 Some(new_selection) => {
8619 if new_selection.range() != selection.range() {
8620 selected_larger_symbol = true;
8621 }
8622 new_selection
8623 }
8624 None => selection.clone(),
8625 })
8626 .collect::<Vec<_>>();
8627
8628 if selected_larger_symbol {
8629 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8630 s.select(new_selections);
8631 });
8632 }
8633 }
8634
8635 pub fn select_larger_syntax_node(
8636 &mut self,
8637 _: &SelectLargerSyntaxNode,
8638 cx: &mut ViewContext<Self>,
8639 ) {
8640 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8641 let buffer = self.buffer.read(cx).snapshot(cx);
8642 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8643
8644 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8645 let mut selected_larger_node = false;
8646 let new_selections = old_selections
8647 .iter()
8648 .map(|selection| {
8649 let old_range = selection.start..selection.end;
8650 let mut new_range = old_range.clone();
8651 while let Some(containing_range) =
8652 buffer.range_for_syntax_ancestor(new_range.clone())
8653 {
8654 new_range = containing_range;
8655 if !display_map.intersects_fold(new_range.start)
8656 && !display_map.intersects_fold(new_range.end)
8657 {
8658 break;
8659 }
8660 }
8661
8662 selected_larger_node |= new_range != old_range;
8663 Selection {
8664 id: selection.id,
8665 start: new_range.start,
8666 end: new_range.end,
8667 goal: SelectionGoal::None,
8668 reversed: selection.reversed,
8669 }
8670 })
8671 .collect::<Vec<_>>();
8672
8673 if selected_larger_node {
8674 stack.push(old_selections);
8675 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8676 s.select(new_selections);
8677 });
8678 }
8679 self.select_larger_syntax_node_stack = stack;
8680 }
8681
8682 pub fn select_smaller_syntax_node(
8683 &mut self,
8684 _: &SelectSmallerSyntaxNode,
8685 cx: &mut ViewContext<Self>,
8686 ) {
8687 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8688 if let Some(selections) = stack.pop() {
8689 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8690 s.select(selections.to_vec());
8691 });
8692 }
8693 self.select_larger_syntax_node_stack = stack;
8694 }
8695
8696 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8697 if !EditorSettings::get_global(cx).gutter.runnables {
8698 self.clear_tasks();
8699 return Task::ready(());
8700 }
8701 let project = self.project.as_ref().map(Model::downgrade);
8702 cx.spawn(|this, mut cx| async move {
8703 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
8704 let Some(project) = project.and_then(|p| p.upgrade()) else {
8705 return;
8706 };
8707 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8708 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8709 }) else {
8710 return;
8711 };
8712
8713 let hide_runnables = project
8714 .update(&mut cx, |project, cx| {
8715 // Do not display any test indicators in non-dev server remote projects.
8716 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8717 })
8718 .unwrap_or(true);
8719 if hide_runnables {
8720 return;
8721 }
8722 let new_rows =
8723 cx.background_executor()
8724 .spawn({
8725 let snapshot = display_snapshot.clone();
8726 async move {
8727 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8728 }
8729 })
8730 .await;
8731 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8732
8733 this.update(&mut cx, |this, _| {
8734 this.clear_tasks();
8735 for (key, value) in rows {
8736 this.insert_tasks(key, value);
8737 }
8738 })
8739 .ok();
8740 })
8741 }
8742 fn fetch_runnable_ranges(
8743 snapshot: &DisplaySnapshot,
8744 range: Range<Anchor>,
8745 ) -> Vec<language::RunnableRange> {
8746 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8747 }
8748
8749 fn runnable_rows(
8750 project: Model<Project>,
8751 snapshot: DisplaySnapshot,
8752 runnable_ranges: Vec<RunnableRange>,
8753 mut cx: AsyncWindowContext,
8754 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8755 runnable_ranges
8756 .into_iter()
8757 .filter_map(|mut runnable| {
8758 let tasks = cx
8759 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8760 .ok()?;
8761 if tasks.is_empty() {
8762 return None;
8763 }
8764
8765 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8766
8767 let row = snapshot
8768 .buffer_snapshot
8769 .buffer_line_for_row(MultiBufferRow(point.row))?
8770 .1
8771 .start
8772 .row;
8773
8774 let context_range =
8775 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8776 Some((
8777 (runnable.buffer_id, row),
8778 RunnableTasks {
8779 templates: tasks,
8780 offset: MultiBufferOffset(runnable.run_range.start),
8781 context_range,
8782 column: point.column,
8783 extra_variables: runnable.extra_captures,
8784 },
8785 ))
8786 })
8787 .collect()
8788 }
8789
8790 fn templates_with_tags(
8791 project: &Model<Project>,
8792 runnable: &mut Runnable,
8793 cx: &WindowContext<'_>,
8794 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8795 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8796 let (worktree_id, file) = project
8797 .buffer_for_id(runnable.buffer, cx)
8798 .and_then(|buffer| buffer.read(cx).file())
8799 .map(|file| (file.worktree_id(cx), file.clone()))
8800 .unzip();
8801
8802 (
8803 project.task_store().read(cx).task_inventory().cloned(),
8804 worktree_id,
8805 file,
8806 )
8807 });
8808
8809 let tags = mem::take(&mut runnable.tags);
8810 let mut tags: Vec<_> = tags
8811 .into_iter()
8812 .flat_map(|tag| {
8813 let tag = tag.0.clone();
8814 inventory
8815 .as_ref()
8816 .into_iter()
8817 .flat_map(|inventory| {
8818 inventory.read(cx).list_tasks(
8819 file.clone(),
8820 Some(runnable.language.clone()),
8821 worktree_id,
8822 cx,
8823 )
8824 })
8825 .filter(move |(_, template)| {
8826 template.tags.iter().any(|source_tag| source_tag == &tag)
8827 })
8828 })
8829 .sorted_by_key(|(kind, _)| kind.to_owned())
8830 .collect();
8831 if let Some((leading_tag_source, _)) = tags.first() {
8832 // Strongest source wins; if we have worktree tag binding, prefer that to
8833 // global and language bindings;
8834 // if we have a global binding, prefer that to language binding.
8835 let first_mismatch = tags
8836 .iter()
8837 .position(|(tag_source, _)| tag_source != leading_tag_source);
8838 if let Some(index) = first_mismatch {
8839 tags.truncate(index);
8840 }
8841 }
8842
8843 tags
8844 }
8845
8846 pub fn move_to_enclosing_bracket(
8847 &mut self,
8848 _: &MoveToEnclosingBracket,
8849 cx: &mut ViewContext<Self>,
8850 ) {
8851 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8852 s.move_offsets_with(|snapshot, selection| {
8853 let Some(enclosing_bracket_ranges) =
8854 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
8855 else {
8856 return;
8857 };
8858
8859 let mut best_length = usize::MAX;
8860 let mut best_inside = false;
8861 let mut best_in_bracket_range = false;
8862 let mut best_destination = None;
8863 for (open, close) in enclosing_bracket_ranges {
8864 let close = close.to_inclusive();
8865 let length = close.end() - open.start;
8866 let inside = selection.start >= open.end && selection.end <= *close.start();
8867 let in_bracket_range = open.to_inclusive().contains(&selection.head())
8868 || close.contains(&selection.head());
8869
8870 // If best is next to a bracket and current isn't, skip
8871 if !in_bracket_range && best_in_bracket_range {
8872 continue;
8873 }
8874
8875 // Prefer smaller lengths unless best is inside and current isn't
8876 if length > best_length && (best_inside || !inside) {
8877 continue;
8878 }
8879
8880 best_length = length;
8881 best_inside = inside;
8882 best_in_bracket_range = in_bracket_range;
8883 best_destination = Some(
8884 if close.contains(&selection.start) && close.contains(&selection.end) {
8885 if inside {
8886 open.end
8887 } else {
8888 open.start
8889 }
8890 } else if inside {
8891 *close.start()
8892 } else {
8893 *close.end()
8894 },
8895 );
8896 }
8897
8898 if let Some(destination) = best_destination {
8899 selection.collapse_to(destination, SelectionGoal::None);
8900 }
8901 })
8902 });
8903 }
8904
8905 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
8906 self.end_selection(cx);
8907 self.selection_history.mode = SelectionHistoryMode::Undoing;
8908 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
8909 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8910 self.select_next_state = entry.select_next_state;
8911 self.select_prev_state = entry.select_prev_state;
8912 self.add_selections_state = entry.add_selections_state;
8913 self.request_autoscroll(Autoscroll::newest(), cx);
8914 }
8915 self.selection_history.mode = SelectionHistoryMode::Normal;
8916 }
8917
8918 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
8919 self.end_selection(cx);
8920 self.selection_history.mode = SelectionHistoryMode::Redoing;
8921 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
8922 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8923 self.select_next_state = entry.select_next_state;
8924 self.select_prev_state = entry.select_prev_state;
8925 self.add_selections_state = entry.add_selections_state;
8926 self.request_autoscroll(Autoscroll::newest(), cx);
8927 }
8928 self.selection_history.mode = SelectionHistoryMode::Normal;
8929 }
8930
8931 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
8932 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
8933 }
8934
8935 pub fn expand_excerpts_down(
8936 &mut self,
8937 action: &ExpandExcerptsDown,
8938 cx: &mut ViewContext<Self>,
8939 ) {
8940 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
8941 }
8942
8943 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
8944 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
8945 }
8946
8947 pub fn expand_excerpts_for_direction(
8948 &mut self,
8949 lines: u32,
8950 direction: ExpandExcerptDirection,
8951 cx: &mut ViewContext<Self>,
8952 ) {
8953 let selections = self.selections.disjoint_anchors();
8954
8955 let lines = if lines == 0 {
8956 EditorSettings::get_global(cx).expand_excerpt_lines
8957 } else {
8958 lines
8959 };
8960
8961 self.buffer.update(cx, |buffer, cx| {
8962 buffer.expand_excerpts(
8963 selections
8964 .iter()
8965 .map(|selection| selection.head().excerpt_id)
8966 .dedup(),
8967 lines,
8968 direction,
8969 cx,
8970 )
8971 })
8972 }
8973
8974 pub fn expand_excerpt(
8975 &mut self,
8976 excerpt: ExcerptId,
8977 direction: ExpandExcerptDirection,
8978 cx: &mut ViewContext<Self>,
8979 ) {
8980 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
8981 self.buffer.update(cx, |buffer, cx| {
8982 buffer.expand_excerpts([excerpt], lines, direction, cx)
8983 })
8984 }
8985
8986 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
8987 self.go_to_diagnostic_impl(Direction::Next, cx)
8988 }
8989
8990 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
8991 self.go_to_diagnostic_impl(Direction::Prev, cx)
8992 }
8993
8994 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
8995 let buffer = self.buffer.read(cx).snapshot(cx);
8996 let selection = self.selections.newest::<usize>(cx);
8997
8998 // If there is an active Diagnostic Popover jump to its diagnostic instead.
8999 if direction == Direction::Next {
9000 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9001 let (group_id, jump_to) = popover.activation_info();
9002 if self.activate_diagnostics(group_id, cx) {
9003 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9004 let mut new_selection = s.newest_anchor().clone();
9005 new_selection.collapse_to(jump_to, SelectionGoal::None);
9006 s.select_anchors(vec![new_selection.clone()]);
9007 });
9008 }
9009 return;
9010 }
9011 }
9012
9013 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9014 active_diagnostics
9015 .primary_range
9016 .to_offset(&buffer)
9017 .to_inclusive()
9018 });
9019 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9020 if active_primary_range.contains(&selection.head()) {
9021 *active_primary_range.start()
9022 } else {
9023 selection.head()
9024 }
9025 } else {
9026 selection.head()
9027 };
9028 let snapshot = self.snapshot(cx);
9029 loop {
9030 let diagnostics = if direction == Direction::Prev {
9031 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9032 } else {
9033 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9034 }
9035 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9036 let group = diagnostics
9037 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9038 // be sorted in a stable way
9039 // skip until we are at current active diagnostic, if it exists
9040 .skip_while(|entry| {
9041 (match direction {
9042 Direction::Prev => entry.range.start >= search_start,
9043 Direction::Next => entry.range.start <= search_start,
9044 }) && self
9045 .active_diagnostics
9046 .as_ref()
9047 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9048 })
9049 .find_map(|entry| {
9050 if entry.diagnostic.is_primary
9051 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9052 && !entry.range.is_empty()
9053 // if we match with the active diagnostic, skip it
9054 && Some(entry.diagnostic.group_id)
9055 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9056 {
9057 Some((entry.range, entry.diagnostic.group_id))
9058 } else {
9059 None
9060 }
9061 });
9062
9063 if let Some((primary_range, group_id)) = group {
9064 if self.activate_diagnostics(group_id, cx) {
9065 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9066 s.select(vec![Selection {
9067 id: selection.id,
9068 start: primary_range.start,
9069 end: primary_range.start,
9070 reversed: false,
9071 goal: SelectionGoal::None,
9072 }]);
9073 });
9074 }
9075 break;
9076 } else {
9077 // Cycle around to the start of the buffer, potentially moving back to the start of
9078 // the currently active diagnostic.
9079 active_primary_range.take();
9080 if direction == Direction::Prev {
9081 if search_start == buffer.len() {
9082 break;
9083 } else {
9084 search_start = buffer.len();
9085 }
9086 } else if search_start == 0 {
9087 break;
9088 } else {
9089 search_start = 0;
9090 }
9091 }
9092 }
9093 }
9094
9095 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9096 let snapshot = self.snapshot(cx);
9097 let selection = self.selections.newest::<Point>(cx);
9098 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9099 }
9100
9101 fn go_to_hunk_after_position(
9102 &mut self,
9103 snapshot: &EditorSnapshot,
9104 position: Point,
9105 cx: &mut ViewContext<'_, Editor>,
9106 ) -> Option<MultiBufferDiffHunk> {
9107 for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
9108 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9109 snapshot,
9110 position,
9111 ix > 0,
9112 snapshot.diff_map.diff_hunks_in_range(
9113 position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
9114 &snapshot.buffer_snapshot,
9115 ),
9116 cx,
9117 ) {
9118 return Some(hunk);
9119 }
9120 }
9121 None
9122 }
9123
9124 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9125 let snapshot = self.snapshot(cx);
9126 let selection = self.selections.newest::<Point>(cx);
9127 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9128 }
9129
9130 fn go_to_hunk_before_position(
9131 &mut self,
9132 snapshot: &EditorSnapshot,
9133 position: Point,
9134 cx: &mut ViewContext<'_, Editor>,
9135 ) -> Option<MultiBufferDiffHunk> {
9136 for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
9137 .into_iter()
9138 .enumerate()
9139 {
9140 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9141 snapshot,
9142 position,
9143 ix > 0,
9144 snapshot
9145 .diff_map
9146 .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
9147 cx,
9148 ) {
9149 return Some(hunk);
9150 }
9151 }
9152 None
9153 }
9154
9155 fn go_to_next_hunk_in_direction(
9156 &mut self,
9157 snapshot: &DisplaySnapshot,
9158 initial_point: Point,
9159 is_wrapped: bool,
9160 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9161 cx: &mut ViewContext<Editor>,
9162 ) -> Option<MultiBufferDiffHunk> {
9163 let display_point = initial_point.to_display_point(snapshot);
9164 let mut hunks = hunks
9165 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9166 .filter(|(display_hunk, _)| {
9167 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9168 })
9169 .dedup();
9170
9171 if let Some((display_hunk, hunk)) = hunks.next() {
9172 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9173 let row = display_hunk.start_display_row();
9174 let point = DisplayPoint::new(row, 0);
9175 s.select_display_ranges([point..point]);
9176 });
9177
9178 Some(hunk)
9179 } else {
9180 None
9181 }
9182 }
9183
9184 pub fn go_to_definition(
9185 &mut self,
9186 _: &GoToDefinition,
9187 cx: &mut ViewContext<Self>,
9188 ) -> Task<Result<Navigated>> {
9189 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9190 cx.spawn(|editor, mut cx| async move {
9191 if definition.await? == Navigated::Yes {
9192 return Ok(Navigated::Yes);
9193 }
9194 match editor.update(&mut cx, |editor, cx| {
9195 editor.find_all_references(&FindAllReferences, cx)
9196 })? {
9197 Some(references) => references.await,
9198 None => Ok(Navigated::No),
9199 }
9200 })
9201 }
9202
9203 pub fn go_to_declaration(
9204 &mut self,
9205 _: &GoToDeclaration,
9206 cx: &mut ViewContext<Self>,
9207 ) -> Task<Result<Navigated>> {
9208 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9209 }
9210
9211 pub fn go_to_declaration_split(
9212 &mut self,
9213 _: &GoToDeclaration,
9214 cx: &mut ViewContext<Self>,
9215 ) -> Task<Result<Navigated>> {
9216 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9217 }
9218
9219 pub fn go_to_implementation(
9220 &mut self,
9221 _: &GoToImplementation,
9222 cx: &mut ViewContext<Self>,
9223 ) -> Task<Result<Navigated>> {
9224 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9225 }
9226
9227 pub fn go_to_implementation_split(
9228 &mut self,
9229 _: &GoToImplementationSplit,
9230 cx: &mut ViewContext<Self>,
9231 ) -> Task<Result<Navigated>> {
9232 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9233 }
9234
9235 pub fn go_to_type_definition(
9236 &mut self,
9237 _: &GoToTypeDefinition,
9238 cx: &mut ViewContext<Self>,
9239 ) -> Task<Result<Navigated>> {
9240 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9241 }
9242
9243 pub fn go_to_definition_split(
9244 &mut self,
9245 _: &GoToDefinitionSplit,
9246 cx: &mut ViewContext<Self>,
9247 ) -> Task<Result<Navigated>> {
9248 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9249 }
9250
9251 pub fn go_to_type_definition_split(
9252 &mut self,
9253 _: &GoToTypeDefinitionSplit,
9254 cx: &mut ViewContext<Self>,
9255 ) -> Task<Result<Navigated>> {
9256 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9257 }
9258
9259 fn go_to_definition_of_kind(
9260 &mut self,
9261 kind: GotoDefinitionKind,
9262 split: bool,
9263 cx: &mut ViewContext<Self>,
9264 ) -> Task<Result<Navigated>> {
9265 let Some(provider) = self.semantics_provider.clone() else {
9266 return Task::ready(Ok(Navigated::No));
9267 };
9268 let head = self.selections.newest::<usize>(cx).head();
9269 let buffer = self.buffer.read(cx);
9270 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9271 text_anchor
9272 } else {
9273 return Task::ready(Ok(Navigated::No));
9274 };
9275
9276 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9277 return Task::ready(Ok(Navigated::No));
9278 };
9279
9280 cx.spawn(|editor, mut cx| async move {
9281 let definitions = definitions.await?;
9282 let navigated = editor
9283 .update(&mut cx, |editor, cx| {
9284 editor.navigate_to_hover_links(
9285 Some(kind),
9286 definitions
9287 .into_iter()
9288 .filter(|location| {
9289 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9290 })
9291 .map(HoverLink::Text)
9292 .collect::<Vec<_>>(),
9293 split,
9294 cx,
9295 )
9296 })?
9297 .await?;
9298 anyhow::Ok(navigated)
9299 })
9300 }
9301
9302 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9303 let selection = self.selections.newest_anchor();
9304 let head = selection.head();
9305 let tail = selection.tail();
9306
9307 let Some((buffer, start_position)) =
9308 self.buffer.read(cx).text_anchor_for_position(head, cx)
9309 else {
9310 return;
9311 };
9312
9313 let end_position = if head != tail {
9314 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
9315 return;
9316 };
9317 Some(pos)
9318 } else {
9319 None
9320 };
9321
9322 let url_finder = cx.spawn(|editor, mut cx| async move {
9323 let url = if let Some(end_pos) = end_position {
9324 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
9325 } else {
9326 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
9327 };
9328
9329 if let Some(url) = url {
9330 editor.update(&mut cx, |_, cx| {
9331 cx.open_url(&url);
9332 })
9333 } else {
9334 Ok(())
9335 }
9336 });
9337
9338 url_finder.detach();
9339 }
9340
9341 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9342 let Some(workspace) = self.workspace() else {
9343 return;
9344 };
9345
9346 let position = self.selections.newest_anchor().head();
9347
9348 let Some((buffer, buffer_position)) =
9349 self.buffer.read(cx).text_anchor_for_position(position, cx)
9350 else {
9351 return;
9352 };
9353
9354 let project = self.project.clone();
9355
9356 cx.spawn(|_, mut cx| async move {
9357 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9358
9359 if let Some((_, path)) = result {
9360 workspace
9361 .update(&mut cx, |workspace, cx| {
9362 workspace.open_resolved_path(path, cx)
9363 })?
9364 .await?;
9365 }
9366 anyhow::Ok(())
9367 })
9368 .detach();
9369 }
9370
9371 pub(crate) fn navigate_to_hover_links(
9372 &mut self,
9373 kind: Option<GotoDefinitionKind>,
9374 mut definitions: Vec<HoverLink>,
9375 split: bool,
9376 cx: &mut ViewContext<Editor>,
9377 ) -> Task<Result<Navigated>> {
9378 // If there is one definition, just open it directly
9379 if definitions.len() == 1 {
9380 let definition = definitions.pop().unwrap();
9381
9382 enum TargetTaskResult {
9383 Location(Option<Location>),
9384 AlreadyNavigated,
9385 }
9386
9387 let target_task = match definition {
9388 HoverLink::Text(link) => {
9389 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9390 }
9391 HoverLink::InlayHint(lsp_location, server_id) => {
9392 let computation = self.compute_target_location(lsp_location, server_id, cx);
9393 cx.background_executor().spawn(async move {
9394 let location = computation.await?;
9395 Ok(TargetTaskResult::Location(location))
9396 })
9397 }
9398 HoverLink::Url(url) => {
9399 cx.open_url(&url);
9400 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9401 }
9402 HoverLink::File(path) => {
9403 if let Some(workspace) = self.workspace() {
9404 cx.spawn(|_, mut cx| async move {
9405 workspace
9406 .update(&mut cx, |workspace, cx| {
9407 workspace.open_resolved_path(path, cx)
9408 })?
9409 .await
9410 .map(|_| TargetTaskResult::AlreadyNavigated)
9411 })
9412 } else {
9413 Task::ready(Ok(TargetTaskResult::Location(None)))
9414 }
9415 }
9416 };
9417 cx.spawn(|editor, mut cx| async move {
9418 let target = match target_task.await.context("target resolution task")? {
9419 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9420 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9421 TargetTaskResult::Location(Some(target)) => target,
9422 };
9423
9424 editor.update(&mut cx, |editor, cx| {
9425 let Some(workspace) = editor.workspace() else {
9426 return Navigated::No;
9427 };
9428 let pane = workspace.read(cx).active_pane().clone();
9429
9430 let range = target.range.to_offset(target.buffer.read(cx));
9431 let range = editor.range_for_match(&range);
9432
9433 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9434 let buffer = target.buffer.read(cx);
9435 let range = check_multiline_range(buffer, range);
9436 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9437 s.select_ranges([range]);
9438 });
9439 } else {
9440 cx.window_context().defer(move |cx| {
9441 let target_editor: View<Self> =
9442 workspace.update(cx, |workspace, cx| {
9443 let pane = if split {
9444 workspace.adjacent_pane(cx)
9445 } else {
9446 workspace.active_pane().clone()
9447 };
9448
9449 workspace.open_project_item(
9450 pane,
9451 target.buffer.clone(),
9452 true,
9453 true,
9454 cx,
9455 )
9456 });
9457 target_editor.update(cx, |target_editor, cx| {
9458 // When selecting a definition in a different buffer, disable the nav history
9459 // to avoid creating a history entry at the previous cursor location.
9460 pane.update(cx, |pane, _| pane.disable_history());
9461 let buffer = target.buffer.read(cx);
9462 let range = check_multiline_range(buffer, range);
9463 target_editor.change_selections(
9464 Some(Autoscroll::focused()),
9465 cx,
9466 |s| {
9467 s.select_ranges([range]);
9468 },
9469 );
9470 pane.update(cx, |pane, _| pane.enable_history());
9471 });
9472 });
9473 }
9474 Navigated::Yes
9475 })
9476 })
9477 } else if !definitions.is_empty() {
9478 cx.spawn(|editor, mut cx| async move {
9479 let (title, location_tasks, workspace) = editor
9480 .update(&mut cx, |editor, cx| {
9481 let tab_kind = match kind {
9482 Some(GotoDefinitionKind::Implementation) => "Implementations",
9483 _ => "Definitions",
9484 };
9485 let title = definitions
9486 .iter()
9487 .find_map(|definition| match definition {
9488 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9489 let buffer = origin.buffer.read(cx);
9490 format!(
9491 "{} for {}",
9492 tab_kind,
9493 buffer
9494 .text_for_range(origin.range.clone())
9495 .collect::<String>()
9496 )
9497 }),
9498 HoverLink::InlayHint(_, _) => None,
9499 HoverLink::Url(_) => None,
9500 HoverLink::File(_) => None,
9501 })
9502 .unwrap_or(tab_kind.to_string());
9503 let location_tasks = definitions
9504 .into_iter()
9505 .map(|definition| match definition {
9506 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
9507 HoverLink::InlayHint(lsp_location, server_id) => {
9508 editor.compute_target_location(lsp_location, server_id, cx)
9509 }
9510 HoverLink::Url(_) => Task::ready(Ok(None)),
9511 HoverLink::File(_) => Task::ready(Ok(None)),
9512 })
9513 .collect::<Vec<_>>();
9514 (title, location_tasks, editor.workspace().clone())
9515 })
9516 .context("location tasks preparation")?;
9517
9518 let locations = future::join_all(location_tasks)
9519 .await
9520 .into_iter()
9521 .filter_map(|location| location.transpose())
9522 .collect::<Result<_>>()
9523 .context("location tasks")?;
9524
9525 let Some(workspace) = workspace else {
9526 return Ok(Navigated::No);
9527 };
9528 let opened = workspace
9529 .update(&mut cx, |workspace, cx| {
9530 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9531 })
9532 .ok();
9533
9534 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9535 })
9536 } else {
9537 Task::ready(Ok(Navigated::No))
9538 }
9539 }
9540
9541 fn compute_target_location(
9542 &self,
9543 lsp_location: lsp::Location,
9544 server_id: LanguageServerId,
9545 cx: &mut ViewContext<Self>,
9546 ) -> Task<anyhow::Result<Option<Location>>> {
9547 let Some(project) = self.project.clone() else {
9548 return Task::ready(Ok(None));
9549 };
9550
9551 cx.spawn(move |editor, mut cx| async move {
9552 let location_task = editor.update(&mut cx, |_, cx| {
9553 project.update(cx, |project, cx| {
9554 let language_server_name = project
9555 .language_server_statuses(cx)
9556 .find(|(id, _)| server_id == *id)
9557 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
9558 language_server_name.map(|language_server_name| {
9559 project.open_local_buffer_via_lsp(
9560 lsp_location.uri.clone(),
9561 server_id,
9562 language_server_name,
9563 cx,
9564 )
9565 })
9566 })
9567 })?;
9568 let location = match location_task {
9569 Some(task) => Some({
9570 let target_buffer_handle = task.await.context("open local buffer")?;
9571 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9572 let target_start = target_buffer
9573 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9574 let target_end = target_buffer
9575 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9576 target_buffer.anchor_after(target_start)
9577 ..target_buffer.anchor_before(target_end)
9578 })?;
9579 Location {
9580 buffer: target_buffer_handle,
9581 range,
9582 }
9583 }),
9584 None => None,
9585 };
9586 Ok(location)
9587 })
9588 }
9589
9590 pub fn find_all_references(
9591 &mut self,
9592 _: &FindAllReferences,
9593 cx: &mut ViewContext<Self>,
9594 ) -> Option<Task<Result<Navigated>>> {
9595 let selection = self.selections.newest::<usize>(cx);
9596 let multi_buffer = self.buffer.read(cx);
9597 let head = selection.head();
9598
9599 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9600 let head_anchor = multi_buffer_snapshot.anchor_at(
9601 head,
9602 if head < selection.tail() {
9603 Bias::Right
9604 } else {
9605 Bias::Left
9606 },
9607 );
9608
9609 match self
9610 .find_all_references_task_sources
9611 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9612 {
9613 Ok(_) => {
9614 log::info!(
9615 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9616 );
9617 return None;
9618 }
9619 Err(i) => {
9620 self.find_all_references_task_sources.insert(i, head_anchor);
9621 }
9622 }
9623
9624 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9625 let workspace = self.workspace()?;
9626 let project = workspace.read(cx).project().clone();
9627 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9628 Some(cx.spawn(|editor, mut cx| async move {
9629 let _cleanup = defer({
9630 let mut cx = cx.clone();
9631 move || {
9632 let _ = editor.update(&mut cx, |editor, _| {
9633 if let Ok(i) =
9634 editor
9635 .find_all_references_task_sources
9636 .binary_search_by(|anchor| {
9637 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9638 })
9639 {
9640 editor.find_all_references_task_sources.remove(i);
9641 }
9642 });
9643 }
9644 });
9645
9646 let locations = references.await?;
9647 if locations.is_empty() {
9648 return anyhow::Ok(Navigated::No);
9649 }
9650
9651 workspace.update(&mut cx, |workspace, cx| {
9652 let title = locations
9653 .first()
9654 .as_ref()
9655 .map(|location| {
9656 let buffer = location.buffer.read(cx);
9657 format!(
9658 "References to `{}`",
9659 buffer
9660 .text_for_range(location.range.clone())
9661 .collect::<String>()
9662 )
9663 })
9664 .unwrap();
9665 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9666 Navigated::Yes
9667 })
9668 }))
9669 }
9670
9671 /// Opens a multibuffer with the given project locations in it
9672 pub fn open_locations_in_multibuffer(
9673 workspace: &mut Workspace,
9674 mut locations: Vec<Location>,
9675 title: String,
9676 split: bool,
9677 cx: &mut ViewContext<Workspace>,
9678 ) {
9679 // If there are multiple definitions, open them in a multibuffer
9680 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9681 let mut locations = locations.into_iter().peekable();
9682 let mut ranges_to_highlight = Vec::new();
9683 let capability = workspace.project().read(cx).capability();
9684
9685 let excerpt_buffer = cx.new_model(|cx| {
9686 let mut multibuffer = MultiBuffer::new(capability);
9687 while let Some(location) = locations.next() {
9688 let buffer = location.buffer.read(cx);
9689 let mut ranges_for_buffer = Vec::new();
9690 let range = location.range.to_offset(buffer);
9691 ranges_for_buffer.push(range.clone());
9692
9693 while let Some(next_location) = locations.peek() {
9694 if next_location.buffer == location.buffer {
9695 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9696 locations.next();
9697 } else {
9698 break;
9699 }
9700 }
9701
9702 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9703 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9704 location.buffer.clone(),
9705 ranges_for_buffer,
9706 DEFAULT_MULTIBUFFER_CONTEXT,
9707 cx,
9708 ))
9709 }
9710
9711 multibuffer.with_title(title)
9712 });
9713
9714 let editor = cx.new_view(|cx| {
9715 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9716 });
9717 editor.update(cx, |editor, cx| {
9718 if let Some(first_range) = ranges_to_highlight.first() {
9719 editor.change_selections(None, cx, |selections| {
9720 selections.clear_disjoint();
9721 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9722 });
9723 }
9724 editor.highlight_background::<Self>(
9725 &ranges_to_highlight,
9726 |theme| theme.editor_highlighted_line_background,
9727 cx,
9728 );
9729 editor.register_buffers_with_language_servers(cx);
9730 });
9731
9732 let item = Box::new(editor);
9733 let item_id = item.item_id();
9734
9735 if split {
9736 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9737 } else {
9738 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9739 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9740 pane.close_current_preview_item(cx)
9741 } else {
9742 None
9743 }
9744 });
9745 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9746 }
9747 workspace.active_pane().update(cx, |pane, cx| {
9748 pane.set_preview_item_id(Some(item_id), cx);
9749 });
9750 }
9751
9752 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9753 use language::ToOffset as _;
9754
9755 let provider = self.semantics_provider.clone()?;
9756 let selection = self.selections.newest_anchor().clone();
9757 let (cursor_buffer, cursor_buffer_position) = self
9758 .buffer
9759 .read(cx)
9760 .text_anchor_for_position(selection.head(), cx)?;
9761 let (tail_buffer, cursor_buffer_position_end) = self
9762 .buffer
9763 .read(cx)
9764 .text_anchor_for_position(selection.tail(), cx)?;
9765 if tail_buffer != cursor_buffer {
9766 return None;
9767 }
9768
9769 let snapshot = cursor_buffer.read(cx).snapshot();
9770 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9771 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9772 let prepare_rename = provider
9773 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
9774 .unwrap_or_else(|| Task::ready(Ok(None)));
9775 drop(snapshot);
9776
9777 Some(cx.spawn(|this, mut cx| async move {
9778 let rename_range = if let Some(range) = prepare_rename.await? {
9779 Some(range)
9780 } else {
9781 this.update(&mut cx, |this, cx| {
9782 let buffer = this.buffer.read(cx).snapshot(cx);
9783 let mut buffer_highlights = this
9784 .document_highlights_for_position(selection.head(), &buffer)
9785 .filter(|highlight| {
9786 highlight.start.excerpt_id == selection.head().excerpt_id
9787 && highlight.end.excerpt_id == selection.head().excerpt_id
9788 });
9789 buffer_highlights
9790 .next()
9791 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9792 })?
9793 };
9794 if let Some(rename_range) = rename_range {
9795 this.update(&mut cx, |this, cx| {
9796 let snapshot = cursor_buffer.read(cx).snapshot();
9797 let rename_buffer_range = rename_range.to_offset(&snapshot);
9798 let cursor_offset_in_rename_range =
9799 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9800 let cursor_offset_in_rename_range_end =
9801 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9802
9803 this.take_rename(false, cx);
9804 let buffer = this.buffer.read(cx).read(cx);
9805 let cursor_offset = selection.head().to_offset(&buffer);
9806 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9807 let rename_end = rename_start + rename_buffer_range.len();
9808 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9809 let mut old_highlight_id = None;
9810 let old_name: Arc<str> = buffer
9811 .chunks(rename_start..rename_end, true)
9812 .map(|chunk| {
9813 if old_highlight_id.is_none() {
9814 old_highlight_id = chunk.syntax_highlight_id;
9815 }
9816 chunk.text
9817 })
9818 .collect::<String>()
9819 .into();
9820
9821 drop(buffer);
9822
9823 // Position the selection in the rename editor so that it matches the current selection.
9824 this.show_local_selections = false;
9825 let rename_editor = cx.new_view(|cx| {
9826 let mut editor = Editor::single_line(cx);
9827 editor.buffer.update(cx, |buffer, cx| {
9828 buffer.edit([(0..0, old_name.clone())], None, cx)
9829 });
9830 let rename_selection_range = match cursor_offset_in_rename_range
9831 .cmp(&cursor_offset_in_rename_range_end)
9832 {
9833 Ordering::Equal => {
9834 editor.select_all(&SelectAll, cx);
9835 return editor;
9836 }
9837 Ordering::Less => {
9838 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9839 }
9840 Ordering::Greater => {
9841 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9842 }
9843 };
9844 if rename_selection_range.end > old_name.len() {
9845 editor.select_all(&SelectAll, cx);
9846 } else {
9847 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9848 s.select_ranges([rename_selection_range]);
9849 });
9850 }
9851 editor
9852 });
9853 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
9854 if e == &EditorEvent::Focused {
9855 cx.emit(EditorEvent::FocusedIn)
9856 }
9857 })
9858 .detach();
9859
9860 let write_highlights =
9861 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
9862 let read_highlights =
9863 this.clear_background_highlights::<DocumentHighlightRead>(cx);
9864 let ranges = write_highlights
9865 .iter()
9866 .flat_map(|(_, ranges)| ranges.iter())
9867 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
9868 .cloned()
9869 .collect();
9870
9871 this.highlight_text::<Rename>(
9872 ranges,
9873 HighlightStyle {
9874 fade_out: Some(0.6),
9875 ..Default::default()
9876 },
9877 cx,
9878 );
9879 let rename_focus_handle = rename_editor.focus_handle(cx);
9880 cx.focus(&rename_focus_handle);
9881 let block_id = this.insert_blocks(
9882 [BlockProperties {
9883 style: BlockStyle::Flex,
9884 placement: BlockPlacement::Below(range.start),
9885 height: 1,
9886 render: Arc::new({
9887 let rename_editor = rename_editor.clone();
9888 move |cx: &mut BlockContext| {
9889 let mut text_style = cx.editor_style.text.clone();
9890 if let Some(highlight_style) = old_highlight_id
9891 .and_then(|h| h.style(&cx.editor_style.syntax))
9892 {
9893 text_style = text_style.highlight(highlight_style);
9894 }
9895 div()
9896 .block_mouse_down()
9897 .pl(cx.anchor_x)
9898 .child(EditorElement::new(
9899 &rename_editor,
9900 EditorStyle {
9901 background: cx.theme().system().transparent,
9902 local_player: cx.editor_style.local_player,
9903 text: text_style,
9904 scrollbar_width: cx.editor_style.scrollbar_width,
9905 syntax: cx.editor_style.syntax.clone(),
9906 status: cx.editor_style.status.clone(),
9907 inlay_hints_style: HighlightStyle {
9908 font_weight: Some(FontWeight::BOLD),
9909 ..make_inlay_hints_style(cx)
9910 },
9911 inline_completion_styles: make_suggestion_styles(
9912 cx,
9913 ),
9914 ..EditorStyle::default()
9915 },
9916 ))
9917 .into_any_element()
9918 }
9919 }),
9920 priority: 0,
9921 }],
9922 Some(Autoscroll::fit()),
9923 cx,
9924 )[0];
9925 this.pending_rename = Some(RenameState {
9926 range,
9927 old_name,
9928 editor: rename_editor,
9929 block_id,
9930 });
9931 })?;
9932 }
9933
9934 Ok(())
9935 }))
9936 }
9937
9938 pub fn confirm_rename(
9939 &mut self,
9940 _: &ConfirmRename,
9941 cx: &mut ViewContext<Self>,
9942 ) -> Option<Task<Result<()>>> {
9943 let rename = self.take_rename(false, cx)?;
9944 let workspace = self.workspace()?.downgrade();
9945 let (buffer, start) = self
9946 .buffer
9947 .read(cx)
9948 .text_anchor_for_position(rename.range.start, cx)?;
9949 let (end_buffer, _) = self
9950 .buffer
9951 .read(cx)
9952 .text_anchor_for_position(rename.range.end, cx)?;
9953 if buffer != end_buffer {
9954 return None;
9955 }
9956
9957 let old_name = rename.old_name;
9958 let new_name = rename.editor.read(cx).text(cx);
9959
9960 let rename = self.semantics_provider.as_ref()?.perform_rename(
9961 &buffer,
9962 start,
9963 new_name.clone(),
9964 cx,
9965 )?;
9966
9967 Some(cx.spawn(|editor, mut cx| async move {
9968 let project_transaction = rename.await?;
9969 Self::open_project_transaction(
9970 &editor,
9971 workspace,
9972 project_transaction,
9973 format!("Rename: {} → {}", old_name, new_name),
9974 cx.clone(),
9975 )
9976 .await?;
9977
9978 editor.update(&mut cx, |editor, cx| {
9979 editor.refresh_document_highlights(cx);
9980 })?;
9981 Ok(())
9982 }))
9983 }
9984
9985 fn take_rename(
9986 &mut self,
9987 moving_cursor: bool,
9988 cx: &mut ViewContext<Self>,
9989 ) -> Option<RenameState> {
9990 let rename = self.pending_rename.take()?;
9991 if rename.editor.focus_handle(cx).is_focused(cx) {
9992 cx.focus(&self.focus_handle);
9993 }
9994
9995 self.remove_blocks(
9996 [rename.block_id].into_iter().collect(),
9997 Some(Autoscroll::fit()),
9998 cx,
9999 );
10000 self.clear_highlights::<Rename>(cx);
10001 self.show_local_selections = true;
10002
10003 if moving_cursor {
10004 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10005 editor.selections.newest::<usize>(cx).head()
10006 });
10007
10008 // Update the selection to match the position of the selection inside
10009 // the rename editor.
10010 let snapshot = self.buffer.read(cx).read(cx);
10011 let rename_range = rename.range.to_offset(&snapshot);
10012 let cursor_in_editor = snapshot
10013 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10014 .min(rename_range.end);
10015 drop(snapshot);
10016
10017 self.change_selections(None, cx, |s| {
10018 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10019 });
10020 } else {
10021 self.refresh_document_highlights(cx);
10022 }
10023
10024 Some(rename)
10025 }
10026
10027 pub fn pending_rename(&self) -> Option<&RenameState> {
10028 self.pending_rename.as_ref()
10029 }
10030
10031 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10032 let project = match &self.project {
10033 Some(project) => project.clone(),
10034 None => return None,
10035 };
10036
10037 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10038 }
10039
10040 fn format_selections(
10041 &mut self,
10042 _: &FormatSelections,
10043 cx: &mut ViewContext<Self>,
10044 ) -> Option<Task<Result<()>>> {
10045 let project = match &self.project {
10046 Some(project) => project.clone(),
10047 None => return None,
10048 };
10049
10050 let selections = self
10051 .selections
10052 .all_adjusted(cx)
10053 .into_iter()
10054 .filter(|s| !s.is_empty())
10055 .collect_vec();
10056
10057 Some(self.perform_format(
10058 project,
10059 FormatTrigger::Manual,
10060 FormatTarget::Ranges(selections),
10061 cx,
10062 ))
10063 }
10064
10065 fn perform_format(
10066 &mut self,
10067 project: Model<Project>,
10068 trigger: FormatTrigger,
10069 target: FormatTarget,
10070 cx: &mut ViewContext<Self>,
10071 ) -> Task<Result<()>> {
10072 let buffer = self.buffer().clone();
10073 let mut buffers = buffer.read(cx).all_buffers();
10074 if trigger == FormatTrigger::Save {
10075 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10076 }
10077
10078 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10079 let format = project.update(cx, |project, cx| {
10080 project.format(buffers, true, trigger, target, cx)
10081 });
10082
10083 cx.spawn(|_, mut cx| async move {
10084 let transaction = futures::select_biased! {
10085 () = timeout => {
10086 log::warn!("timed out waiting for formatting");
10087 None
10088 }
10089 transaction = format.log_err().fuse() => transaction,
10090 };
10091
10092 buffer
10093 .update(&mut cx, |buffer, cx| {
10094 if let Some(transaction) = transaction {
10095 if !buffer.is_singleton() {
10096 buffer.push_transaction(&transaction.0, cx);
10097 }
10098 }
10099
10100 cx.notify();
10101 })
10102 .ok();
10103
10104 Ok(())
10105 })
10106 }
10107
10108 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10109 if let Some(project) = self.project.clone() {
10110 self.buffer.update(cx, |multi_buffer, cx| {
10111 project.update(cx, |project, cx| {
10112 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10113 });
10114 })
10115 }
10116 }
10117
10118 fn cancel_language_server_work(
10119 &mut self,
10120 _: &actions::CancelLanguageServerWork,
10121 cx: &mut ViewContext<Self>,
10122 ) {
10123 if let Some(project) = self.project.clone() {
10124 self.buffer.update(cx, |multi_buffer, cx| {
10125 project.update(cx, |project, cx| {
10126 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10127 });
10128 })
10129 }
10130 }
10131
10132 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10133 cx.show_character_palette();
10134 }
10135
10136 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10137 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10138 let buffer = self.buffer.read(cx).snapshot(cx);
10139 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10140 let is_valid = buffer
10141 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10142 .any(|entry| {
10143 entry.diagnostic.is_primary
10144 && !entry.range.is_empty()
10145 && entry.range.start == primary_range_start
10146 && entry.diagnostic.message == active_diagnostics.primary_message
10147 });
10148
10149 if is_valid != active_diagnostics.is_valid {
10150 active_diagnostics.is_valid = is_valid;
10151 let mut new_styles = HashMap::default();
10152 for (block_id, diagnostic) in &active_diagnostics.blocks {
10153 new_styles.insert(
10154 *block_id,
10155 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10156 );
10157 }
10158 self.display_map.update(cx, |display_map, _cx| {
10159 display_map.replace_blocks(new_styles)
10160 });
10161 }
10162 }
10163 }
10164
10165 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10166 self.dismiss_diagnostics(cx);
10167 let snapshot = self.snapshot(cx);
10168 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10169 let buffer = self.buffer.read(cx).snapshot(cx);
10170
10171 let mut primary_range = None;
10172 let mut primary_message = None;
10173 let mut group_end = Point::zero();
10174 let diagnostic_group = buffer
10175 .diagnostic_group::<MultiBufferPoint>(group_id)
10176 .filter_map(|entry| {
10177 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10178 && (entry.range.start.row == entry.range.end.row
10179 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10180 {
10181 return None;
10182 }
10183 if entry.range.end > group_end {
10184 group_end = entry.range.end;
10185 }
10186 if entry.diagnostic.is_primary {
10187 primary_range = Some(entry.range.clone());
10188 primary_message = Some(entry.diagnostic.message.clone());
10189 }
10190 Some(entry)
10191 })
10192 .collect::<Vec<_>>();
10193 let primary_range = primary_range?;
10194 let primary_message = primary_message?;
10195 let primary_range =
10196 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10197
10198 let blocks = display_map
10199 .insert_blocks(
10200 diagnostic_group.iter().map(|entry| {
10201 let diagnostic = entry.diagnostic.clone();
10202 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10203 BlockProperties {
10204 style: BlockStyle::Fixed,
10205 placement: BlockPlacement::Below(
10206 buffer.anchor_after(entry.range.start),
10207 ),
10208 height: message_height,
10209 render: diagnostic_block_renderer(diagnostic, None, true, true),
10210 priority: 0,
10211 }
10212 }),
10213 cx,
10214 )
10215 .into_iter()
10216 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10217 .collect();
10218
10219 Some(ActiveDiagnosticGroup {
10220 primary_range,
10221 primary_message,
10222 group_id,
10223 blocks,
10224 is_valid: true,
10225 })
10226 });
10227 self.active_diagnostics.is_some()
10228 }
10229
10230 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10231 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10232 self.display_map.update(cx, |display_map, cx| {
10233 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10234 });
10235 cx.notify();
10236 }
10237 }
10238
10239 pub fn set_selections_from_remote(
10240 &mut self,
10241 selections: Vec<Selection<Anchor>>,
10242 pending_selection: Option<Selection<Anchor>>,
10243 cx: &mut ViewContext<Self>,
10244 ) {
10245 let old_cursor_position = self.selections.newest_anchor().head();
10246 self.selections.change_with(cx, |s| {
10247 s.select_anchors(selections);
10248 if let Some(pending_selection) = pending_selection {
10249 s.set_pending(pending_selection, SelectMode::Character);
10250 } else {
10251 s.clear_pending();
10252 }
10253 });
10254 self.selections_did_change(false, &old_cursor_position, true, cx);
10255 }
10256
10257 fn push_to_selection_history(&mut self) {
10258 self.selection_history.push(SelectionHistoryEntry {
10259 selections: self.selections.disjoint_anchors(),
10260 select_next_state: self.select_next_state.clone(),
10261 select_prev_state: self.select_prev_state.clone(),
10262 add_selections_state: self.add_selections_state.clone(),
10263 });
10264 }
10265
10266 pub fn transact(
10267 &mut self,
10268 cx: &mut ViewContext<Self>,
10269 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10270 ) -> Option<TransactionId> {
10271 self.start_transaction_at(Instant::now(), cx);
10272 update(self, cx);
10273 self.end_transaction_at(Instant::now(), cx)
10274 }
10275
10276 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10277 self.end_selection(cx);
10278 if let Some(tx_id) = self
10279 .buffer
10280 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10281 {
10282 self.selection_history
10283 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10284 cx.emit(EditorEvent::TransactionBegun {
10285 transaction_id: tx_id,
10286 })
10287 }
10288 }
10289
10290 fn end_transaction_at(
10291 &mut self,
10292 now: Instant,
10293 cx: &mut ViewContext<Self>,
10294 ) -> Option<TransactionId> {
10295 if let Some(transaction_id) = self
10296 .buffer
10297 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10298 {
10299 if let Some((_, end_selections)) =
10300 self.selection_history.transaction_mut(transaction_id)
10301 {
10302 *end_selections = Some(self.selections.disjoint_anchors());
10303 } else {
10304 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10305 }
10306
10307 cx.emit(EditorEvent::Edited { transaction_id });
10308 Some(transaction_id)
10309 } else {
10310 None
10311 }
10312 }
10313
10314 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10315 if self.is_singleton(cx) {
10316 let selection = self.selections.newest::<Point>(cx);
10317
10318 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10319 let range = if selection.is_empty() {
10320 let point = selection.head().to_display_point(&display_map);
10321 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10322 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10323 .to_point(&display_map);
10324 start..end
10325 } else {
10326 selection.range()
10327 };
10328 if display_map.folds_in_range(range).next().is_some() {
10329 self.unfold_lines(&Default::default(), cx)
10330 } else {
10331 self.fold(&Default::default(), cx)
10332 }
10333 } else {
10334 let (display_snapshot, selections) = self.selections.all_adjusted_display(cx);
10335 let mut toggled_buffers = HashSet::default();
10336 for selection in selections {
10337 if let Some(buffer_id) = display_snapshot
10338 .display_point_to_anchor(selection.head(), Bias::Right)
10339 .buffer_id
10340 {
10341 if toggled_buffers.insert(buffer_id) {
10342 if self.buffer_folded(buffer_id, cx) {
10343 self.unfold_buffer(buffer_id, cx);
10344 } else {
10345 self.fold_buffer(buffer_id, cx);
10346 }
10347 }
10348 }
10349 if let Some(buffer_id) = display_snapshot
10350 .display_point_to_anchor(selection.tail(), Bias::Left)
10351 .buffer_id
10352 {
10353 if toggled_buffers.insert(buffer_id) {
10354 if self.buffer_folded(buffer_id, cx) {
10355 self.unfold_buffer(buffer_id, cx);
10356 } else {
10357 self.fold_buffer(buffer_id, cx);
10358 }
10359 }
10360 }
10361 }
10362 }
10363 }
10364
10365 pub fn toggle_fold_recursive(
10366 &mut self,
10367 _: &actions::ToggleFoldRecursive,
10368 cx: &mut ViewContext<Self>,
10369 ) {
10370 let selection = self.selections.newest::<Point>(cx);
10371
10372 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10373 let range = if selection.is_empty() {
10374 let point = selection.head().to_display_point(&display_map);
10375 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10376 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10377 .to_point(&display_map);
10378 start..end
10379 } else {
10380 selection.range()
10381 };
10382 if display_map.folds_in_range(range).next().is_some() {
10383 self.unfold_recursive(&Default::default(), cx)
10384 } else {
10385 self.fold_recursive(&Default::default(), cx)
10386 }
10387 }
10388
10389 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10390 if self.is_singleton(cx) {
10391 let mut to_fold = Vec::new();
10392 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10393 let selections = self.selections.all_adjusted(cx);
10394
10395 for selection in selections {
10396 let range = selection.range().sorted();
10397 let buffer_start_row = range.start.row;
10398
10399 if range.start.row != range.end.row {
10400 let mut found = false;
10401 let mut row = range.start.row;
10402 while row <= range.end.row {
10403 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10404 {
10405 found = true;
10406 row = crease.range().end.row + 1;
10407 to_fold.push(crease);
10408 } else {
10409 row += 1
10410 }
10411 }
10412 if found {
10413 continue;
10414 }
10415 }
10416
10417 for row in (0..=range.start.row).rev() {
10418 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10419 if crease.range().end.row >= buffer_start_row {
10420 to_fold.push(crease);
10421 if row <= range.start.row {
10422 break;
10423 }
10424 }
10425 }
10426 }
10427 }
10428
10429 self.fold_creases(to_fold, true, cx);
10430 } else {
10431 let (display_snapshot, selections) = self.selections.all_adjusted_display(cx);
10432 let mut folded_buffers = HashSet::default();
10433 for selection in selections {
10434 if let Some(buffer_id) = display_snapshot
10435 .display_point_to_anchor(selection.head(), Bias::Right)
10436 .buffer_id
10437 {
10438 if folded_buffers.insert(buffer_id) {
10439 self.fold_buffer(buffer_id, cx);
10440 }
10441 }
10442 if let Some(buffer_id) = display_snapshot
10443 .display_point_to_anchor(selection.tail(), Bias::Left)
10444 .buffer_id
10445 {
10446 if folded_buffers.insert(buffer_id) {
10447 self.fold_buffer(buffer_id, cx);
10448 }
10449 }
10450 }
10451 }
10452 }
10453
10454 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10455 if !self.buffer.read(cx).is_singleton() {
10456 return;
10457 }
10458
10459 let fold_at_level = fold_at.level;
10460 let snapshot = self.buffer.read(cx).snapshot(cx);
10461 let mut to_fold = Vec::new();
10462 let mut stack = vec![(0, snapshot.max_row().0, 1)];
10463
10464 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10465 while start_row < end_row {
10466 match self
10467 .snapshot(cx)
10468 .crease_for_buffer_row(MultiBufferRow(start_row))
10469 {
10470 Some(crease) => {
10471 let nested_start_row = crease.range().start.row + 1;
10472 let nested_end_row = crease.range().end.row;
10473
10474 if current_level < fold_at_level {
10475 stack.push((nested_start_row, nested_end_row, current_level + 1));
10476 } else if current_level == fold_at_level {
10477 to_fold.push(crease);
10478 }
10479
10480 start_row = nested_end_row + 1;
10481 }
10482 None => start_row += 1,
10483 }
10484 }
10485 }
10486
10487 self.fold_creases(to_fold, true, cx);
10488 }
10489
10490 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10491 if self.buffer.read(cx).is_singleton() {
10492 let mut fold_ranges = Vec::new();
10493 let snapshot = self.buffer.read(cx).snapshot(cx);
10494
10495 for row in 0..snapshot.max_row().0 {
10496 if let Some(foldable_range) =
10497 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10498 {
10499 fold_ranges.push(foldable_range);
10500 }
10501 }
10502
10503 self.fold_creases(fold_ranges, true, cx);
10504 } else {
10505 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10506 editor
10507 .update(&mut cx, |editor, cx| {
10508 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10509 editor.fold_buffer(buffer_id, cx);
10510 }
10511 })
10512 .ok();
10513 });
10514 }
10515 }
10516
10517 pub fn fold_function_bodies(
10518 &mut self,
10519 _: &actions::FoldFunctionBodies,
10520 cx: &mut ViewContext<Self>,
10521 ) {
10522 let snapshot = self.buffer.read(cx).snapshot(cx);
10523 let Some((_, _, buffer)) = snapshot.as_singleton() else {
10524 return;
10525 };
10526 let creases = buffer
10527 .function_body_fold_ranges(0..buffer.len())
10528 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10529 .collect();
10530
10531 self.fold_creases(creases, true, cx);
10532 }
10533
10534 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10535 let mut to_fold = Vec::new();
10536 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10537 let selections = self.selections.all_adjusted(cx);
10538
10539 for selection in selections {
10540 let range = selection.range().sorted();
10541 let buffer_start_row = range.start.row;
10542
10543 if range.start.row != range.end.row {
10544 let mut found = false;
10545 for row in range.start.row..=range.end.row {
10546 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10547 found = true;
10548 to_fold.push(crease);
10549 }
10550 }
10551 if found {
10552 continue;
10553 }
10554 }
10555
10556 for row in (0..=range.start.row).rev() {
10557 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10558 if crease.range().end.row >= buffer_start_row {
10559 to_fold.push(crease);
10560 } else {
10561 break;
10562 }
10563 }
10564 }
10565 }
10566
10567 self.fold_creases(to_fold, true, cx);
10568 }
10569
10570 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10571 let buffer_row = fold_at.buffer_row;
10572 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10573
10574 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10575 let autoscroll = self
10576 .selections
10577 .all::<Point>(cx)
10578 .iter()
10579 .any(|selection| crease.range().overlaps(&selection.range()));
10580
10581 self.fold_creases(vec![crease], autoscroll, cx);
10582 }
10583 }
10584
10585 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10586 if self.is_singleton(cx) {
10587 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10588 let buffer = &display_map.buffer_snapshot;
10589 let selections = self.selections.all::<Point>(cx);
10590 let ranges = selections
10591 .iter()
10592 .map(|s| {
10593 let range = s.display_range(&display_map).sorted();
10594 let mut start = range.start.to_point(&display_map);
10595 let mut end = range.end.to_point(&display_map);
10596 start.column = 0;
10597 end.column = buffer.line_len(MultiBufferRow(end.row));
10598 start..end
10599 })
10600 .collect::<Vec<_>>();
10601
10602 self.unfold_ranges(&ranges, true, true, cx);
10603 } else {
10604 let (display_snapshot, selections) = self.selections.all_adjusted_display(cx);
10605 let mut unfolded_buffers = HashSet::default();
10606 for selection in selections {
10607 if let Some(buffer_id) = display_snapshot
10608 .display_point_to_anchor(selection.head(), Bias::Right)
10609 .buffer_id
10610 {
10611 if unfolded_buffers.insert(buffer_id) {
10612 self.unfold_buffer(buffer_id, cx);
10613 }
10614 }
10615 if let Some(buffer_id) = display_snapshot
10616 .display_point_to_anchor(selection.tail(), Bias::Left)
10617 .buffer_id
10618 {
10619 if unfolded_buffers.insert(buffer_id) {
10620 self.unfold_buffer(buffer_id, cx);
10621 }
10622 }
10623 }
10624 }
10625 }
10626
10627 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10628 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10629 let selections = self.selections.all::<Point>(cx);
10630 let ranges = selections
10631 .iter()
10632 .map(|s| {
10633 let mut range = s.display_range(&display_map).sorted();
10634 *range.start.column_mut() = 0;
10635 *range.end.column_mut() = display_map.line_len(range.end.row());
10636 let start = range.start.to_point(&display_map);
10637 let end = range.end.to_point(&display_map);
10638 start..end
10639 })
10640 .collect::<Vec<_>>();
10641
10642 self.unfold_ranges(&ranges, true, true, cx);
10643 }
10644
10645 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10646 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10647
10648 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10649 ..Point::new(
10650 unfold_at.buffer_row.0,
10651 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10652 );
10653
10654 let autoscroll = self
10655 .selections
10656 .all::<Point>(cx)
10657 .iter()
10658 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10659
10660 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10661 }
10662
10663 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10664 if self.buffer.read(cx).is_singleton() {
10665 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10666 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10667 } else {
10668 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10669 editor
10670 .update(&mut cx, |editor, cx| {
10671 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10672 editor.unfold_buffer(buffer_id, cx);
10673 }
10674 })
10675 .ok();
10676 });
10677 }
10678 }
10679
10680 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10681 let selections = self.selections.all::<Point>(cx);
10682 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10683 let line_mode = self.selections.line_mode;
10684 let ranges = selections
10685 .into_iter()
10686 .map(|s| {
10687 if line_mode {
10688 let start = Point::new(s.start.row, 0);
10689 let end = Point::new(
10690 s.end.row,
10691 display_map
10692 .buffer_snapshot
10693 .line_len(MultiBufferRow(s.end.row)),
10694 );
10695 Crease::simple(start..end, display_map.fold_placeholder.clone())
10696 } else {
10697 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10698 }
10699 })
10700 .collect::<Vec<_>>();
10701 self.fold_creases(ranges, true, cx);
10702 }
10703
10704 pub fn fold_creases<T: ToOffset + Clone>(
10705 &mut self,
10706 creases: Vec<Crease<T>>,
10707 auto_scroll: bool,
10708 cx: &mut ViewContext<Self>,
10709 ) {
10710 if creases.is_empty() {
10711 return;
10712 }
10713
10714 let mut buffers_affected = HashSet::default();
10715 let multi_buffer = self.buffer().read(cx);
10716 for crease in &creases {
10717 if let Some((_, buffer, _)) =
10718 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10719 {
10720 buffers_affected.insert(buffer.read(cx).remote_id());
10721 };
10722 }
10723
10724 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10725
10726 if auto_scroll {
10727 self.request_autoscroll(Autoscroll::fit(), cx);
10728 }
10729
10730 for buffer_id in buffers_affected {
10731 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10732 }
10733
10734 cx.notify();
10735
10736 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10737 // Clear diagnostics block when folding a range that contains it.
10738 let snapshot = self.snapshot(cx);
10739 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10740 drop(snapshot);
10741 self.active_diagnostics = Some(active_diagnostics);
10742 self.dismiss_diagnostics(cx);
10743 } else {
10744 self.active_diagnostics = Some(active_diagnostics);
10745 }
10746 }
10747
10748 self.scrollbar_marker_state.dirty = true;
10749 }
10750
10751 /// Removes any folds whose ranges intersect any of the given ranges.
10752 pub fn unfold_ranges<T: ToOffset + Clone>(
10753 &mut self,
10754 ranges: &[Range<T>],
10755 inclusive: bool,
10756 auto_scroll: bool,
10757 cx: &mut ViewContext<Self>,
10758 ) {
10759 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10760 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10761 });
10762 }
10763
10764 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10765 if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10766 return;
10767 }
10768 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10769 return;
10770 };
10771 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10772 self.display_map
10773 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10774 cx.emit(EditorEvent::BufferFoldToggled {
10775 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
10776 folded: true,
10777 });
10778 cx.notify();
10779 }
10780
10781 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10782 if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
10783 return;
10784 }
10785 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10786 return;
10787 };
10788 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10789 self.display_map.update(cx, |display_map, cx| {
10790 display_map.unfold_buffer(buffer_id, cx);
10791 });
10792 cx.emit(EditorEvent::BufferFoldToggled {
10793 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
10794 folded: false,
10795 });
10796 cx.notify();
10797 }
10798
10799 pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
10800 self.display_map.read(cx).buffer_folded(buffer)
10801 }
10802
10803 /// Removes any folds with the given ranges.
10804 pub fn remove_folds_with_type<T: ToOffset + Clone>(
10805 &mut self,
10806 ranges: &[Range<T>],
10807 type_id: TypeId,
10808 auto_scroll: bool,
10809 cx: &mut ViewContext<Self>,
10810 ) {
10811 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10812 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
10813 });
10814 }
10815
10816 fn remove_folds_with<T: ToOffset + Clone>(
10817 &mut self,
10818 ranges: &[Range<T>],
10819 auto_scroll: bool,
10820 cx: &mut ViewContext<Self>,
10821 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
10822 ) {
10823 if ranges.is_empty() {
10824 return;
10825 }
10826
10827 let mut buffers_affected = HashSet::default();
10828 let multi_buffer = self.buffer().read(cx);
10829 for range in ranges {
10830 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10831 buffers_affected.insert(buffer.read(cx).remote_id());
10832 };
10833 }
10834
10835 self.display_map.update(cx, update);
10836
10837 if auto_scroll {
10838 self.request_autoscroll(Autoscroll::fit(), cx);
10839 }
10840
10841 for buffer_id in buffers_affected {
10842 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10843 }
10844
10845 cx.notify();
10846 self.scrollbar_marker_state.dirty = true;
10847 self.active_indent_guides_state.dirty = true;
10848 }
10849
10850 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10851 self.display_map.read(cx).fold_placeholder.clone()
10852 }
10853
10854 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10855 if hovered != self.gutter_hovered {
10856 self.gutter_hovered = hovered;
10857 cx.notify();
10858 }
10859 }
10860
10861 pub fn insert_blocks(
10862 &mut self,
10863 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10864 autoscroll: Option<Autoscroll>,
10865 cx: &mut ViewContext<Self>,
10866 ) -> Vec<CustomBlockId> {
10867 let blocks = self
10868 .display_map
10869 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10870 if let Some(autoscroll) = autoscroll {
10871 self.request_autoscroll(autoscroll, cx);
10872 }
10873 cx.notify();
10874 blocks
10875 }
10876
10877 pub fn resize_blocks(
10878 &mut self,
10879 heights: HashMap<CustomBlockId, u32>,
10880 autoscroll: Option<Autoscroll>,
10881 cx: &mut ViewContext<Self>,
10882 ) {
10883 self.display_map
10884 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10885 if let Some(autoscroll) = autoscroll {
10886 self.request_autoscroll(autoscroll, cx);
10887 }
10888 cx.notify();
10889 }
10890
10891 pub fn replace_blocks(
10892 &mut self,
10893 renderers: HashMap<CustomBlockId, RenderBlock>,
10894 autoscroll: Option<Autoscroll>,
10895 cx: &mut ViewContext<Self>,
10896 ) {
10897 self.display_map
10898 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10899 if let Some(autoscroll) = autoscroll {
10900 self.request_autoscroll(autoscroll, cx);
10901 }
10902 cx.notify();
10903 }
10904
10905 pub fn remove_blocks(
10906 &mut self,
10907 block_ids: HashSet<CustomBlockId>,
10908 autoscroll: Option<Autoscroll>,
10909 cx: &mut ViewContext<Self>,
10910 ) {
10911 self.display_map.update(cx, |display_map, cx| {
10912 display_map.remove_blocks(block_ids, cx)
10913 });
10914 if let Some(autoscroll) = autoscroll {
10915 self.request_autoscroll(autoscroll, cx);
10916 }
10917 cx.notify();
10918 }
10919
10920 pub fn row_for_block(
10921 &self,
10922 block_id: CustomBlockId,
10923 cx: &mut ViewContext<Self>,
10924 ) -> Option<DisplayRow> {
10925 self.display_map
10926 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10927 }
10928
10929 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10930 self.focused_block = Some(focused_block);
10931 }
10932
10933 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10934 self.focused_block.take()
10935 }
10936
10937 pub fn insert_creases(
10938 &mut self,
10939 creases: impl IntoIterator<Item = Crease<Anchor>>,
10940 cx: &mut ViewContext<Self>,
10941 ) -> Vec<CreaseId> {
10942 self.display_map
10943 .update(cx, |map, cx| map.insert_creases(creases, cx))
10944 }
10945
10946 pub fn remove_creases(
10947 &mut self,
10948 ids: impl IntoIterator<Item = CreaseId>,
10949 cx: &mut ViewContext<Self>,
10950 ) {
10951 self.display_map
10952 .update(cx, |map, cx| map.remove_creases(ids, cx));
10953 }
10954
10955 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10956 self.display_map
10957 .update(cx, |map, cx| map.snapshot(cx))
10958 .longest_row()
10959 }
10960
10961 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10962 self.display_map
10963 .update(cx, |map, cx| map.snapshot(cx))
10964 .max_point()
10965 }
10966
10967 pub fn text(&self, cx: &AppContext) -> String {
10968 self.buffer.read(cx).read(cx).text()
10969 }
10970
10971 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10972 let text = self.text(cx);
10973 let text = text.trim();
10974
10975 if text.is_empty() {
10976 return None;
10977 }
10978
10979 Some(text.to_string())
10980 }
10981
10982 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10983 self.transact(cx, |this, cx| {
10984 this.buffer
10985 .read(cx)
10986 .as_singleton()
10987 .expect("you can only call set_text on editors for singleton buffers")
10988 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10989 });
10990 }
10991
10992 pub fn display_text(&self, cx: &mut AppContext) -> String {
10993 self.display_map
10994 .update(cx, |map, cx| map.snapshot(cx))
10995 .text()
10996 }
10997
10998 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10999 let mut wrap_guides = smallvec::smallvec![];
11000
11001 if self.show_wrap_guides == Some(false) {
11002 return wrap_guides;
11003 }
11004
11005 let settings = self.buffer.read(cx).settings_at(0, cx);
11006 if settings.show_wrap_guides {
11007 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11008 wrap_guides.push((soft_wrap as usize, true));
11009 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11010 wrap_guides.push((soft_wrap as usize, true));
11011 }
11012 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11013 }
11014
11015 wrap_guides
11016 }
11017
11018 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11019 let settings = self.buffer.read(cx).settings_at(0, cx);
11020 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11021 match mode {
11022 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11023 SoftWrap::None
11024 }
11025 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11026 language_settings::SoftWrap::PreferredLineLength => {
11027 SoftWrap::Column(settings.preferred_line_length)
11028 }
11029 language_settings::SoftWrap::Bounded => {
11030 SoftWrap::Bounded(settings.preferred_line_length)
11031 }
11032 }
11033 }
11034
11035 pub fn set_soft_wrap_mode(
11036 &mut self,
11037 mode: language_settings::SoftWrap,
11038 cx: &mut ViewContext<Self>,
11039 ) {
11040 self.soft_wrap_mode_override = Some(mode);
11041 cx.notify();
11042 }
11043
11044 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11045 self.text_style_refinement = Some(style);
11046 }
11047
11048 /// called by the Element so we know what style we were most recently rendered with.
11049 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11050 let rem_size = cx.rem_size();
11051 self.display_map.update(cx, |map, cx| {
11052 map.set_font(
11053 style.text.font(),
11054 style.text.font_size.to_pixels(rem_size),
11055 cx,
11056 )
11057 });
11058 self.style = Some(style);
11059 }
11060
11061 pub fn style(&self) -> Option<&EditorStyle> {
11062 self.style.as_ref()
11063 }
11064
11065 // Called by the element. This method is not designed to be called outside of the editor
11066 // element's layout code because it does not notify when rewrapping is computed synchronously.
11067 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11068 self.display_map
11069 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11070 }
11071
11072 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11073 if self.soft_wrap_mode_override.is_some() {
11074 self.soft_wrap_mode_override.take();
11075 } else {
11076 let soft_wrap = match self.soft_wrap_mode(cx) {
11077 SoftWrap::GitDiff => return,
11078 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11079 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11080 language_settings::SoftWrap::None
11081 }
11082 };
11083 self.soft_wrap_mode_override = Some(soft_wrap);
11084 }
11085 cx.notify();
11086 }
11087
11088 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11089 let Some(workspace) = self.workspace() else {
11090 return;
11091 };
11092 let fs = workspace.read(cx).app_state().fs.clone();
11093 let current_show = TabBarSettings::get_global(cx).show;
11094 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11095 setting.show = Some(!current_show);
11096 });
11097 }
11098
11099 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11100 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11101 self.buffer
11102 .read(cx)
11103 .settings_at(0, cx)
11104 .indent_guides
11105 .enabled
11106 });
11107 self.show_indent_guides = Some(!currently_enabled);
11108 cx.notify();
11109 }
11110
11111 fn should_show_indent_guides(&self) -> Option<bool> {
11112 self.show_indent_guides
11113 }
11114
11115 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11116 let mut editor_settings = EditorSettings::get_global(cx).clone();
11117 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11118 EditorSettings::override_global(editor_settings, cx);
11119 }
11120
11121 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11122 self.use_relative_line_numbers
11123 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11124 }
11125
11126 pub fn toggle_relative_line_numbers(
11127 &mut self,
11128 _: &ToggleRelativeLineNumbers,
11129 cx: &mut ViewContext<Self>,
11130 ) {
11131 let is_relative = self.should_use_relative_line_numbers(cx);
11132 self.set_relative_line_number(Some(!is_relative), cx)
11133 }
11134
11135 pub fn set_relative_line_number(
11136 &mut self,
11137 is_relative: Option<bool>,
11138 cx: &mut ViewContext<Self>,
11139 ) {
11140 self.use_relative_line_numbers = is_relative;
11141 cx.notify();
11142 }
11143
11144 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11145 self.show_gutter = show_gutter;
11146 cx.notify();
11147 }
11148
11149 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11150 self.show_line_numbers = Some(show_line_numbers);
11151 cx.notify();
11152 }
11153
11154 pub fn set_show_git_diff_gutter(
11155 &mut self,
11156 show_git_diff_gutter: bool,
11157 cx: &mut ViewContext<Self>,
11158 ) {
11159 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11160 cx.notify();
11161 }
11162
11163 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11164 self.show_code_actions = Some(show_code_actions);
11165 cx.notify();
11166 }
11167
11168 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11169 self.show_runnables = Some(show_runnables);
11170 cx.notify();
11171 }
11172
11173 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11174 if self.display_map.read(cx).masked != masked {
11175 self.display_map.update(cx, |map, _| map.masked = masked);
11176 }
11177 cx.notify()
11178 }
11179
11180 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11181 self.show_wrap_guides = Some(show_wrap_guides);
11182 cx.notify();
11183 }
11184
11185 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11186 self.show_indent_guides = Some(show_indent_guides);
11187 cx.notify();
11188 }
11189
11190 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11191 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11192 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11193 if let Some(dir) = file.abs_path(cx).parent() {
11194 return Some(dir.to_owned());
11195 }
11196 }
11197
11198 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11199 return Some(project_path.path.to_path_buf());
11200 }
11201 }
11202
11203 None
11204 }
11205
11206 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11207 self.active_excerpt(cx)?
11208 .1
11209 .read(cx)
11210 .file()
11211 .and_then(|f| f.as_local())
11212 }
11213
11214 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11215 if let Some(target) = self.target_file(cx) {
11216 cx.reveal_path(&target.abs_path(cx));
11217 }
11218 }
11219
11220 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11221 if let Some(file) = self.target_file(cx) {
11222 if let Some(path) = file.abs_path(cx).to_str() {
11223 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11224 }
11225 }
11226 }
11227
11228 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11229 if let Some(file) = self.target_file(cx) {
11230 if let Some(path) = file.path().to_str() {
11231 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11232 }
11233 }
11234 }
11235
11236 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11237 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11238
11239 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11240 self.start_git_blame(true, cx);
11241 }
11242
11243 cx.notify();
11244 }
11245
11246 pub fn toggle_git_blame_inline(
11247 &mut self,
11248 _: &ToggleGitBlameInline,
11249 cx: &mut ViewContext<Self>,
11250 ) {
11251 self.toggle_git_blame_inline_internal(true, cx);
11252 cx.notify();
11253 }
11254
11255 pub fn git_blame_inline_enabled(&self) -> bool {
11256 self.git_blame_inline_enabled
11257 }
11258
11259 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11260 self.show_selection_menu = self
11261 .show_selection_menu
11262 .map(|show_selections_menu| !show_selections_menu)
11263 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11264
11265 cx.notify();
11266 }
11267
11268 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11269 self.show_selection_menu
11270 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11271 }
11272
11273 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11274 if let Some(project) = self.project.as_ref() {
11275 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11276 return;
11277 };
11278
11279 if buffer.read(cx).file().is_none() {
11280 return;
11281 }
11282
11283 let focused = self.focus_handle(cx).contains_focused(cx);
11284
11285 let project = project.clone();
11286 let blame =
11287 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11288 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11289 self.blame = Some(blame);
11290 }
11291 }
11292
11293 fn toggle_git_blame_inline_internal(
11294 &mut self,
11295 user_triggered: bool,
11296 cx: &mut ViewContext<Self>,
11297 ) {
11298 if self.git_blame_inline_enabled {
11299 self.git_blame_inline_enabled = false;
11300 self.show_git_blame_inline = false;
11301 self.show_git_blame_inline_delay_task.take();
11302 } else {
11303 self.git_blame_inline_enabled = true;
11304 self.start_git_blame_inline(user_triggered, cx);
11305 }
11306
11307 cx.notify();
11308 }
11309
11310 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11311 self.start_git_blame(user_triggered, cx);
11312
11313 if ProjectSettings::get_global(cx)
11314 .git
11315 .inline_blame_delay()
11316 .is_some()
11317 {
11318 self.start_inline_blame_timer(cx);
11319 } else {
11320 self.show_git_blame_inline = true
11321 }
11322 }
11323
11324 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11325 self.blame.as_ref()
11326 }
11327
11328 pub fn show_git_blame_gutter(&self) -> bool {
11329 self.show_git_blame_gutter
11330 }
11331
11332 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11333 self.show_git_blame_gutter && self.has_blame_entries(cx)
11334 }
11335
11336 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11337 self.show_git_blame_inline
11338 && self.focus_handle.is_focused(cx)
11339 && !self.newest_selection_head_on_empty_line(cx)
11340 && self.has_blame_entries(cx)
11341 }
11342
11343 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11344 self.blame()
11345 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11346 }
11347
11348 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11349 let cursor_anchor = self.selections.newest_anchor().head();
11350
11351 let snapshot = self.buffer.read(cx).snapshot(cx);
11352 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11353
11354 snapshot.line_len(buffer_row) == 0
11355 }
11356
11357 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11358 let buffer_and_selection = maybe!({
11359 let selection = self.selections.newest::<Point>(cx);
11360 let selection_range = selection.range();
11361
11362 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11363 (buffer, selection_range.start.row..selection_range.end.row)
11364 } else {
11365 let buffer_ranges = self
11366 .buffer()
11367 .read(cx)
11368 .range_to_buffer_ranges(selection_range, cx);
11369
11370 let (buffer, range, _) = if selection.reversed {
11371 buffer_ranges.first()
11372 } else {
11373 buffer_ranges.last()
11374 }?;
11375
11376 let snapshot = buffer.read(cx).snapshot();
11377 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11378 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11379 (buffer.clone(), selection)
11380 };
11381
11382 Some((buffer, selection))
11383 });
11384
11385 let Some((buffer, selection)) = buffer_and_selection else {
11386 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11387 };
11388
11389 let Some(project) = self.project.as_ref() else {
11390 return Task::ready(Err(anyhow!("editor does not have project")));
11391 };
11392
11393 project.update(cx, |project, cx| {
11394 project.get_permalink_to_line(&buffer, selection, cx)
11395 })
11396 }
11397
11398 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11399 let permalink_task = self.get_permalink_to_line(cx);
11400 let workspace = self.workspace();
11401
11402 cx.spawn(|_, mut cx| async move {
11403 match permalink_task.await {
11404 Ok(permalink) => {
11405 cx.update(|cx| {
11406 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11407 })
11408 .ok();
11409 }
11410 Err(err) => {
11411 let message = format!("Failed to copy permalink: {err}");
11412
11413 Err::<(), anyhow::Error>(err).log_err();
11414
11415 if let Some(workspace) = workspace {
11416 workspace
11417 .update(&mut cx, |workspace, cx| {
11418 struct CopyPermalinkToLine;
11419
11420 workspace.show_toast(
11421 Toast::new(
11422 NotificationId::unique::<CopyPermalinkToLine>(),
11423 message,
11424 ),
11425 cx,
11426 )
11427 })
11428 .ok();
11429 }
11430 }
11431 }
11432 })
11433 .detach();
11434 }
11435
11436 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11437 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11438 if let Some(file) = self.target_file(cx) {
11439 if let Some(path) = file.path().to_str() {
11440 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11441 }
11442 }
11443 }
11444
11445 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11446 let permalink_task = self.get_permalink_to_line(cx);
11447 let workspace = self.workspace();
11448
11449 cx.spawn(|_, mut cx| async move {
11450 match permalink_task.await {
11451 Ok(permalink) => {
11452 cx.update(|cx| {
11453 cx.open_url(permalink.as_ref());
11454 })
11455 .ok();
11456 }
11457 Err(err) => {
11458 let message = format!("Failed to open permalink: {err}");
11459
11460 Err::<(), anyhow::Error>(err).log_err();
11461
11462 if let Some(workspace) = workspace {
11463 workspace
11464 .update(&mut cx, |workspace, cx| {
11465 struct OpenPermalinkToLine;
11466
11467 workspace.show_toast(
11468 Toast::new(
11469 NotificationId::unique::<OpenPermalinkToLine>(),
11470 message,
11471 ),
11472 cx,
11473 )
11474 })
11475 .ok();
11476 }
11477 }
11478 }
11479 })
11480 .detach();
11481 }
11482
11483 pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11484 self.insert_uuid(UuidVersion::V4, cx);
11485 }
11486
11487 pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11488 self.insert_uuid(UuidVersion::V7, cx);
11489 }
11490
11491 fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11492 self.transact(cx, |this, cx| {
11493 let edits = this
11494 .selections
11495 .all::<Point>(cx)
11496 .into_iter()
11497 .map(|selection| {
11498 let uuid = match version {
11499 UuidVersion::V4 => uuid::Uuid::new_v4(),
11500 UuidVersion::V7 => uuid::Uuid::now_v7(),
11501 };
11502
11503 (selection.range(), uuid.to_string())
11504 });
11505 this.edit(edits, cx);
11506 this.refresh_inline_completion(true, false, cx);
11507 });
11508 }
11509
11510 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11511 /// last highlight added will be used.
11512 ///
11513 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11514 pub fn highlight_rows<T: 'static>(
11515 &mut self,
11516 range: Range<Anchor>,
11517 color: Hsla,
11518 should_autoscroll: bool,
11519 cx: &mut ViewContext<Self>,
11520 ) {
11521 let snapshot = self.buffer().read(cx).snapshot(cx);
11522 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11523 let ix = row_highlights.binary_search_by(|highlight| {
11524 Ordering::Equal
11525 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11526 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11527 });
11528
11529 if let Err(mut ix) = ix {
11530 let index = post_inc(&mut self.highlight_order);
11531
11532 // If this range intersects with the preceding highlight, then merge it with
11533 // the preceding highlight. Otherwise insert a new highlight.
11534 let mut merged = false;
11535 if ix > 0 {
11536 let prev_highlight = &mut row_highlights[ix - 1];
11537 if prev_highlight
11538 .range
11539 .end
11540 .cmp(&range.start, &snapshot)
11541 .is_ge()
11542 {
11543 ix -= 1;
11544 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11545 prev_highlight.range.end = range.end;
11546 }
11547 merged = true;
11548 prev_highlight.index = index;
11549 prev_highlight.color = color;
11550 prev_highlight.should_autoscroll = should_autoscroll;
11551 }
11552 }
11553
11554 if !merged {
11555 row_highlights.insert(
11556 ix,
11557 RowHighlight {
11558 range: range.clone(),
11559 index,
11560 color,
11561 should_autoscroll,
11562 },
11563 );
11564 }
11565
11566 // If any of the following highlights intersect with this one, merge them.
11567 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11568 let highlight = &row_highlights[ix];
11569 if next_highlight
11570 .range
11571 .start
11572 .cmp(&highlight.range.end, &snapshot)
11573 .is_le()
11574 {
11575 if next_highlight
11576 .range
11577 .end
11578 .cmp(&highlight.range.end, &snapshot)
11579 .is_gt()
11580 {
11581 row_highlights[ix].range.end = next_highlight.range.end;
11582 }
11583 row_highlights.remove(ix + 1);
11584 } else {
11585 break;
11586 }
11587 }
11588 }
11589 }
11590
11591 /// Remove any highlighted row ranges of the given type that intersect the
11592 /// given ranges.
11593 pub fn remove_highlighted_rows<T: 'static>(
11594 &mut self,
11595 ranges_to_remove: Vec<Range<Anchor>>,
11596 cx: &mut ViewContext<Self>,
11597 ) {
11598 let snapshot = self.buffer().read(cx).snapshot(cx);
11599 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11600 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11601 row_highlights.retain(|highlight| {
11602 while let Some(range_to_remove) = ranges_to_remove.peek() {
11603 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11604 Ordering::Less | Ordering::Equal => {
11605 ranges_to_remove.next();
11606 }
11607 Ordering::Greater => {
11608 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11609 Ordering::Less | Ordering::Equal => {
11610 return false;
11611 }
11612 Ordering::Greater => break,
11613 }
11614 }
11615 }
11616 }
11617
11618 true
11619 })
11620 }
11621
11622 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11623 pub fn clear_row_highlights<T: 'static>(&mut self) {
11624 self.highlighted_rows.remove(&TypeId::of::<T>());
11625 }
11626
11627 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11628 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11629 self.highlighted_rows
11630 .get(&TypeId::of::<T>())
11631 .map_or(&[] as &[_], |vec| vec.as_slice())
11632 .iter()
11633 .map(|highlight| (highlight.range.clone(), highlight.color))
11634 }
11635
11636 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11637 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11638 /// Allows to ignore certain kinds of highlights.
11639 pub fn highlighted_display_rows(
11640 &mut self,
11641 cx: &mut WindowContext,
11642 ) -> BTreeMap<DisplayRow, Hsla> {
11643 let snapshot = self.snapshot(cx);
11644 let mut used_highlight_orders = HashMap::default();
11645 self.highlighted_rows
11646 .iter()
11647 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11648 .fold(
11649 BTreeMap::<DisplayRow, Hsla>::new(),
11650 |mut unique_rows, highlight| {
11651 let start = highlight.range.start.to_display_point(&snapshot);
11652 let end = highlight.range.end.to_display_point(&snapshot);
11653 let start_row = start.row().0;
11654 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11655 && end.column() == 0
11656 {
11657 end.row().0.saturating_sub(1)
11658 } else {
11659 end.row().0
11660 };
11661 for row in start_row..=end_row {
11662 let used_index =
11663 used_highlight_orders.entry(row).or_insert(highlight.index);
11664 if highlight.index >= *used_index {
11665 *used_index = highlight.index;
11666 unique_rows.insert(DisplayRow(row), highlight.color);
11667 }
11668 }
11669 unique_rows
11670 },
11671 )
11672 }
11673
11674 pub fn highlighted_display_row_for_autoscroll(
11675 &self,
11676 snapshot: &DisplaySnapshot,
11677 ) -> Option<DisplayRow> {
11678 self.highlighted_rows
11679 .values()
11680 .flat_map(|highlighted_rows| highlighted_rows.iter())
11681 .filter_map(|highlight| {
11682 if highlight.should_autoscroll {
11683 Some(highlight.range.start.to_display_point(snapshot).row())
11684 } else {
11685 None
11686 }
11687 })
11688 .min()
11689 }
11690
11691 pub fn set_search_within_ranges(
11692 &mut self,
11693 ranges: &[Range<Anchor>],
11694 cx: &mut ViewContext<Self>,
11695 ) {
11696 self.highlight_background::<SearchWithinRange>(
11697 ranges,
11698 |colors| colors.editor_document_highlight_read_background,
11699 cx,
11700 )
11701 }
11702
11703 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11704 self.breadcrumb_header = Some(new_header);
11705 }
11706
11707 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11708 self.clear_background_highlights::<SearchWithinRange>(cx);
11709 }
11710
11711 pub fn highlight_background<T: 'static>(
11712 &mut self,
11713 ranges: &[Range<Anchor>],
11714 color_fetcher: fn(&ThemeColors) -> Hsla,
11715 cx: &mut ViewContext<Self>,
11716 ) {
11717 self.background_highlights
11718 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11719 self.scrollbar_marker_state.dirty = true;
11720 cx.notify();
11721 }
11722
11723 pub fn clear_background_highlights<T: 'static>(
11724 &mut self,
11725 cx: &mut ViewContext<Self>,
11726 ) -> Option<BackgroundHighlight> {
11727 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11728 if !text_highlights.1.is_empty() {
11729 self.scrollbar_marker_state.dirty = true;
11730 cx.notify();
11731 }
11732 Some(text_highlights)
11733 }
11734
11735 pub fn highlight_gutter<T: 'static>(
11736 &mut self,
11737 ranges: &[Range<Anchor>],
11738 color_fetcher: fn(&AppContext) -> Hsla,
11739 cx: &mut ViewContext<Self>,
11740 ) {
11741 self.gutter_highlights
11742 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11743 cx.notify();
11744 }
11745
11746 pub fn clear_gutter_highlights<T: 'static>(
11747 &mut self,
11748 cx: &mut ViewContext<Self>,
11749 ) -> Option<GutterHighlight> {
11750 cx.notify();
11751 self.gutter_highlights.remove(&TypeId::of::<T>())
11752 }
11753
11754 #[cfg(feature = "test-support")]
11755 pub fn all_text_background_highlights(
11756 &mut self,
11757 cx: &mut ViewContext<Self>,
11758 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11759 let snapshot = self.snapshot(cx);
11760 let buffer = &snapshot.buffer_snapshot;
11761 let start = buffer.anchor_before(0);
11762 let end = buffer.anchor_after(buffer.len());
11763 let theme = cx.theme().colors();
11764 self.background_highlights_in_range(start..end, &snapshot, theme)
11765 }
11766
11767 #[cfg(feature = "test-support")]
11768 pub fn search_background_highlights(
11769 &mut self,
11770 cx: &mut ViewContext<Self>,
11771 ) -> Vec<Range<Point>> {
11772 let snapshot = self.buffer().read(cx).snapshot(cx);
11773
11774 let highlights = self
11775 .background_highlights
11776 .get(&TypeId::of::<items::BufferSearchHighlights>());
11777
11778 if let Some((_color, ranges)) = highlights {
11779 ranges
11780 .iter()
11781 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11782 .collect_vec()
11783 } else {
11784 vec![]
11785 }
11786 }
11787
11788 fn document_highlights_for_position<'a>(
11789 &'a self,
11790 position: Anchor,
11791 buffer: &'a MultiBufferSnapshot,
11792 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11793 let read_highlights = self
11794 .background_highlights
11795 .get(&TypeId::of::<DocumentHighlightRead>())
11796 .map(|h| &h.1);
11797 let write_highlights = self
11798 .background_highlights
11799 .get(&TypeId::of::<DocumentHighlightWrite>())
11800 .map(|h| &h.1);
11801 let left_position = position.bias_left(buffer);
11802 let right_position = position.bias_right(buffer);
11803 read_highlights
11804 .into_iter()
11805 .chain(write_highlights)
11806 .flat_map(move |ranges| {
11807 let start_ix = match ranges.binary_search_by(|probe| {
11808 let cmp = probe.end.cmp(&left_position, buffer);
11809 if cmp.is_ge() {
11810 Ordering::Greater
11811 } else {
11812 Ordering::Less
11813 }
11814 }) {
11815 Ok(i) | Err(i) => i,
11816 };
11817
11818 ranges[start_ix..]
11819 .iter()
11820 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11821 })
11822 }
11823
11824 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11825 self.background_highlights
11826 .get(&TypeId::of::<T>())
11827 .map_or(false, |(_, highlights)| !highlights.is_empty())
11828 }
11829
11830 pub fn background_highlights_in_range(
11831 &self,
11832 search_range: Range<Anchor>,
11833 display_snapshot: &DisplaySnapshot,
11834 theme: &ThemeColors,
11835 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11836 let mut results = Vec::new();
11837 for (color_fetcher, ranges) in self.background_highlights.values() {
11838 let color = color_fetcher(theme);
11839 let start_ix = match ranges.binary_search_by(|probe| {
11840 let cmp = probe
11841 .end
11842 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11843 if cmp.is_gt() {
11844 Ordering::Greater
11845 } else {
11846 Ordering::Less
11847 }
11848 }) {
11849 Ok(i) | Err(i) => i,
11850 };
11851 for range in &ranges[start_ix..] {
11852 if range
11853 .start
11854 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11855 .is_ge()
11856 {
11857 break;
11858 }
11859
11860 let start = range.start.to_display_point(display_snapshot);
11861 let end = range.end.to_display_point(display_snapshot);
11862 results.push((start..end, color))
11863 }
11864 }
11865 results
11866 }
11867
11868 pub fn background_highlight_row_ranges<T: 'static>(
11869 &self,
11870 search_range: Range<Anchor>,
11871 display_snapshot: &DisplaySnapshot,
11872 count: usize,
11873 ) -> Vec<RangeInclusive<DisplayPoint>> {
11874 let mut results = Vec::new();
11875 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11876 return vec![];
11877 };
11878
11879 let start_ix = match ranges.binary_search_by(|probe| {
11880 let cmp = probe
11881 .end
11882 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11883 if cmp.is_gt() {
11884 Ordering::Greater
11885 } else {
11886 Ordering::Less
11887 }
11888 }) {
11889 Ok(i) | Err(i) => i,
11890 };
11891 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11892 if let (Some(start_display), Some(end_display)) = (start, end) {
11893 results.push(
11894 start_display.to_display_point(display_snapshot)
11895 ..=end_display.to_display_point(display_snapshot),
11896 );
11897 }
11898 };
11899 let mut start_row: Option<Point> = None;
11900 let mut end_row: Option<Point> = None;
11901 if ranges.len() > count {
11902 return Vec::new();
11903 }
11904 for range in &ranges[start_ix..] {
11905 if range
11906 .start
11907 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11908 .is_ge()
11909 {
11910 break;
11911 }
11912 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11913 if let Some(current_row) = &end_row {
11914 if end.row == current_row.row {
11915 continue;
11916 }
11917 }
11918 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11919 if start_row.is_none() {
11920 assert_eq!(end_row, None);
11921 start_row = Some(start);
11922 end_row = Some(end);
11923 continue;
11924 }
11925 if let Some(current_end) = end_row.as_mut() {
11926 if start.row > current_end.row + 1 {
11927 push_region(start_row, end_row);
11928 start_row = Some(start);
11929 end_row = Some(end);
11930 } else {
11931 // Merge two hunks.
11932 *current_end = end;
11933 }
11934 } else {
11935 unreachable!();
11936 }
11937 }
11938 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11939 push_region(start_row, end_row);
11940 results
11941 }
11942
11943 pub fn gutter_highlights_in_range(
11944 &self,
11945 search_range: Range<Anchor>,
11946 display_snapshot: &DisplaySnapshot,
11947 cx: &AppContext,
11948 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11949 let mut results = Vec::new();
11950 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11951 let color = color_fetcher(cx);
11952 let start_ix = match ranges.binary_search_by(|probe| {
11953 let cmp = probe
11954 .end
11955 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11956 if cmp.is_gt() {
11957 Ordering::Greater
11958 } else {
11959 Ordering::Less
11960 }
11961 }) {
11962 Ok(i) | Err(i) => i,
11963 };
11964 for range in &ranges[start_ix..] {
11965 if range
11966 .start
11967 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11968 .is_ge()
11969 {
11970 break;
11971 }
11972
11973 let start = range.start.to_display_point(display_snapshot);
11974 let end = range.end.to_display_point(display_snapshot);
11975 results.push((start..end, color))
11976 }
11977 }
11978 results
11979 }
11980
11981 /// Get the text ranges corresponding to the redaction query
11982 pub fn redacted_ranges(
11983 &self,
11984 search_range: Range<Anchor>,
11985 display_snapshot: &DisplaySnapshot,
11986 cx: &WindowContext,
11987 ) -> Vec<Range<DisplayPoint>> {
11988 display_snapshot
11989 .buffer_snapshot
11990 .redacted_ranges(search_range, |file| {
11991 if let Some(file) = file {
11992 file.is_private()
11993 && EditorSettings::get(
11994 Some(SettingsLocation {
11995 worktree_id: file.worktree_id(cx),
11996 path: file.path().as_ref(),
11997 }),
11998 cx,
11999 )
12000 .redact_private_values
12001 } else {
12002 false
12003 }
12004 })
12005 .map(|range| {
12006 range.start.to_display_point(display_snapshot)
12007 ..range.end.to_display_point(display_snapshot)
12008 })
12009 .collect()
12010 }
12011
12012 pub fn highlight_text<T: 'static>(
12013 &mut self,
12014 ranges: Vec<Range<Anchor>>,
12015 style: HighlightStyle,
12016 cx: &mut ViewContext<Self>,
12017 ) {
12018 self.display_map.update(cx, |map, _| {
12019 map.highlight_text(TypeId::of::<T>(), ranges, style)
12020 });
12021 cx.notify();
12022 }
12023
12024 pub(crate) fn highlight_inlays<T: 'static>(
12025 &mut self,
12026 highlights: Vec<InlayHighlight>,
12027 style: HighlightStyle,
12028 cx: &mut ViewContext<Self>,
12029 ) {
12030 self.display_map.update(cx, |map, _| {
12031 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12032 });
12033 cx.notify();
12034 }
12035
12036 pub fn text_highlights<'a, T: 'static>(
12037 &'a self,
12038 cx: &'a AppContext,
12039 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12040 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12041 }
12042
12043 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12044 let cleared = self
12045 .display_map
12046 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12047 if cleared {
12048 cx.notify();
12049 }
12050 }
12051
12052 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12053 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12054 && self.focus_handle.is_focused(cx)
12055 }
12056
12057 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12058 self.show_cursor_when_unfocused = is_enabled;
12059 cx.notify();
12060 }
12061
12062 pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12063 self.project
12064 .as_ref()
12065 .map(|project| project.read(cx).lsp_store())
12066 }
12067
12068 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12069 cx.notify();
12070 }
12071
12072 fn on_buffer_event(
12073 &mut self,
12074 multibuffer: Model<MultiBuffer>,
12075 event: &multi_buffer::Event,
12076 cx: &mut ViewContext<Self>,
12077 ) {
12078 match event {
12079 multi_buffer::Event::Edited {
12080 singleton_buffer_edited,
12081 edited_buffer: buffer_edited,
12082 } => {
12083 self.scrollbar_marker_state.dirty = true;
12084 self.active_indent_guides_state.dirty = true;
12085 self.refresh_active_diagnostics(cx);
12086 self.refresh_code_actions(cx);
12087 if self.has_active_inline_completion() {
12088 self.update_visible_inline_completion(cx);
12089 }
12090 if let Some(buffer) = buffer_edited {
12091 let buffer_id = buffer.read(cx).remote_id();
12092 if !self.registered_buffers.contains_key(&buffer_id) {
12093 if let Some(lsp_store) = self.lsp_store(cx) {
12094 lsp_store.update(cx, |lsp_store, cx| {
12095 self.registered_buffers.insert(
12096 buffer_id,
12097 lsp_store.register_buffer_with_language_servers(&buffer, cx),
12098 );
12099 })
12100 }
12101 }
12102 }
12103 cx.emit(EditorEvent::BufferEdited);
12104 cx.emit(SearchEvent::MatchesInvalidated);
12105 if *singleton_buffer_edited {
12106 if let Some(project) = &self.project {
12107 let project = project.read(cx);
12108 #[allow(clippy::mutable_key_type)]
12109 let languages_affected = multibuffer
12110 .read(cx)
12111 .all_buffers()
12112 .into_iter()
12113 .filter_map(|buffer| {
12114 let buffer = buffer.read(cx);
12115 let language = buffer.language()?;
12116 if project.is_local()
12117 && project
12118 .language_servers_for_local_buffer(buffer, cx)
12119 .count()
12120 == 0
12121 {
12122 None
12123 } else {
12124 Some(language)
12125 }
12126 })
12127 .cloned()
12128 .collect::<HashSet<_>>();
12129 if !languages_affected.is_empty() {
12130 self.refresh_inlay_hints(
12131 InlayHintRefreshReason::BufferEdited(languages_affected),
12132 cx,
12133 );
12134 }
12135 }
12136 }
12137
12138 let Some(project) = &self.project else { return };
12139 let (telemetry, is_via_ssh) = {
12140 let project = project.read(cx);
12141 let telemetry = project.client().telemetry().clone();
12142 let is_via_ssh = project.is_via_ssh();
12143 (telemetry, is_via_ssh)
12144 };
12145 refresh_linked_ranges(self, cx);
12146 telemetry.log_edit_event("editor", is_via_ssh);
12147 }
12148 multi_buffer::Event::ExcerptsAdded {
12149 buffer,
12150 predecessor,
12151 excerpts,
12152 } => {
12153 self.tasks_update_task = Some(self.refresh_runnables(cx));
12154 let buffer_id = buffer.read(cx).remote_id();
12155 if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12156 if let Some(project) = &self.project {
12157 get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12158 }
12159 }
12160 cx.emit(EditorEvent::ExcerptsAdded {
12161 buffer: buffer.clone(),
12162 predecessor: *predecessor,
12163 excerpts: excerpts.clone(),
12164 });
12165 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12166 }
12167 multi_buffer::Event::ExcerptsRemoved { ids } => {
12168 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12169 let buffer = self.buffer.read(cx);
12170 self.registered_buffers
12171 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12172 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12173 }
12174 multi_buffer::Event::ExcerptsEdited { ids } => {
12175 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12176 }
12177 multi_buffer::Event::ExcerptsExpanded { ids } => {
12178 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12179 }
12180 multi_buffer::Event::Reparsed(buffer_id) => {
12181 self.tasks_update_task = Some(self.refresh_runnables(cx));
12182
12183 cx.emit(EditorEvent::Reparsed(*buffer_id));
12184 }
12185 multi_buffer::Event::LanguageChanged(buffer_id) => {
12186 linked_editing_ranges::refresh_linked_ranges(self, cx);
12187 cx.emit(EditorEvent::Reparsed(*buffer_id));
12188 cx.notify();
12189 }
12190 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12191 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12192 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12193 cx.emit(EditorEvent::TitleChanged)
12194 }
12195 // multi_buffer::Event::DiffBaseChanged => {
12196 // self.scrollbar_marker_state.dirty = true;
12197 // cx.emit(EditorEvent::DiffBaseChanged);
12198 // cx.notify();
12199 // }
12200 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12201 multi_buffer::Event::DiagnosticsUpdated => {
12202 self.refresh_active_diagnostics(cx);
12203 self.scrollbar_marker_state.dirty = true;
12204 cx.notify();
12205 }
12206 _ => {}
12207 };
12208 }
12209
12210 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12211 cx.notify();
12212 }
12213
12214 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12215 self.tasks_update_task = Some(self.refresh_runnables(cx));
12216 self.refresh_inline_completion(true, false, cx);
12217 self.refresh_inlay_hints(
12218 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12219 self.selections.newest_anchor().head(),
12220 &self.buffer.read(cx).snapshot(cx),
12221 cx,
12222 )),
12223 cx,
12224 );
12225
12226 let old_cursor_shape = self.cursor_shape;
12227
12228 {
12229 let editor_settings = EditorSettings::get_global(cx);
12230 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12231 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12232 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12233 }
12234
12235 if old_cursor_shape != self.cursor_shape {
12236 cx.emit(EditorEvent::CursorShapeChanged);
12237 }
12238
12239 let project_settings = ProjectSettings::get_global(cx);
12240 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12241
12242 if self.mode == EditorMode::Full {
12243 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12244 if self.git_blame_inline_enabled != inline_blame_enabled {
12245 self.toggle_git_blame_inline_internal(false, cx);
12246 }
12247 }
12248
12249 cx.notify();
12250 }
12251
12252 pub fn set_searchable(&mut self, searchable: bool) {
12253 self.searchable = searchable;
12254 }
12255
12256 pub fn searchable(&self) -> bool {
12257 self.searchable
12258 }
12259
12260 fn open_proposed_changes_editor(
12261 &mut self,
12262 _: &OpenProposedChangesEditor,
12263 cx: &mut ViewContext<Self>,
12264 ) {
12265 let Some(workspace) = self.workspace() else {
12266 cx.propagate();
12267 return;
12268 };
12269
12270 let selections = self.selections.all::<usize>(cx);
12271 let buffer = self.buffer.read(cx);
12272 let mut new_selections_by_buffer = HashMap::default();
12273 for selection in selections {
12274 for (buffer, range, _) in
12275 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12276 {
12277 let mut range = range.to_point(buffer.read(cx));
12278 range.start.column = 0;
12279 range.end.column = buffer.read(cx).line_len(range.end.row);
12280 new_selections_by_buffer
12281 .entry(buffer)
12282 .or_insert(Vec::new())
12283 .push(range)
12284 }
12285 }
12286
12287 let proposed_changes_buffers = new_selections_by_buffer
12288 .into_iter()
12289 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12290 .collect::<Vec<_>>();
12291 let proposed_changes_editor = cx.new_view(|cx| {
12292 ProposedChangesEditor::new(
12293 "Proposed changes",
12294 proposed_changes_buffers,
12295 self.project.clone(),
12296 cx,
12297 )
12298 });
12299
12300 cx.window_context().defer(move |cx| {
12301 workspace.update(cx, |workspace, cx| {
12302 workspace.active_pane().update(cx, |pane, cx| {
12303 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12304 });
12305 });
12306 });
12307 }
12308
12309 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12310 self.open_excerpts_common(None, true, cx)
12311 }
12312
12313 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12314 self.open_excerpts_common(None, false, cx)
12315 }
12316
12317 fn open_excerpts_common(
12318 &mut self,
12319 jump_data: Option<JumpData>,
12320 split: bool,
12321 cx: &mut ViewContext<Self>,
12322 ) {
12323 let Some(workspace) = self.workspace() else {
12324 cx.propagate();
12325 return;
12326 };
12327
12328 if self.buffer.read(cx).is_singleton() {
12329 cx.propagate();
12330 return;
12331 }
12332
12333 let mut new_selections_by_buffer = HashMap::default();
12334 match &jump_data {
12335 Some(jump_data) => {
12336 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12337 if let Some(buffer) = multi_buffer_snapshot
12338 .buffer_id_for_excerpt(jump_data.excerpt_id)
12339 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12340 {
12341 let buffer_snapshot = buffer.read(cx).snapshot();
12342 let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12343 language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12344 } else {
12345 buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12346 };
12347 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12348 new_selections_by_buffer.insert(
12349 buffer,
12350 (
12351 vec![jump_to_offset..jump_to_offset],
12352 Some(jump_data.line_offset_from_top),
12353 ),
12354 );
12355 }
12356 }
12357 None => {
12358 let selections = self.selections.all::<usize>(cx);
12359 let buffer = self.buffer.read(cx);
12360 for selection in selections {
12361 for (mut buffer_handle, mut range, _) in
12362 buffer.range_to_buffer_ranges(selection.range(), cx)
12363 {
12364 // When editing branch buffers, jump to the corresponding location
12365 // in their base buffer.
12366 let buffer = buffer_handle.read(cx);
12367 if let Some(base_buffer) = buffer.base_buffer() {
12368 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12369 buffer_handle = base_buffer;
12370 }
12371
12372 if selection.reversed {
12373 mem::swap(&mut range.start, &mut range.end);
12374 }
12375 new_selections_by_buffer
12376 .entry(buffer_handle)
12377 .or_insert((Vec::new(), None))
12378 .0
12379 .push(range)
12380 }
12381 }
12382 }
12383 }
12384
12385 if new_selections_by_buffer.is_empty() {
12386 return;
12387 }
12388
12389 // We defer the pane interaction because we ourselves are a workspace item
12390 // and activating a new item causes the pane to call a method on us reentrantly,
12391 // which panics if we're on the stack.
12392 cx.window_context().defer(move |cx| {
12393 workspace.update(cx, |workspace, cx| {
12394 let pane = if split {
12395 workspace.adjacent_pane(cx)
12396 } else {
12397 workspace.active_pane().clone()
12398 };
12399
12400 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12401 let editor = buffer
12402 .read(cx)
12403 .file()
12404 .is_none()
12405 .then(|| {
12406 // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
12407 // so `workspace.open_project_item` will never find them, always opening a new editor.
12408 // Instead, we try to activate the existing editor in the pane first.
12409 let (editor, pane_item_index) =
12410 pane.read(cx).items().enumerate().find_map(|(i, item)| {
12411 let editor = item.downcast::<Editor>()?;
12412 let singleton_buffer =
12413 editor.read(cx).buffer().read(cx).as_singleton()?;
12414 if singleton_buffer == buffer {
12415 Some((editor, i))
12416 } else {
12417 None
12418 }
12419 })?;
12420 pane.update(cx, |pane, cx| {
12421 pane.activate_item(pane_item_index, true, true, cx)
12422 });
12423 Some(editor)
12424 })
12425 .flatten()
12426 .unwrap_or_else(|| {
12427 workspace.open_project_item::<Self>(
12428 pane.clone(),
12429 buffer,
12430 true,
12431 true,
12432 cx,
12433 )
12434 });
12435
12436 editor.update(cx, |editor, cx| {
12437 let autoscroll = match scroll_offset {
12438 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12439 None => Autoscroll::newest(),
12440 };
12441 let nav_history = editor.nav_history.take();
12442 editor.change_selections(Some(autoscroll), cx, |s| {
12443 s.select_ranges(ranges);
12444 });
12445 editor.nav_history = nav_history;
12446 });
12447 }
12448 })
12449 });
12450 }
12451
12452 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12453 let snapshot = self.buffer.read(cx).read(cx);
12454 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12455 Some(
12456 ranges
12457 .iter()
12458 .map(move |range| {
12459 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12460 })
12461 .collect(),
12462 )
12463 }
12464
12465 fn selection_replacement_ranges(
12466 &self,
12467 range: Range<OffsetUtf16>,
12468 cx: &mut AppContext,
12469 ) -> Vec<Range<OffsetUtf16>> {
12470 let selections = self.selections.all::<OffsetUtf16>(cx);
12471 let newest_selection = selections
12472 .iter()
12473 .max_by_key(|selection| selection.id)
12474 .unwrap();
12475 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12476 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12477 let snapshot = self.buffer.read(cx).read(cx);
12478 selections
12479 .into_iter()
12480 .map(|mut selection| {
12481 selection.start.0 =
12482 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12483 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12484 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12485 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12486 })
12487 .collect()
12488 }
12489
12490 fn report_editor_event(
12491 &self,
12492 operation: &'static str,
12493 file_extension: Option<String>,
12494 cx: &AppContext,
12495 ) {
12496 if cfg!(any(test, feature = "test-support")) {
12497 return;
12498 }
12499
12500 let Some(project) = &self.project else { return };
12501
12502 // If None, we are in a file without an extension
12503 let file = self
12504 .buffer
12505 .read(cx)
12506 .as_singleton()
12507 .and_then(|b| b.read(cx).file());
12508 let file_extension = file_extension.or(file
12509 .as_ref()
12510 .and_then(|file| Path::new(file.file_name(cx)).extension())
12511 .and_then(|e| e.to_str())
12512 .map(|a| a.to_string()));
12513
12514 let vim_mode = cx
12515 .global::<SettingsStore>()
12516 .raw_user_settings()
12517 .get("vim_mode")
12518 == Some(&serde_json::Value::Bool(true));
12519
12520 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12521 == language::language_settings::InlineCompletionProvider::Copilot;
12522 let copilot_enabled_for_language = self
12523 .buffer
12524 .read(cx)
12525 .settings_at(0, cx)
12526 .show_inline_completions;
12527
12528 let project = project.read(cx);
12529 let telemetry = project.client().telemetry().clone();
12530 telemetry.report_editor_event(
12531 file_extension,
12532 vim_mode,
12533 operation,
12534 copilot_enabled,
12535 copilot_enabled_for_language,
12536 project.is_via_ssh(),
12537 )
12538 }
12539
12540 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12541 /// with each line being an array of {text, highlight} objects.
12542 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12543 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12544 return;
12545 };
12546
12547 #[derive(Serialize)]
12548 struct Chunk<'a> {
12549 text: String,
12550 highlight: Option<&'a str>,
12551 }
12552
12553 let snapshot = buffer.read(cx).snapshot();
12554 let range = self
12555 .selected_text_range(false, cx)
12556 .and_then(|selection| {
12557 if selection.range.is_empty() {
12558 None
12559 } else {
12560 Some(selection.range)
12561 }
12562 })
12563 .unwrap_or_else(|| 0..snapshot.len());
12564
12565 let chunks = snapshot.chunks(range, true);
12566 let mut lines = Vec::new();
12567 let mut line: VecDeque<Chunk> = VecDeque::new();
12568
12569 let Some(style) = self.style.as_ref() else {
12570 return;
12571 };
12572
12573 for chunk in chunks {
12574 let highlight = chunk
12575 .syntax_highlight_id
12576 .and_then(|id| id.name(&style.syntax));
12577 let mut chunk_lines = chunk.text.split('\n').peekable();
12578 while let Some(text) = chunk_lines.next() {
12579 let mut merged_with_last_token = false;
12580 if let Some(last_token) = line.back_mut() {
12581 if last_token.highlight == highlight {
12582 last_token.text.push_str(text);
12583 merged_with_last_token = true;
12584 }
12585 }
12586
12587 if !merged_with_last_token {
12588 line.push_back(Chunk {
12589 text: text.into(),
12590 highlight,
12591 });
12592 }
12593
12594 if chunk_lines.peek().is_some() {
12595 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12596 line.pop_front();
12597 }
12598 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12599 line.pop_back();
12600 }
12601
12602 lines.push(mem::take(&mut line));
12603 }
12604 }
12605 }
12606
12607 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12608 return;
12609 };
12610 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12611 }
12612
12613 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12614 self.request_autoscroll(Autoscroll::newest(), cx);
12615 let position = self.selections.newest_display(cx).start;
12616 mouse_context_menu::deploy_context_menu(self, None, position, cx);
12617 }
12618
12619 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12620 &self.inlay_hint_cache
12621 }
12622
12623 pub fn replay_insert_event(
12624 &mut self,
12625 text: &str,
12626 relative_utf16_range: Option<Range<isize>>,
12627 cx: &mut ViewContext<Self>,
12628 ) {
12629 if !self.input_enabled {
12630 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12631 return;
12632 }
12633 if let Some(relative_utf16_range) = relative_utf16_range {
12634 let selections = self.selections.all::<OffsetUtf16>(cx);
12635 self.change_selections(None, cx, |s| {
12636 let new_ranges = selections.into_iter().map(|range| {
12637 let start = OffsetUtf16(
12638 range
12639 .head()
12640 .0
12641 .saturating_add_signed(relative_utf16_range.start),
12642 );
12643 let end = OffsetUtf16(
12644 range
12645 .head()
12646 .0
12647 .saturating_add_signed(relative_utf16_range.end),
12648 );
12649 start..end
12650 });
12651 s.select_ranges(new_ranges);
12652 });
12653 }
12654
12655 self.handle_input(text, cx);
12656 }
12657
12658 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12659 let Some(provider) = self.semantics_provider.as_ref() else {
12660 return false;
12661 };
12662
12663 let mut supports = false;
12664 self.buffer().read(cx).for_each_buffer(|buffer| {
12665 supports |= provider.supports_inlay_hints(buffer, cx);
12666 });
12667 supports
12668 }
12669
12670 pub fn focus(&self, cx: &mut WindowContext) {
12671 cx.focus(&self.focus_handle)
12672 }
12673
12674 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12675 self.focus_handle.is_focused(cx)
12676 }
12677
12678 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12679 cx.emit(EditorEvent::Focused);
12680
12681 if let Some(descendant) = self
12682 .last_focused_descendant
12683 .take()
12684 .and_then(|descendant| descendant.upgrade())
12685 {
12686 cx.focus(&descendant);
12687 } else {
12688 if let Some(blame) = self.blame.as_ref() {
12689 blame.update(cx, GitBlame::focus)
12690 }
12691
12692 self.blink_manager.update(cx, BlinkManager::enable);
12693 self.show_cursor_names(cx);
12694 self.buffer.update(cx, |buffer, cx| {
12695 buffer.finalize_last_transaction(cx);
12696 if self.leader_peer_id.is_none() {
12697 buffer.set_active_selections(
12698 &self.selections.disjoint_anchors(),
12699 self.selections.line_mode,
12700 self.cursor_shape,
12701 cx,
12702 );
12703 }
12704 });
12705 }
12706 }
12707
12708 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12709 cx.emit(EditorEvent::FocusedIn)
12710 }
12711
12712 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12713 if event.blurred != self.focus_handle {
12714 self.last_focused_descendant = Some(event.blurred);
12715 }
12716 }
12717
12718 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12719 self.blink_manager.update(cx, BlinkManager::disable);
12720 self.buffer
12721 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12722
12723 if let Some(blame) = self.blame.as_ref() {
12724 blame.update(cx, GitBlame::blur)
12725 }
12726 if !self.hover_state.focused(cx) {
12727 hide_hover(self, cx);
12728 }
12729
12730 self.hide_context_menu(cx);
12731 cx.emit(EditorEvent::Blurred);
12732 cx.notify();
12733 }
12734
12735 pub fn register_action<A: Action>(
12736 &mut self,
12737 listener: impl Fn(&A, &mut WindowContext) + 'static,
12738 ) -> Subscription {
12739 let id = self.next_editor_action_id.post_inc();
12740 let listener = Arc::new(listener);
12741 self.editor_actions.borrow_mut().insert(
12742 id,
12743 Box::new(move |cx| {
12744 let cx = cx.window_context();
12745 let listener = listener.clone();
12746 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12747 let action = action.downcast_ref().unwrap();
12748 if phase == DispatchPhase::Bubble {
12749 listener(action, cx)
12750 }
12751 })
12752 }),
12753 );
12754
12755 let editor_actions = self.editor_actions.clone();
12756 Subscription::new(move || {
12757 editor_actions.borrow_mut().remove(&id);
12758 })
12759 }
12760
12761 pub fn file_header_size(&self) -> u32 {
12762 FILE_HEADER_HEIGHT
12763 }
12764
12765 pub fn revert(
12766 &mut self,
12767 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12768 cx: &mut ViewContext<Self>,
12769 ) {
12770 self.buffer().update(cx, |multi_buffer, cx| {
12771 for (buffer_id, changes) in revert_changes {
12772 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12773 buffer.update(cx, |buffer, cx| {
12774 buffer.edit(
12775 changes.into_iter().map(|(range, text)| {
12776 (range, text.to_string().map(Arc::<str>::from))
12777 }),
12778 None,
12779 cx,
12780 );
12781 });
12782 }
12783 }
12784 });
12785 self.change_selections(None, cx, |selections| selections.refresh());
12786 }
12787
12788 pub fn to_pixel_point(
12789 &mut self,
12790 source: multi_buffer::Anchor,
12791 editor_snapshot: &EditorSnapshot,
12792 cx: &mut ViewContext<Self>,
12793 ) -> Option<gpui::Point<Pixels>> {
12794 let source_point = source.to_display_point(editor_snapshot);
12795 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12796 }
12797
12798 pub fn display_to_pixel_point(
12799 &self,
12800 source: DisplayPoint,
12801 editor_snapshot: &EditorSnapshot,
12802 cx: &WindowContext,
12803 ) -> Option<gpui::Point<Pixels>> {
12804 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12805 let text_layout_details = self.text_layout_details(cx);
12806 let scroll_top = text_layout_details
12807 .scroll_anchor
12808 .scroll_position(editor_snapshot)
12809 .y;
12810
12811 if source.row().as_f32() < scroll_top.floor() {
12812 return None;
12813 }
12814 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12815 let source_y = line_height * (source.row().as_f32() - scroll_top);
12816 Some(gpui::Point::new(source_x, source_y))
12817 }
12818
12819 pub fn has_active_completions_menu(&self) -> bool {
12820 self.context_menu.borrow().as_ref().map_or(false, |menu| {
12821 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
12822 })
12823 }
12824
12825 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12826 self.addons
12827 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12828 }
12829
12830 pub fn unregister_addon<T: Addon>(&mut self) {
12831 self.addons.remove(&std::any::TypeId::of::<T>());
12832 }
12833
12834 pub fn addon<T: Addon>(&self) -> Option<&T> {
12835 let type_id = std::any::TypeId::of::<T>();
12836 self.addons
12837 .get(&type_id)
12838 .and_then(|item| item.to_any().downcast_ref::<T>())
12839 }
12840
12841 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
12842 let text_layout_details = self.text_layout_details(cx);
12843 let style = &text_layout_details.editor_style;
12844 let font_id = cx.text_system().resolve_font(&style.text.font());
12845 let font_size = style.text.font_size.to_pixels(cx.rem_size());
12846 let line_height = style.text.line_height_in_pixels(cx.rem_size());
12847
12848 let em_width = cx
12849 .text_system()
12850 .typographic_bounds(font_id, font_size, 'm')
12851 .unwrap()
12852 .size
12853 .width;
12854
12855 gpui::Point::new(em_width, line_height)
12856 }
12857}
12858
12859fn get_unstaged_changes_for_buffers(
12860 project: &Model<Project>,
12861 buffers: impl IntoIterator<Item = Model<Buffer>>,
12862 cx: &mut ViewContext<Editor>,
12863) {
12864 let mut tasks = Vec::new();
12865 project.update(cx, |project, cx| {
12866 for buffer in buffers {
12867 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
12868 }
12869 });
12870 cx.spawn(|this, mut cx| async move {
12871 let change_sets = futures::future::join_all(tasks).await;
12872 this.update(&mut cx, |this, cx| {
12873 for change_set in change_sets {
12874 if let Some(change_set) = change_set.log_err() {
12875 this.diff_map.add_change_set(change_set, cx);
12876 }
12877 }
12878 })
12879 .ok();
12880 })
12881 .detach();
12882}
12883
12884fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
12885 let tab_size = tab_size.get() as usize;
12886 let mut width = offset;
12887
12888 for ch in text.chars() {
12889 width += if ch == '\t' {
12890 tab_size - (width % tab_size)
12891 } else {
12892 1
12893 };
12894 }
12895
12896 width - offset
12897}
12898
12899#[cfg(test)]
12900mod tests {
12901 use super::*;
12902
12903 #[test]
12904 fn test_string_size_with_expanded_tabs() {
12905 let nz = |val| NonZeroU32::new(val).unwrap();
12906 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
12907 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
12908 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
12909 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
12910 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
12911 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
12912 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
12913 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
12914 }
12915}
12916
12917/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
12918struct WordBreakingTokenizer<'a> {
12919 input: &'a str,
12920}
12921
12922impl<'a> WordBreakingTokenizer<'a> {
12923 fn new(input: &'a str) -> Self {
12924 Self { input }
12925 }
12926}
12927
12928fn is_char_ideographic(ch: char) -> bool {
12929 use unicode_script::Script::*;
12930 use unicode_script::UnicodeScript;
12931 matches!(ch.script(), Han | Tangut | Yi)
12932}
12933
12934fn is_grapheme_ideographic(text: &str) -> bool {
12935 text.chars().any(is_char_ideographic)
12936}
12937
12938fn is_grapheme_whitespace(text: &str) -> bool {
12939 text.chars().any(|x| x.is_whitespace())
12940}
12941
12942fn should_stay_with_preceding_ideograph(text: &str) -> bool {
12943 text.chars().next().map_or(false, |ch| {
12944 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
12945 })
12946}
12947
12948#[derive(PartialEq, Eq, Debug, Clone, Copy)]
12949struct WordBreakToken<'a> {
12950 token: &'a str,
12951 grapheme_len: usize,
12952 is_whitespace: bool,
12953}
12954
12955impl<'a> Iterator for WordBreakingTokenizer<'a> {
12956 /// Yields a span, the count of graphemes in the token, and whether it was
12957 /// whitespace. Note that it also breaks at word boundaries.
12958 type Item = WordBreakToken<'a>;
12959
12960 fn next(&mut self) -> Option<Self::Item> {
12961 use unicode_segmentation::UnicodeSegmentation;
12962 if self.input.is_empty() {
12963 return None;
12964 }
12965
12966 let mut iter = self.input.graphemes(true).peekable();
12967 let mut offset = 0;
12968 let mut graphemes = 0;
12969 if let Some(first_grapheme) = iter.next() {
12970 let is_whitespace = is_grapheme_whitespace(first_grapheme);
12971 offset += first_grapheme.len();
12972 graphemes += 1;
12973 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
12974 if let Some(grapheme) = iter.peek().copied() {
12975 if should_stay_with_preceding_ideograph(grapheme) {
12976 offset += grapheme.len();
12977 graphemes += 1;
12978 }
12979 }
12980 } else {
12981 let mut words = self.input[offset..].split_word_bound_indices().peekable();
12982 let mut next_word_bound = words.peek().copied();
12983 if next_word_bound.map_or(false, |(i, _)| i == 0) {
12984 next_word_bound = words.next();
12985 }
12986 while let Some(grapheme) = iter.peek().copied() {
12987 if next_word_bound.map_or(false, |(i, _)| i == offset) {
12988 break;
12989 };
12990 if is_grapheme_whitespace(grapheme) != is_whitespace {
12991 break;
12992 };
12993 offset += grapheme.len();
12994 graphemes += 1;
12995 iter.next();
12996 }
12997 }
12998 let token = &self.input[..offset];
12999 self.input = &self.input[offset..];
13000 if is_whitespace {
13001 Some(WordBreakToken {
13002 token: " ",
13003 grapheme_len: 1,
13004 is_whitespace: true,
13005 })
13006 } else {
13007 Some(WordBreakToken {
13008 token,
13009 grapheme_len: graphemes,
13010 is_whitespace: false,
13011 })
13012 }
13013 } else {
13014 None
13015 }
13016 }
13017}
13018
13019#[test]
13020fn test_word_breaking_tokenizer() {
13021 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13022 ("", &[]),
13023 (" ", &[(" ", 1, true)]),
13024 ("Ʒ", &[("Ʒ", 1, false)]),
13025 ("Ǽ", &[("Ǽ", 1, false)]),
13026 ("⋑", &[("⋑", 1, false)]),
13027 ("⋑⋑", &[("⋑⋑", 2, false)]),
13028 (
13029 "原理,进而",
13030 &[
13031 ("原", 1, false),
13032 ("理,", 2, false),
13033 ("进", 1, false),
13034 ("而", 1, false),
13035 ],
13036 ),
13037 (
13038 "hello world",
13039 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13040 ),
13041 (
13042 "hello, world",
13043 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13044 ),
13045 (
13046 " hello world",
13047 &[
13048 (" ", 1, true),
13049 ("hello", 5, false),
13050 (" ", 1, true),
13051 ("world", 5, false),
13052 ],
13053 ),
13054 (
13055 "这是什么 \n 钢笔",
13056 &[
13057 ("这", 1, false),
13058 ("是", 1, false),
13059 ("什", 1, false),
13060 ("么", 1, false),
13061 (" ", 1, true),
13062 ("钢", 1, false),
13063 ("笔", 1, false),
13064 ],
13065 ),
13066 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13067 ];
13068
13069 for (input, result) in tests {
13070 assert_eq!(
13071 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13072 result
13073 .iter()
13074 .copied()
13075 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13076 token,
13077 grapheme_len,
13078 is_whitespace,
13079 })
13080 .collect::<Vec<_>>()
13081 );
13082 }
13083}
13084
13085fn wrap_with_prefix(
13086 line_prefix: String,
13087 unwrapped_text: String,
13088 wrap_column: usize,
13089 tab_size: NonZeroU32,
13090) -> String {
13091 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13092 let mut wrapped_text = String::new();
13093 let mut current_line = line_prefix.clone();
13094
13095 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13096 let mut current_line_len = line_prefix_len;
13097 for WordBreakToken {
13098 token,
13099 grapheme_len,
13100 is_whitespace,
13101 } in tokenizer
13102 {
13103 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13104 wrapped_text.push_str(current_line.trim_end());
13105 wrapped_text.push('\n');
13106 current_line.truncate(line_prefix.len());
13107 current_line_len = line_prefix_len;
13108 if !is_whitespace {
13109 current_line.push_str(token);
13110 current_line_len += grapheme_len;
13111 }
13112 } else if !is_whitespace {
13113 current_line.push_str(token);
13114 current_line_len += grapheme_len;
13115 } else if current_line_len != line_prefix_len {
13116 current_line.push(' ');
13117 current_line_len += 1;
13118 }
13119 }
13120
13121 if !current_line.is_empty() {
13122 wrapped_text.push_str(¤t_line);
13123 }
13124 wrapped_text
13125}
13126
13127#[test]
13128fn test_wrap_with_prefix() {
13129 assert_eq!(
13130 wrap_with_prefix(
13131 "# ".to_string(),
13132 "abcdefg".to_string(),
13133 4,
13134 NonZeroU32::new(4).unwrap()
13135 ),
13136 "# abcdefg"
13137 );
13138 assert_eq!(
13139 wrap_with_prefix(
13140 "".to_string(),
13141 "\thello world".to_string(),
13142 8,
13143 NonZeroU32::new(4).unwrap()
13144 ),
13145 "hello\nworld"
13146 );
13147 assert_eq!(
13148 wrap_with_prefix(
13149 "// ".to_string(),
13150 "xx \nyy zz aa bb cc".to_string(),
13151 12,
13152 NonZeroU32::new(4).unwrap()
13153 ),
13154 "// xx yy zz\n// aa bb cc"
13155 );
13156 assert_eq!(
13157 wrap_with_prefix(
13158 String::new(),
13159 "这是什么 \n 钢笔".to_string(),
13160 3,
13161 NonZeroU32::new(4).unwrap()
13162 ),
13163 "这是什\n么 钢\n笔"
13164 );
13165}
13166
13167fn hunks_for_selections(
13168 snapshot: &EditorSnapshot,
13169 selections: &[Selection<Point>],
13170) -> Vec<MultiBufferDiffHunk> {
13171 hunks_for_ranges(
13172 selections.iter().map(|selection| selection.range()),
13173 snapshot,
13174 )
13175}
13176
13177pub fn hunks_for_ranges(
13178 ranges: impl Iterator<Item = Range<Point>>,
13179 snapshot: &EditorSnapshot,
13180) -> Vec<MultiBufferDiffHunk> {
13181 let mut hunks = Vec::new();
13182 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13183 HashMap::default();
13184 for query_range in ranges {
13185 let query_rows =
13186 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13187 for hunk in snapshot.diff_map.diff_hunks_in_range(
13188 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13189 &snapshot.buffer_snapshot,
13190 ) {
13191 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13192 // when the caret is just above or just below the deleted hunk.
13193 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13194 let related_to_selection = if allow_adjacent {
13195 hunk.row_range.overlaps(&query_rows)
13196 || hunk.row_range.start == query_rows.end
13197 || hunk.row_range.end == query_rows.start
13198 } else {
13199 hunk.row_range.overlaps(&query_rows)
13200 };
13201 if related_to_selection {
13202 if !processed_buffer_rows
13203 .entry(hunk.buffer_id)
13204 .or_default()
13205 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13206 {
13207 continue;
13208 }
13209 hunks.push(hunk);
13210 }
13211 }
13212 }
13213
13214 hunks
13215}
13216
13217pub trait CollaborationHub {
13218 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13219 fn user_participant_indices<'a>(
13220 &self,
13221 cx: &'a AppContext,
13222 ) -> &'a HashMap<u64, ParticipantIndex>;
13223 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13224}
13225
13226impl CollaborationHub for Model<Project> {
13227 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13228 self.read(cx).collaborators()
13229 }
13230
13231 fn user_participant_indices<'a>(
13232 &self,
13233 cx: &'a AppContext,
13234 ) -> &'a HashMap<u64, ParticipantIndex> {
13235 self.read(cx).user_store().read(cx).participant_indices()
13236 }
13237
13238 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13239 let this = self.read(cx);
13240 let user_ids = this.collaborators().values().map(|c| c.user_id);
13241 this.user_store().read_with(cx, |user_store, cx| {
13242 user_store.participant_names(user_ids, cx)
13243 })
13244 }
13245}
13246
13247pub trait SemanticsProvider {
13248 fn hover(
13249 &self,
13250 buffer: &Model<Buffer>,
13251 position: text::Anchor,
13252 cx: &mut AppContext,
13253 ) -> Option<Task<Vec<project::Hover>>>;
13254
13255 fn inlay_hints(
13256 &self,
13257 buffer_handle: Model<Buffer>,
13258 range: Range<text::Anchor>,
13259 cx: &mut AppContext,
13260 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13261
13262 fn resolve_inlay_hint(
13263 &self,
13264 hint: InlayHint,
13265 buffer_handle: Model<Buffer>,
13266 server_id: LanguageServerId,
13267 cx: &mut AppContext,
13268 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13269
13270 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13271
13272 fn document_highlights(
13273 &self,
13274 buffer: &Model<Buffer>,
13275 position: text::Anchor,
13276 cx: &mut AppContext,
13277 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13278
13279 fn definitions(
13280 &self,
13281 buffer: &Model<Buffer>,
13282 position: text::Anchor,
13283 kind: GotoDefinitionKind,
13284 cx: &mut AppContext,
13285 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13286
13287 fn range_for_rename(
13288 &self,
13289 buffer: &Model<Buffer>,
13290 position: text::Anchor,
13291 cx: &mut AppContext,
13292 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13293
13294 fn perform_rename(
13295 &self,
13296 buffer: &Model<Buffer>,
13297 position: text::Anchor,
13298 new_name: String,
13299 cx: &mut AppContext,
13300 ) -> Option<Task<Result<ProjectTransaction>>>;
13301}
13302
13303pub trait CompletionProvider {
13304 fn completions(
13305 &self,
13306 buffer: &Model<Buffer>,
13307 buffer_position: text::Anchor,
13308 trigger: CompletionContext,
13309 cx: &mut ViewContext<Editor>,
13310 ) -> Task<Result<Vec<Completion>>>;
13311
13312 fn resolve_completions(
13313 &self,
13314 buffer: Model<Buffer>,
13315 completion_indices: Vec<usize>,
13316 completions: Rc<RefCell<Box<[Completion]>>>,
13317 cx: &mut ViewContext<Editor>,
13318 ) -> Task<Result<bool>>;
13319
13320 fn apply_additional_edits_for_completion(
13321 &self,
13322 buffer: Model<Buffer>,
13323 completion: Completion,
13324 push_to_history: bool,
13325 cx: &mut ViewContext<Editor>,
13326 ) -> Task<Result<Option<language::Transaction>>>;
13327
13328 fn is_completion_trigger(
13329 &self,
13330 buffer: &Model<Buffer>,
13331 position: language::Anchor,
13332 text: &str,
13333 trigger_in_words: bool,
13334 cx: &mut ViewContext<Editor>,
13335 ) -> bool;
13336
13337 fn sort_completions(&self) -> bool {
13338 true
13339 }
13340}
13341
13342pub trait CodeActionProvider {
13343 fn code_actions(
13344 &self,
13345 buffer: &Model<Buffer>,
13346 range: Range<text::Anchor>,
13347 cx: &mut WindowContext,
13348 ) -> Task<Result<Vec<CodeAction>>>;
13349
13350 fn apply_code_action(
13351 &self,
13352 buffer_handle: Model<Buffer>,
13353 action: CodeAction,
13354 excerpt_id: ExcerptId,
13355 push_to_history: bool,
13356 cx: &mut WindowContext,
13357 ) -> Task<Result<ProjectTransaction>>;
13358}
13359
13360impl CodeActionProvider for Model<Project> {
13361 fn code_actions(
13362 &self,
13363 buffer: &Model<Buffer>,
13364 range: Range<text::Anchor>,
13365 cx: &mut WindowContext,
13366 ) -> Task<Result<Vec<CodeAction>>> {
13367 self.update(cx, |project, cx| {
13368 project.code_actions(buffer, range, None, cx)
13369 })
13370 }
13371
13372 fn apply_code_action(
13373 &self,
13374 buffer_handle: Model<Buffer>,
13375 action: CodeAction,
13376 _excerpt_id: ExcerptId,
13377 push_to_history: bool,
13378 cx: &mut WindowContext,
13379 ) -> Task<Result<ProjectTransaction>> {
13380 self.update(cx, |project, cx| {
13381 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13382 })
13383 }
13384}
13385
13386fn snippet_completions(
13387 project: &Project,
13388 buffer: &Model<Buffer>,
13389 buffer_position: text::Anchor,
13390 cx: &mut AppContext,
13391) -> Task<Result<Vec<Completion>>> {
13392 let language = buffer.read(cx).language_at(buffer_position);
13393 let language_name = language.as_ref().map(|language| language.lsp_id());
13394 let snippet_store = project.snippets().read(cx);
13395 let snippets = snippet_store.snippets_for(language_name, cx);
13396
13397 if snippets.is_empty() {
13398 return Task::ready(Ok(vec![]));
13399 }
13400 let snapshot = buffer.read(cx).text_snapshot();
13401 let chars: String = snapshot
13402 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13403 .collect();
13404
13405 let scope = language.map(|language| language.default_scope());
13406 let executor = cx.background_executor().clone();
13407
13408 cx.background_executor().spawn(async move {
13409 let classifier = CharClassifier::new(scope).for_completion(true);
13410 let mut last_word = chars
13411 .chars()
13412 .take_while(|c| classifier.is_word(*c))
13413 .collect::<String>();
13414 last_word = last_word.chars().rev().collect();
13415
13416 if last_word.is_empty() {
13417 return Ok(vec![]);
13418 }
13419
13420 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13421 let to_lsp = |point: &text::Anchor| {
13422 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13423 point_to_lsp(end)
13424 };
13425 let lsp_end = to_lsp(&buffer_position);
13426
13427 let candidates = snippets
13428 .iter()
13429 .enumerate()
13430 .flat_map(|(ix, snippet)| {
13431 snippet
13432 .prefix
13433 .iter()
13434 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13435 })
13436 .collect::<Vec<StringMatchCandidate>>();
13437
13438 let mut matches = fuzzy::match_strings(
13439 &candidates,
13440 &last_word,
13441 last_word.chars().any(|c| c.is_uppercase()),
13442 100,
13443 &Default::default(),
13444 executor,
13445 )
13446 .await;
13447
13448 // Remove all candidates where the query's start does not match the start of any word in the candidate
13449 if let Some(query_start) = last_word.chars().next() {
13450 matches.retain(|string_match| {
13451 split_words(&string_match.string).any(|word| {
13452 // Check that the first codepoint of the word as lowercase matches the first
13453 // codepoint of the query as lowercase
13454 word.chars()
13455 .flat_map(|codepoint| codepoint.to_lowercase())
13456 .zip(query_start.to_lowercase())
13457 .all(|(word_cp, query_cp)| word_cp == query_cp)
13458 })
13459 });
13460 }
13461
13462 let matched_strings = matches
13463 .into_iter()
13464 .map(|m| m.string)
13465 .collect::<HashSet<_>>();
13466
13467 let result: Vec<Completion> = snippets
13468 .into_iter()
13469 .filter_map(|snippet| {
13470 let matching_prefix = snippet
13471 .prefix
13472 .iter()
13473 .find(|prefix| matched_strings.contains(*prefix))?;
13474 let start = as_offset - last_word.len();
13475 let start = snapshot.anchor_before(start);
13476 let range = start..buffer_position;
13477 let lsp_start = to_lsp(&start);
13478 let lsp_range = lsp::Range {
13479 start: lsp_start,
13480 end: lsp_end,
13481 };
13482 Some(Completion {
13483 old_range: range,
13484 new_text: snippet.body.clone(),
13485 label: CodeLabel {
13486 text: matching_prefix.clone(),
13487 runs: vec![],
13488 filter_range: 0..matching_prefix.len(),
13489 },
13490 server_id: LanguageServerId(usize::MAX),
13491 documentation: snippet.description.clone().map(Documentation::SingleLine),
13492 lsp_completion: lsp::CompletionItem {
13493 label: snippet.prefix.first().unwrap().clone(),
13494 kind: Some(CompletionItemKind::SNIPPET),
13495 label_details: snippet.description.as_ref().map(|description| {
13496 lsp::CompletionItemLabelDetails {
13497 detail: Some(description.clone()),
13498 description: None,
13499 }
13500 }),
13501 insert_text_format: Some(InsertTextFormat::SNIPPET),
13502 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13503 lsp::InsertReplaceEdit {
13504 new_text: snippet.body.clone(),
13505 insert: lsp_range,
13506 replace: lsp_range,
13507 },
13508 )),
13509 filter_text: Some(snippet.body.clone()),
13510 sort_text: Some(char::MAX.to_string()),
13511 ..Default::default()
13512 },
13513 confirm: None,
13514 })
13515 })
13516 .collect();
13517
13518 Ok(result)
13519 })
13520}
13521
13522impl CompletionProvider for Model<Project> {
13523 fn completions(
13524 &self,
13525 buffer: &Model<Buffer>,
13526 buffer_position: text::Anchor,
13527 options: CompletionContext,
13528 cx: &mut ViewContext<Editor>,
13529 ) -> Task<Result<Vec<Completion>>> {
13530 self.update(cx, |project, cx| {
13531 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13532 let project_completions = project.completions(buffer, buffer_position, options, cx);
13533 cx.background_executor().spawn(async move {
13534 let mut completions = project_completions.await?;
13535 let snippets_completions = snippets.await?;
13536 completions.extend(snippets_completions);
13537 Ok(completions)
13538 })
13539 })
13540 }
13541
13542 fn resolve_completions(
13543 &self,
13544 buffer: Model<Buffer>,
13545 completion_indices: Vec<usize>,
13546 completions: Rc<RefCell<Box<[Completion]>>>,
13547 cx: &mut ViewContext<Editor>,
13548 ) -> Task<Result<bool>> {
13549 self.update(cx, |project, cx| {
13550 project.resolve_completions(buffer, completion_indices, completions, cx)
13551 })
13552 }
13553
13554 fn apply_additional_edits_for_completion(
13555 &self,
13556 buffer: Model<Buffer>,
13557 completion: Completion,
13558 push_to_history: bool,
13559 cx: &mut ViewContext<Editor>,
13560 ) -> Task<Result<Option<language::Transaction>>> {
13561 self.update(cx, |project, cx| {
13562 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13563 })
13564 }
13565
13566 fn is_completion_trigger(
13567 &self,
13568 buffer: &Model<Buffer>,
13569 position: language::Anchor,
13570 text: &str,
13571 trigger_in_words: bool,
13572 cx: &mut ViewContext<Editor>,
13573 ) -> bool {
13574 let mut chars = text.chars();
13575 let char = if let Some(char) = chars.next() {
13576 char
13577 } else {
13578 return false;
13579 };
13580 if chars.next().is_some() {
13581 return false;
13582 }
13583
13584 let buffer = buffer.read(cx);
13585 let snapshot = buffer.snapshot();
13586 if !snapshot.settings_at(position, cx).show_completions_on_input {
13587 return false;
13588 }
13589 let classifier = snapshot.char_classifier_at(position).for_completion(true);
13590 if trigger_in_words && classifier.is_word(char) {
13591 return true;
13592 }
13593
13594 buffer.completion_triggers().contains(text)
13595 }
13596}
13597
13598impl SemanticsProvider for Model<Project> {
13599 fn hover(
13600 &self,
13601 buffer: &Model<Buffer>,
13602 position: text::Anchor,
13603 cx: &mut AppContext,
13604 ) -> Option<Task<Vec<project::Hover>>> {
13605 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13606 }
13607
13608 fn document_highlights(
13609 &self,
13610 buffer: &Model<Buffer>,
13611 position: text::Anchor,
13612 cx: &mut AppContext,
13613 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13614 Some(self.update(cx, |project, cx| {
13615 project.document_highlights(buffer, position, cx)
13616 }))
13617 }
13618
13619 fn definitions(
13620 &self,
13621 buffer: &Model<Buffer>,
13622 position: text::Anchor,
13623 kind: GotoDefinitionKind,
13624 cx: &mut AppContext,
13625 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13626 Some(self.update(cx, |project, cx| match kind {
13627 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13628 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13629 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13630 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13631 }))
13632 }
13633
13634 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13635 // TODO: make this work for remote projects
13636 self.read(cx)
13637 .language_servers_for_local_buffer(buffer.read(cx), cx)
13638 .any(
13639 |(_, server)| match server.capabilities().inlay_hint_provider {
13640 Some(lsp::OneOf::Left(enabled)) => enabled,
13641 Some(lsp::OneOf::Right(_)) => true,
13642 None => false,
13643 },
13644 )
13645 }
13646
13647 fn inlay_hints(
13648 &self,
13649 buffer_handle: Model<Buffer>,
13650 range: Range<text::Anchor>,
13651 cx: &mut AppContext,
13652 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13653 Some(self.update(cx, |project, cx| {
13654 project.inlay_hints(buffer_handle, range, cx)
13655 }))
13656 }
13657
13658 fn resolve_inlay_hint(
13659 &self,
13660 hint: InlayHint,
13661 buffer_handle: Model<Buffer>,
13662 server_id: LanguageServerId,
13663 cx: &mut AppContext,
13664 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13665 Some(self.update(cx, |project, cx| {
13666 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13667 }))
13668 }
13669
13670 fn range_for_rename(
13671 &self,
13672 buffer: &Model<Buffer>,
13673 position: text::Anchor,
13674 cx: &mut AppContext,
13675 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13676 Some(self.update(cx, |project, cx| {
13677 project.prepare_rename(buffer.clone(), position, cx)
13678 }))
13679 }
13680
13681 fn perform_rename(
13682 &self,
13683 buffer: &Model<Buffer>,
13684 position: text::Anchor,
13685 new_name: String,
13686 cx: &mut AppContext,
13687 ) -> Option<Task<Result<ProjectTransaction>>> {
13688 Some(self.update(cx, |project, cx| {
13689 project.perform_rename(buffer.clone(), position, new_name, cx)
13690 }))
13691 }
13692}
13693
13694fn inlay_hint_settings(
13695 location: Anchor,
13696 snapshot: &MultiBufferSnapshot,
13697 cx: &mut ViewContext<'_, Editor>,
13698) -> InlayHintSettings {
13699 let file = snapshot.file_at(location);
13700 let language = snapshot.language_at(location).map(|l| l.name());
13701 language_settings(language, file, cx).inlay_hints
13702}
13703
13704fn consume_contiguous_rows(
13705 contiguous_row_selections: &mut Vec<Selection<Point>>,
13706 selection: &Selection<Point>,
13707 display_map: &DisplaySnapshot,
13708 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13709) -> (MultiBufferRow, MultiBufferRow) {
13710 contiguous_row_selections.push(selection.clone());
13711 let start_row = MultiBufferRow(selection.start.row);
13712 let mut end_row = ending_row(selection, display_map);
13713
13714 while let Some(next_selection) = selections.peek() {
13715 if next_selection.start.row <= end_row.0 {
13716 end_row = ending_row(next_selection, display_map);
13717 contiguous_row_selections.push(selections.next().unwrap().clone());
13718 } else {
13719 break;
13720 }
13721 }
13722 (start_row, end_row)
13723}
13724
13725fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13726 if next_selection.end.column > 0 || next_selection.is_empty() {
13727 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13728 } else {
13729 MultiBufferRow(next_selection.end.row)
13730 }
13731}
13732
13733impl EditorSnapshot {
13734 pub fn remote_selections_in_range<'a>(
13735 &'a self,
13736 range: &'a Range<Anchor>,
13737 collaboration_hub: &dyn CollaborationHub,
13738 cx: &'a AppContext,
13739 ) -> impl 'a + Iterator<Item = RemoteSelection> {
13740 let participant_names = collaboration_hub.user_names(cx);
13741 let participant_indices = collaboration_hub.user_participant_indices(cx);
13742 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13743 let collaborators_by_replica_id = collaborators_by_peer_id
13744 .iter()
13745 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13746 .collect::<HashMap<_, _>>();
13747 self.buffer_snapshot
13748 .selections_in_range(range, false)
13749 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13750 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13751 let participant_index = participant_indices.get(&collaborator.user_id).copied();
13752 let user_name = participant_names.get(&collaborator.user_id).cloned();
13753 Some(RemoteSelection {
13754 replica_id,
13755 selection,
13756 cursor_shape,
13757 line_mode,
13758 participant_index,
13759 peer_id: collaborator.peer_id,
13760 user_name,
13761 })
13762 })
13763 }
13764
13765 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13766 self.display_snapshot.buffer_snapshot.language_at(position)
13767 }
13768
13769 pub fn is_focused(&self) -> bool {
13770 self.is_focused
13771 }
13772
13773 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13774 self.placeholder_text.as_ref()
13775 }
13776
13777 pub fn scroll_position(&self) -> gpui::Point<f32> {
13778 self.scroll_anchor.scroll_position(&self.display_snapshot)
13779 }
13780
13781 fn gutter_dimensions(
13782 &self,
13783 font_id: FontId,
13784 font_size: Pixels,
13785 em_width: Pixels,
13786 em_advance: Pixels,
13787 max_line_number_width: Pixels,
13788 cx: &AppContext,
13789 ) -> GutterDimensions {
13790 if !self.show_gutter {
13791 return GutterDimensions::default();
13792 }
13793 let descent = cx.text_system().descent(font_id, font_size);
13794
13795 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13796 matches!(
13797 ProjectSettings::get_global(cx).git.git_gutter,
13798 Some(GitGutterSetting::TrackedFiles)
13799 )
13800 });
13801 let gutter_settings = EditorSettings::get_global(cx).gutter;
13802 let show_line_numbers = self
13803 .show_line_numbers
13804 .unwrap_or(gutter_settings.line_numbers);
13805 let line_gutter_width = if show_line_numbers {
13806 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13807 let min_width_for_number_on_gutter = em_advance * 4.0;
13808 max_line_number_width.max(min_width_for_number_on_gutter)
13809 } else {
13810 0.0.into()
13811 };
13812
13813 let show_code_actions = self
13814 .show_code_actions
13815 .unwrap_or(gutter_settings.code_actions);
13816
13817 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13818
13819 let git_blame_entries_width =
13820 self.git_blame_gutter_max_author_length
13821 .map(|max_author_length| {
13822 // Length of the author name, but also space for the commit hash,
13823 // the spacing and the timestamp.
13824 let max_char_count = max_author_length
13825 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13826 + 7 // length of commit sha
13827 + 14 // length of max relative timestamp ("60 minutes ago")
13828 + 4; // gaps and margins
13829
13830 em_advance * max_char_count
13831 });
13832
13833 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13834 left_padding += if show_code_actions || show_runnables {
13835 em_width * 3.0
13836 } else if show_git_gutter && show_line_numbers {
13837 em_width * 2.0
13838 } else if show_git_gutter || show_line_numbers {
13839 em_width
13840 } else {
13841 px(0.)
13842 };
13843
13844 let right_padding = if gutter_settings.folds && show_line_numbers {
13845 em_width * 4.0
13846 } else if gutter_settings.folds {
13847 em_width * 3.0
13848 } else if show_line_numbers {
13849 em_width
13850 } else {
13851 px(0.)
13852 };
13853
13854 GutterDimensions {
13855 left_padding,
13856 right_padding,
13857 width: line_gutter_width + left_padding + right_padding,
13858 margin: -descent,
13859 git_blame_entries_width,
13860 }
13861 }
13862
13863 pub fn render_crease_toggle(
13864 &self,
13865 buffer_row: MultiBufferRow,
13866 row_contains_cursor: bool,
13867 editor: View<Editor>,
13868 cx: &mut WindowContext,
13869 ) -> Option<AnyElement> {
13870 let folded = self.is_line_folded(buffer_row);
13871 let mut is_foldable = false;
13872
13873 if let Some(crease) = self
13874 .crease_snapshot
13875 .query_row(buffer_row, &self.buffer_snapshot)
13876 {
13877 is_foldable = true;
13878 match crease {
13879 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
13880 if let Some(render_toggle) = render_toggle {
13881 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13882 if folded {
13883 editor.update(cx, |editor, cx| {
13884 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13885 });
13886 } else {
13887 editor.update(cx, |editor, cx| {
13888 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13889 });
13890 }
13891 });
13892 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
13893 }
13894 }
13895 }
13896 }
13897
13898 is_foldable |= self.starts_indent(buffer_row);
13899
13900 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
13901 Some(
13902 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
13903 .toggle_state(folded)
13904 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13905 if folded {
13906 this.unfold_at(&UnfoldAt { buffer_row }, cx);
13907 } else {
13908 this.fold_at(&FoldAt { buffer_row }, cx);
13909 }
13910 }))
13911 .into_any_element(),
13912 )
13913 } else {
13914 None
13915 }
13916 }
13917
13918 pub fn render_crease_trailer(
13919 &self,
13920 buffer_row: MultiBufferRow,
13921 cx: &mut WindowContext,
13922 ) -> Option<AnyElement> {
13923 let folded = self.is_line_folded(buffer_row);
13924 if let Crease::Inline { render_trailer, .. } = self
13925 .crease_snapshot
13926 .query_row(buffer_row, &self.buffer_snapshot)?
13927 {
13928 let render_trailer = render_trailer.as_ref()?;
13929 Some(render_trailer(buffer_row, folded, cx))
13930 } else {
13931 None
13932 }
13933 }
13934}
13935
13936impl Deref for EditorSnapshot {
13937 type Target = DisplaySnapshot;
13938
13939 fn deref(&self) -> &Self::Target {
13940 &self.display_snapshot
13941 }
13942}
13943
13944#[derive(Clone, Debug, PartialEq, Eq)]
13945pub enum EditorEvent {
13946 InputIgnored {
13947 text: Arc<str>,
13948 },
13949 InputHandled {
13950 utf16_range_to_replace: Option<Range<isize>>,
13951 text: Arc<str>,
13952 },
13953 ExcerptsAdded {
13954 buffer: Model<Buffer>,
13955 predecessor: ExcerptId,
13956 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13957 },
13958 ExcerptsRemoved {
13959 ids: Vec<ExcerptId>,
13960 },
13961 BufferFoldToggled {
13962 ids: Vec<ExcerptId>,
13963 folded: bool,
13964 },
13965 ExcerptsEdited {
13966 ids: Vec<ExcerptId>,
13967 },
13968 ExcerptsExpanded {
13969 ids: Vec<ExcerptId>,
13970 },
13971 BufferEdited,
13972 Edited {
13973 transaction_id: clock::Lamport,
13974 },
13975 Reparsed(BufferId),
13976 Focused,
13977 FocusedIn,
13978 Blurred,
13979 DirtyChanged,
13980 Saved,
13981 TitleChanged,
13982 DiffBaseChanged,
13983 SelectionsChanged {
13984 local: bool,
13985 },
13986 ScrollPositionChanged {
13987 local: bool,
13988 autoscroll: bool,
13989 },
13990 Closed,
13991 TransactionUndone {
13992 transaction_id: clock::Lamport,
13993 },
13994 TransactionBegun {
13995 transaction_id: clock::Lamport,
13996 },
13997 Reloaded,
13998 CursorShapeChanged,
13999}
14000
14001impl EventEmitter<EditorEvent> for Editor {}
14002
14003impl FocusableView for Editor {
14004 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14005 self.focus_handle.clone()
14006 }
14007}
14008
14009impl Render for Editor {
14010 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14011 let settings = ThemeSettings::get_global(cx);
14012
14013 let mut text_style = match self.mode {
14014 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14015 color: cx.theme().colors().editor_foreground,
14016 font_family: settings.ui_font.family.clone(),
14017 font_features: settings.ui_font.features.clone(),
14018 font_fallbacks: settings.ui_font.fallbacks.clone(),
14019 font_size: rems(0.875).into(),
14020 font_weight: settings.ui_font.weight,
14021 line_height: relative(settings.buffer_line_height.value()),
14022 ..Default::default()
14023 },
14024 EditorMode::Full => TextStyle {
14025 color: cx.theme().colors().editor_foreground,
14026 font_family: settings.buffer_font.family.clone(),
14027 font_features: settings.buffer_font.features.clone(),
14028 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14029 font_size: settings.buffer_font_size(cx).into(),
14030 font_weight: settings.buffer_font.weight,
14031 line_height: relative(settings.buffer_line_height.value()),
14032 ..Default::default()
14033 },
14034 };
14035 if let Some(text_style_refinement) = &self.text_style_refinement {
14036 text_style.refine(text_style_refinement)
14037 }
14038
14039 let background = match self.mode {
14040 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14041 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14042 EditorMode::Full => cx.theme().colors().editor_background,
14043 };
14044
14045 EditorElement::new(
14046 cx.view(),
14047 EditorStyle {
14048 background,
14049 local_player: cx.theme().players().local(),
14050 text: text_style,
14051 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14052 syntax: cx.theme().syntax().clone(),
14053 status: cx.theme().status().clone(),
14054 inlay_hints_style: make_inlay_hints_style(cx),
14055 inline_completion_styles: make_suggestion_styles(cx),
14056 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14057 },
14058 )
14059 }
14060}
14061
14062impl ViewInputHandler for Editor {
14063 fn text_for_range(
14064 &mut self,
14065 range_utf16: Range<usize>,
14066 adjusted_range: &mut Option<Range<usize>>,
14067 cx: &mut ViewContext<Self>,
14068 ) -> Option<String> {
14069 let snapshot = self.buffer.read(cx).read(cx);
14070 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14071 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14072 if (start.0..end.0) != range_utf16 {
14073 adjusted_range.replace(start.0..end.0);
14074 }
14075 Some(snapshot.text_for_range(start..end).collect())
14076 }
14077
14078 fn selected_text_range(
14079 &mut self,
14080 ignore_disabled_input: bool,
14081 cx: &mut ViewContext<Self>,
14082 ) -> Option<UTF16Selection> {
14083 // Prevent the IME menu from appearing when holding down an alphabetic key
14084 // while input is disabled.
14085 if !ignore_disabled_input && !self.input_enabled {
14086 return None;
14087 }
14088
14089 let selection = self.selections.newest::<OffsetUtf16>(cx);
14090 let range = selection.range();
14091
14092 Some(UTF16Selection {
14093 range: range.start.0..range.end.0,
14094 reversed: selection.reversed,
14095 })
14096 }
14097
14098 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14099 let snapshot = self.buffer.read(cx).read(cx);
14100 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14101 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14102 }
14103
14104 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14105 self.clear_highlights::<InputComposition>(cx);
14106 self.ime_transaction.take();
14107 }
14108
14109 fn replace_text_in_range(
14110 &mut self,
14111 range_utf16: Option<Range<usize>>,
14112 text: &str,
14113 cx: &mut ViewContext<Self>,
14114 ) {
14115 if !self.input_enabled {
14116 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14117 return;
14118 }
14119
14120 self.transact(cx, |this, cx| {
14121 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14122 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14123 Some(this.selection_replacement_ranges(range_utf16, cx))
14124 } else {
14125 this.marked_text_ranges(cx)
14126 };
14127
14128 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14129 let newest_selection_id = this.selections.newest_anchor().id;
14130 this.selections
14131 .all::<OffsetUtf16>(cx)
14132 .iter()
14133 .zip(ranges_to_replace.iter())
14134 .find_map(|(selection, range)| {
14135 if selection.id == newest_selection_id {
14136 Some(
14137 (range.start.0 as isize - selection.head().0 as isize)
14138 ..(range.end.0 as isize - selection.head().0 as isize),
14139 )
14140 } else {
14141 None
14142 }
14143 })
14144 });
14145
14146 cx.emit(EditorEvent::InputHandled {
14147 utf16_range_to_replace: range_to_replace,
14148 text: text.into(),
14149 });
14150
14151 if let Some(new_selected_ranges) = new_selected_ranges {
14152 this.change_selections(None, cx, |selections| {
14153 selections.select_ranges(new_selected_ranges)
14154 });
14155 this.backspace(&Default::default(), cx);
14156 }
14157
14158 this.handle_input(text, cx);
14159 });
14160
14161 if let Some(transaction) = self.ime_transaction {
14162 self.buffer.update(cx, |buffer, cx| {
14163 buffer.group_until_transaction(transaction, cx);
14164 });
14165 }
14166
14167 self.unmark_text(cx);
14168 }
14169
14170 fn replace_and_mark_text_in_range(
14171 &mut self,
14172 range_utf16: Option<Range<usize>>,
14173 text: &str,
14174 new_selected_range_utf16: Option<Range<usize>>,
14175 cx: &mut ViewContext<Self>,
14176 ) {
14177 if !self.input_enabled {
14178 return;
14179 }
14180
14181 let transaction = self.transact(cx, |this, cx| {
14182 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14183 let snapshot = this.buffer.read(cx).read(cx);
14184 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14185 for marked_range in &mut marked_ranges {
14186 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14187 marked_range.start.0 += relative_range_utf16.start;
14188 marked_range.start =
14189 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14190 marked_range.end =
14191 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14192 }
14193 }
14194 Some(marked_ranges)
14195 } else if let Some(range_utf16) = range_utf16 {
14196 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14197 Some(this.selection_replacement_ranges(range_utf16, cx))
14198 } else {
14199 None
14200 };
14201
14202 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14203 let newest_selection_id = this.selections.newest_anchor().id;
14204 this.selections
14205 .all::<OffsetUtf16>(cx)
14206 .iter()
14207 .zip(ranges_to_replace.iter())
14208 .find_map(|(selection, range)| {
14209 if selection.id == newest_selection_id {
14210 Some(
14211 (range.start.0 as isize - selection.head().0 as isize)
14212 ..(range.end.0 as isize - selection.head().0 as isize),
14213 )
14214 } else {
14215 None
14216 }
14217 })
14218 });
14219
14220 cx.emit(EditorEvent::InputHandled {
14221 utf16_range_to_replace: range_to_replace,
14222 text: text.into(),
14223 });
14224
14225 if let Some(ranges) = ranges_to_replace {
14226 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14227 }
14228
14229 let marked_ranges = {
14230 let snapshot = this.buffer.read(cx).read(cx);
14231 this.selections
14232 .disjoint_anchors()
14233 .iter()
14234 .map(|selection| {
14235 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14236 })
14237 .collect::<Vec<_>>()
14238 };
14239
14240 if text.is_empty() {
14241 this.unmark_text(cx);
14242 } else {
14243 this.highlight_text::<InputComposition>(
14244 marked_ranges.clone(),
14245 HighlightStyle {
14246 underline: Some(UnderlineStyle {
14247 thickness: px(1.),
14248 color: None,
14249 wavy: false,
14250 }),
14251 ..Default::default()
14252 },
14253 cx,
14254 );
14255 }
14256
14257 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14258 let use_autoclose = this.use_autoclose;
14259 let use_auto_surround = this.use_auto_surround;
14260 this.set_use_autoclose(false);
14261 this.set_use_auto_surround(false);
14262 this.handle_input(text, cx);
14263 this.set_use_autoclose(use_autoclose);
14264 this.set_use_auto_surround(use_auto_surround);
14265
14266 if let Some(new_selected_range) = new_selected_range_utf16 {
14267 let snapshot = this.buffer.read(cx).read(cx);
14268 let new_selected_ranges = marked_ranges
14269 .into_iter()
14270 .map(|marked_range| {
14271 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14272 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14273 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14274 snapshot.clip_offset_utf16(new_start, Bias::Left)
14275 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14276 })
14277 .collect::<Vec<_>>();
14278
14279 drop(snapshot);
14280 this.change_selections(None, cx, |selections| {
14281 selections.select_ranges(new_selected_ranges)
14282 });
14283 }
14284 });
14285
14286 self.ime_transaction = self.ime_transaction.or(transaction);
14287 if let Some(transaction) = self.ime_transaction {
14288 self.buffer.update(cx, |buffer, cx| {
14289 buffer.group_until_transaction(transaction, cx);
14290 });
14291 }
14292
14293 if self.text_highlights::<InputComposition>(cx).is_none() {
14294 self.ime_transaction.take();
14295 }
14296 }
14297
14298 fn bounds_for_range(
14299 &mut self,
14300 range_utf16: Range<usize>,
14301 element_bounds: gpui::Bounds<Pixels>,
14302 cx: &mut ViewContext<Self>,
14303 ) -> Option<gpui::Bounds<Pixels>> {
14304 let text_layout_details = self.text_layout_details(cx);
14305 let gpui::Point {
14306 x: em_width,
14307 y: line_height,
14308 } = self.character_size(cx);
14309
14310 let snapshot = self.snapshot(cx);
14311 let scroll_position = snapshot.scroll_position();
14312 let scroll_left = scroll_position.x * em_width;
14313
14314 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14315 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14316 + self.gutter_dimensions.width
14317 + self.gutter_dimensions.margin;
14318 let y = line_height * (start.row().as_f32() - scroll_position.y);
14319
14320 Some(Bounds {
14321 origin: element_bounds.origin + point(x, y),
14322 size: size(em_width, line_height),
14323 })
14324 }
14325}
14326
14327trait SelectionExt {
14328 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14329 fn spanned_rows(
14330 &self,
14331 include_end_if_at_line_start: bool,
14332 map: &DisplaySnapshot,
14333 ) -> Range<MultiBufferRow>;
14334}
14335
14336impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14337 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14338 let start = self
14339 .start
14340 .to_point(&map.buffer_snapshot)
14341 .to_display_point(map);
14342 let end = self
14343 .end
14344 .to_point(&map.buffer_snapshot)
14345 .to_display_point(map);
14346 if self.reversed {
14347 end..start
14348 } else {
14349 start..end
14350 }
14351 }
14352
14353 fn spanned_rows(
14354 &self,
14355 include_end_if_at_line_start: bool,
14356 map: &DisplaySnapshot,
14357 ) -> Range<MultiBufferRow> {
14358 let start = self.start.to_point(&map.buffer_snapshot);
14359 let mut end = self.end.to_point(&map.buffer_snapshot);
14360 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14361 end.row -= 1;
14362 }
14363
14364 let buffer_start = map.prev_line_boundary(start).0;
14365 let buffer_end = map.next_line_boundary(end).0;
14366 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14367 }
14368}
14369
14370impl<T: InvalidationRegion> InvalidationStack<T> {
14371 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14372 where
14373 S: Clone + ToOffset,
14374 {
14375 while let Some(region) = self.last() {
14376 let all_selections_inside_invalidation_ranges =
14377 if selections.len() == region.ranges().len() {
14378 selections
14379 .iter()
14380 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14381 .all(|(selection, invalidation_range)| {
14382 let head = selection.head().to_offset(buffer);
14383 invalidation_range.start <= head && invalidation_range.end >= head
14384 })
14385 } else {
14386 false
14387 };
14388
14389 if all_selections_inside_invalidation_ranges {
14390 break;
14391 } else {
14392 self.pop();
14393 }
14394 }
14395 }
14396}
14397
14398impl<T> Default for InvalidationStack<T> {
14399 fn default() -> Self {
14400 Self(Default::default())
14401 }
14402}
14403
14404impl<T> Deref for InvalidationStack<T> {
14405 type Target = Vec<T>;
14406
14407 fn deref(&self) -> &Self::Target {
14408 &self.0
14409 }
14410}
14411
14412impl<T> DerefMut for InvalidationStack<T> {
14413 fn deref_mut(&mut self) -> &mut Self::Target {
14414 &mut self.0
14415 }
14416}
14417
14418impl InvalidationRegion for SnippetState {
14419 fn ranges(&self) -> &[Range<Anchor>] {
14420 &self.ranges[self.active_index]
14421 }
14422}
14423
14424pub fn diagnostic_block_renderer(
14425 diagnostic: Diagnostic,
14426 max_message_rows: Option<u8>,
14427 allow_closing: bool,
14428 _is_valid: bool,
14429) -> RenderBlock {
14430 let (text_without_backticks, code_ranges) =
14431 highlight_diagnostic_message(&diagnostic, max_message_rows);
14432
14433 Arc::new(move |cx: &mut BlockContext| {
14434 let group_id: SharedString = cx.block_id.to_string().into();
14435
14436 let mut text_style = cx.text_style().clone();
14437 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14438 let theme_settings = ThemeSettings::get_global(cx);
14439 text_style.font_family = theme_settings.buffer_font.family.clone();
14440 text_style.font_style = theme_settings.buffer_font.style;
14441 text_style.font_features = theme_settings.buffer_font.features.clone();
14442 text_style.font_weight = theme_settings.buffer_font.weight;
14443
14444 let multi_line_diagnostic = diagnostic.message.contains('\n');
14445
14446 let buttons = |diagnostic: &Diagnostic| {
14447 if multi_line_diagnostic {
14448 v_flex()
14449 } else {
14450 h_flex()
14451 }
14452 .when(allow_closing, |div| {
14453 div.children(diagnostic.is_primary.then(|| {
14454 IconButton::new("close-block", IconName::XCircle)
14455 .icon_color(Color::Muted)
14456 .size(ButtonSize::Compact)
14457 .style(ButtonStyle::Transparent)
14458 .visible_on_hover(group_id.clone())
14459 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14460 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14461 }))
14462 })
14463 .child(
14464 IconButton::new("copy-block", IconName::Copy)
14465 .icon_color(Color::Muted)
14466 .size(ButtonSize::Compact)
14467 .style(ButtonStyle::Transparent)
14468 .visible_on_hover(group_id.clone())
14469 .on_click({
14470 let message = diagnostic.message.clone();
14471 move |_click, cx| {
14472 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14473 }
14474 })
14475 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14476 )
14477 };
14478
14479 let icon_size = buttons(&diagnostic)
14480 .into_any_element()
14481 .layout_as_root(AvailableSpace::min_size(), cx);
14482
14483 h_flex()
14484 .id(cx.block_id)
14485 .group(group_id.clone())
14486 .relative()
14487 .size_full()
14488 .block_mouse_down()
14489 .pl(cx.gutter_dimensions.width)
14490 .w(cx.max_width - cx.gutter_dimensions.full_width())
14491 .child(
14492 div()
14493 .flex()
14494 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14495 .flex_shrink(),
14496 )
14497 .child(buttons(&diagnostic))
14498 .child(div().flex().flex_shrink_0().child(
14499 StyledText::new(text_without_backticks.clone()).with_highlights(
14500 &text_style,
14501 code_ranges.iter().map(|range| {
14502 (
14503 range.clone(),
14504 HighlightStyle {
14505 font_weight: Some(FontWeight::BOLD),
14506 ..Default::default()
14507 },
14508 )
14509 }),
14510 ),
14511 ))
14512 .into_any_element()
14513 })
14514}
14515
14516pub fn highlight_diagnostic_message(
14517 diagnostic: &Diagnostic,
14518 mut max_message_rows: Option<u8>,
14519) -> (SharedString, Vec<Range<usize>>) {
14520 let mut text_without_backticks = String::new();
14521 let mut code_ranges = Vec::new();
14522
14523 if let Some(source) = &diagnostic.source {
14524 text_without_backticks.push_str(source);
14525 code_ranges.push(0..source.len());
14526 text_without_backticks.push_str(": ");
14527 }
14528
14529 let mut prev_offset = 0;
14530 let mut in_code_block = false;
14531 let has_row_limit = max_message_rows.is_some();
14532 let mut newline_indices = diagnostic
14533 .message
14534 .match_indices('\n')
14535 .filter(|_| has_row_limit)
14536 .map(|(ix, _)| ix)
14537 .fuse()
14538 .peekable();
14539
14540 for (quote_ix, _) in diagnostic
14541 .message
14542 .match_indices('`')
14543 .chain([(diagnostic.message.len(), "")])
14544 {
14545 let mut first_newline_ix = None;
14546 let mut last_newline_ix = None;
14547 while let Some(newline_ix) = newline_indices.peek() {
14548 if *newline_ix < quote_ix {
14549 if first_newline_ix.is_none() {
14550 first_newline_ix = Some(*newline_ix);
14551 }
14552 last_newline_ix = Some(*newline_ix);
14553
14554 if let Some(rows_left) = &mut max_message_rows {
14555 if *rows_left == 0 {
14556 break;
14557 } else {
14558 *rows_left -= 1;
14559 }
14560 }
14561 let _ = newline_indices.next();
14562 } else {
14563 break;
14564 }
14565 }
14566 let prev_len = text_without_backticks.len();
14567 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14568 text_without_backticks.push_str(new_text);
14569 if in_code_block {
14570 code_ranges.push(prev_len..text_without_backticks.len());
14571 }
14572 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14573 in_code_block = !in_code_block;
14574 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14575 text_without_backticks.push_str("...");
14576 break;
14577 }
14578 }
14579
14580 (text_without_backticks.into(), code_ranges)
14581}
14582
14583fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14584 match severity {
14585 DiagnosticSeverity::ERROR => colors.error,
14586 DiagnosticSeverity::WARNING => colors.warning,
14587 DiagnosticSeverity::INFORMATION => colors.info,
14588 DiagnosticSeverity::HINT => colors.info,
14589 _ => colors.ignored,
14590 }
14591}
14592
14593pub fn styled_runs_for_code_label<'a>(
14594 label: &'a CodeLabel,
14595 syntax_theme: &'a theme::SyntaxTheme,
14596) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14597 let fade_out = HighlightStyle {
14598 fade_out: Some(0.35),
14599 ..Default::default()
14600 };
14601
14602 let mut prev_end = label.filter_range.end;
14603 label
14604 .runs
14605 .iter()
14606 .enumerate()
14607 .flat_map(move |(ix, (range, highlight_id))| {
14608 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14609 style
14610 } else {
14611 return Default::default();
14612 };
14613 let mut muted_style = style;
14614 muted_style.highlight(fade_out);
14615
14616 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14617 if range.start >= label.filter_range.end {
14618 if range.start > prev_end {
14619 runs.push((prev_end..range.start, fade_out));
14620 }
14621 runs.push((range.clone(), muted_style));
14622 } else if range.end <= label.filter_range.end {
14623 runs.push((range.clone(), style));
14624 } else {
14625 runs.push((range.start..label.filter_range.end, style));
14626 runs.push((label.filter_range.end..range.end, muted_style));
14627 }
14628 prev_end = cmp::max(prev_end, range.end);
14629
14630 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14631 runs.push((prev_end..label.text.len(), fade_out));
14632 }
14633
14634 runs
14635 })
14636}
14637
14638pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14639 let mut prev_index = 0;
14640 let mut prev_codepoint: Option<char> = None;
14641 text.char_indices()
14642 .chain([(text.len(), '\0')])
14643 .filter_map(move |(index, codepoint)| {
14644 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14645 let is_boundary = index == text.len()
14646 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14647 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14648 if is_boundary {
14649 let chunk = &text[prev_index..index];
14650 prev_index = index;
14651 Some(chunk)
14652 } else {
14653 None
14654 }
14655 })
14656}
14657
14658pub trait RangeToAnchorExt: Sized {
14659 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14660
14661 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14662 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14663 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14664 }
14665}
14666
14667impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14668 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14669 let start_offset = self.start.to_offset(snapshot);
14670 let end_offset = self.end.to_offset(snapshot);
14671 if start_offset == end_offset {
14672 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14673 } else {
14674 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14675 }
14676 }
14677}
14678
14679pub trait RowExt {
14680 fn as_f32(&self) -> f32;
14681
14682 fn next_row(&self) -> Self;
14683
14684 fn previous_row(&self) -> Self;
14685
14686 fn minus(&self, other: Self) -> u32;
14687}
14688
14689impl RowExt for DisplayRow {
14690 fn as_f32(&self) -> f32 {
14691 self.0 as f32
14692 }
14693
14694 fn next_row(&self) -> Self {
14695 Self(self.0 + 1)
14696 }
14697
14698 fn previous_row(&self) -> Self {
14699 Self(self.0.saturating_sub(1))
14700 }
14701
14702 fn minus(&self, other: Self) -> u32 {
14703 self.0 - other.0
14704 }
14705}
14706
14707impl RowExt for MultiBufferRow {
14708 fn as_f32(&self) -> f32 {
14709 self.0 as f32
14710 }
14711
14712 fn next_row(&self) -> Self {
14713 Self(self.0 + 1)
14714 }
14715
14716 fn previous_row(&self) -> Self {
14717 Self(self.0.saturating_sub(1))
14718 }
14719
14720 fn minus(&self, other: Self) -> u32 {
14721 self.0 - other.0
14722 }
14723}
14724
14725trait RowRangeExt {
14726 type Row;
14727
14728 fn len(&self) -> usize;
14729
14730 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14731}
14732
14733impl RowRangeExt for Range<MultiBufferRow> {
14734 type Row = MultiBufferRow;
14735
14736 fn len(&self) -> usize {
14737 (self.end.0 - self.start.0) as usize
14738 }
14739
14740 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14741 (self.start.0..self.end.0).map(MultiBufferRow)
14742 }
14743}
14744
14745impl RowRangeExt for Range<DisplayRow> {
14746 type Row = DisplayRow;
14747
14748 fn len(&self) -> usize {
14749 (self.end.0 - self.start.0) as usize
14750 }
14751
14752 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14753 (self.start.0..self.end.0).map(DisplayRow)
14754 }
14755}
14756
14757fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14758 if hunk.diff_base_byte_range.is_empty() {
14759 DiffHunkStatus::Added
14760 } else if hunk.row_range.is_empty() {
14761 DiffHunkStatus::Removed
14762 } else {
14763 DiffHunkStatus::Modified
14764 }
14765}
14766
14767/// If select range has more than one line, we
14768/// just point the cursor to range.start.
14769fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14770 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14771 range
14772 } else {
14773 range.start..range.start
14774 }
14775}
14776
14777pub struct KillRing(ClipboardItem);
14778impl Global for KillRing {}
14779
14780const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);