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 parking_lot::RwLock;
131use project::{
132 lsp_store::{FormatTarget, FormatTrigger, OpenLspBufferHandle},
133 project_settings::{GitGutterSetting, ProjectSettings},
134 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
135 LspStore, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
136};
137use rand::prelude::*;
138use rpc::{proto::*, ErrorExt};
139use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
140use selections_collection::{
141 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
142};
143use serde::{Deserialize, Serialize};
144use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
145use smallvec::SmallVec;
146use snippet::Snippet;
147use std::{
148 any::TypeId,
149 borrow::Cow,
150 cell::RefCell,
151 cmp::{self, Ordering, Reverse},
152 mem,
153 num::NonZeroU32,
154 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
155 path::{Path, PathBuf},
156 rc::Rc,
157 sync::Arc,
158 time::{Duration, Instant},
159};
160pub use sum_tree::Bias;
161use sum_tree::TreeMap;
162use text::{BufferId, OffsetUtf16, Rope};
163use theme::{
164 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
165 ThemeColors, ThemeSettings,
166};
167use ui::{
168 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
169 PopoverMenuHandle, Tooltip,
170};
171use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
172use workspace::item::{ItemHandle, PreviewTabsSettings};
173use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
174use workspace::{
175 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
176};
177use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
178
179use crate::hover_links::{find_url, find_url_from_range};
180use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
181
182pub const FILE_HEADER_HEIGHT: u32 = 2;
183pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
184pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
185pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
186const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
187const MAX_LINE_LEN: usize = 1024;
188const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
189const MAX_SELECTION_HISTORY_LEN: usize = 1024;
190pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
191#[doc(hidden)]
192pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
193
194pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
195pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
196
197pub fn render_parsed_markdown(
198 element_id: impl Into<ElementId>,
199 parsed: &language::ParsedMarkdown,
200 editor_style: &EditorStyle,
201 workspace: Option<WeakView<Workspace>>,
202 cx: &mut WindowContext,
203) -> InteractiveText {
204 let code_span_background_color = cx
205 .theme()
206 .colors()
207 .editor_document_highlight_read_background;
208
209 let highlights = gpui::combine_highlights(
210 parsed.highlights.iter().filter_map(|(range, highlight)| {
211 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
212 Some((range.clone(), highlight))
213 }),
214 parsed
215 .regions
216 .iter()
217 .zip(&parsed.region_ranges)
218 .filter_map(|(region, range)| {
219 if region.code {
220 Some((
221 range.clone(),
222 HighlightStyle {
223 background_color: Some(code_span_background_color),
224 ..Default::default()
225 },
226 ))
227 } else {
228 None
229 }
230 }),
231 );
232
233 let mut links = Vec::new();
234 let mut link_ranges = Vec::new();
235 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
236 if let Some(link) = region.link.clone() {
237 links.push(link);
238 link_ranges.push(range.clone());
239 }
240 }
241
242 InteractiveText::new(
243 element_id,
244 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
245 )
246 .on_click(link_ranges, move |clicked_range_ix, cx| {
247 match &links[clicked_range_ix] {
248 markdown::Link::Web { url } => cx.open_url(url),
249 markdown::Link::Path { path } => {
250 if let Some(workspace) = &workspace {
251 _ = workspace.update(cx, |workspace, cx| {
252 workspace.open_abs_path(path.clone(), false, cx).detach();
253 });
254 }
255 }
256 }
257 })
258}
259
260#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
261pub(crate) enum InlayId {
262 InlineCompletion(usize),
263 Hint(usize),
264}
265
266impl InlayId {
267 fn id(&self) -> usize {
268 match self {
269 Self::InlineCompletion(id) => *id,
270 Self::Hint(id) => *id,
271 }
272 }
273}
274
275enum DiffRowHighlight {}
276enum DocumentHighlightRead {}
277enum DocumentHighlightWrite {}
278enum InputComposition {}
279
280#[derive(Debug, Copy, Clone, PartialEq, Eq)]
281pub enum Navigated {
282 Yes,
283 No,
284}
285
286impl Navigated {
287 pub fn from_bool(yes: bool) -> Navigated {
288 if yes {
289 Navigated::Yes
290 } else {
291 Navigated::No
292 }
293 }
294}
295
296pub fn init_settings(cx: &mut AppContext) {
297 EditorSettings::register(cx);
298}
299
300pub fn init(cx: &mut AppContext) {
301 init_settings(cx);
302
303 workspace::register_project_item::<Editor>(cx);
304 workspace::FollowableViewRegistry::register::<Editor>(cx);
305 workspace::register_serializable_item::<Editor>(cx);
306
307 cx.observe_new_views(
308 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
309 workspace.register_action(Editor::new_file);
310 workspace.register_action(Editor::new_file_vertical);
311 workspace.register_action(Editor::new_file_horizontal);
312 },
313 )
314 .detach();
315
316 cx.on_action(move |_: &workspace::NewFile, cx| {
317 let app_state = workspace::AppState::global(cx);
318 if let Some(app_state) = app_state.upgrade() {
319 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
320 Editor::new_file(workspace, &Default::default(), cx)
321 })
322 .detach();
323 }
324 });
325 cx.on_action(move |_: &workspace::NewWindow, cx| {
326 let app_state = workspace::AppState::global(cx);
327 if let Some(app_state) = app_state.upgrade() {
328 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
329 Editor::new_file(workspace, &Default::default(), cx)
330 })
331 .detach();
332 }
333 });
334 git::project_diff::init(cx);
335}
336
337pub struct SearchWithinRange;
338
339trait InvalidationRegion {
340 fn ranges(&self) -> &[Range<Anchor>];
341}
342
343#[derive(Clone, Debug, PartialEq)]
344pub enum SelectPhase {
345 Begin {
346 position: DisplayPoint,
347 add: bool,
348 click_count: usize,
349 },
350 BeginColumnar {
351 position: DisplayPoint,
352 reset: bool,
353 goal_column: u32,
354 },
355 Extend {
356 position: DisplayPoint,
357 click_count: usize,
358 },
359 Update {
360 position: DisplayPoint,
361 goal_column: u32,
362 scroll_delta: gpui::Point<f32>,
363 },
364 End,
365}
366
367#[derive(Clone, Debug)]
368pub enum SelectMode {
369 Character,
370 Word(Range<Anchor>),
371 Line(Range<Anchor>),
372 All,
373}
374
375#[derive(Copy, Clone, PartialEq, Eq, Debug)]
376pub enum EditorMode {
377 SingleLine { auto_width: bool },
378 AutoHeight { max_lines: usize },
379 Full,
380}
381
382#[derive(Copy, Clone, Debug)]
383pub enum SoftWrap {
384 /// Prefer not to wrap at all.
385 ///
386 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
387 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
388 GitDiff,
389 /// Prefer a single line generally, unless an overly long line is encountered.
390 None,
391 /// Soft wrap lines that exceed the editor width.
392 EditorWidth,
393 /// Soft wrap lines at the preferred line length.
394 Column(u32),
395 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
396 Bounded(u32),
397}
398
399#[derive(Clone)]
400pub struct EditorStyle {
401 pub background: Hsla,
402 pub local_player: PlayerColor,
403 pub text: TextStyle,
404 pub scrollbar_width: Pixels,
405 pub syntax: Arc<SyntaxTheme>,
406 pub status: StatusColors,
407 pub inlay_hints_style: HighlightStyle,
408 pub inline_completion_styles: InlineCompletionStyles,
409 pub unnecessary_code_fade: f32,
410}
411
412impl Default for EditorStyle {
413 fn default() -> Self {
414 Self {
415 background: Hsla::default(),
416 local_player: PlayerColor::default(),
417 text: TextStyle::default(),
418 scrollbar_width: Pixels::default(),
419 syntax: Default::default(),
420 // HACK: Status colors don't have a real default.
421 // We should look into removing the status colors from the editor
422 // style and retrieve them directly from the theme.
423 status: StatusColors::dark(),
424 inlay_hints_style: HighlightStyle::default(),
425 inline_completion_styles: InlineCompletionStyles {
426 insertion: HighlightStyle::default(),
427 whitespace: HighlightStyle::default(),
428 },
429 unnecessary_code_fade: Default::default(),
430 }
431 }
432}
433
434pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
435 let show_background = language_settings::language_settings(None, None, cx)
436 .inlay_hints
437 .show_background;
438
439 HighlightStyle {
440 color: Some(cx.theme().status().hint),
441 background_color: show_background.then(|| cx.theme().status().hint_background),
442 ..HighlightStyle::default()
443 }
444}
445
446pub fn make_suggestion_styles(cx: &WindowContext) -> InlineCompletionStyles {
447 InlineCompletionStyles {
448 insertion: HighlightStyle {
449 color: Some(cx.theme().status().predictive),
450 ..HighlightStyle::default()
451 },
452 whitespace: HighlightStyle {
453 background_color: Some(cx.theme().status().created_background),
454 ..HighlightStyle::default()
455 },
456 }
457}
458
459type CompletionId = usize;
460
461enum InlineCompletion {
462 Edit(Vec<(Range<Anchor>, String)>),
463 Move(Anchor),
464}
465
466struct InlineCompletionState {
467 inlay_ids: Vec<InlayId>,
468 completion: InlineCompletion,
469 invalidation_range: Range<Anchor>,
470}
471
472enum InlineCompletionHighlight {}
473
474#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
475struct EditorActionId(usize);
476
477impl EditorActionId {
478 pub fn post_inc(&mut self) -> Self {
479 let answer = self.0;
480
481 *self = Self(answer + 1);
482
483 Self(answer)
484 }
485}
486
487// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
488// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
489
490type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
491type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
492
493#[derive(Default)]
494struct ScrollbarMarkerState {
495 scrollbar_size: Size<Pixels>,
496 dirty: bool,
497 markers: Arc<[PaintQuad]>,
498 pending_refresh: Option<Task<Result<()>>>,
499}
500
501impl ScrollbarMarkerState {
502 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
503 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
504 }
505}
506
507#[derive(Clone, Debug)]
508struct RunnableTasks {
509 templates: Vec<(TaskSourceKind, TaskTemplate)>,
510 offset: MultiBufferOffset,
511 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
512 column: u32,
513 // Values of all named captures, including those starting with '_'
514 extra_variables: HashMap<String, String>,
515 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
516 context_range: Range<BufferOffset>,
517}
518
519impl RunnableTasks {
520 fn resolve<'a>(
521 &'a self,
522 cx: &'a task::TaskContext,
523 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
524 self.templates.iter().filter_map(|(kind, template)| {
525 template
526 .resolve_task(&kind.to_id_base(), Default::default(), cx)
527 .map(|task| (kind.clone(), task))
528 })
529 }
530}
531
532#[derive(Clone)]
533struct ResolvedTasks {
534 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
535 position: Anchor,
536}
537#[derive(Copy, Clone, Debug)]
538struct MultiBufferOffset(usize);
539#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
540struct BufferOffset(usize);
541
542// Addons allow storing per-editor state in other crates (e.g. Vim)
543pub trait Addon: 'static {
544 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
545
546 fn to_any(&self) -> &dyn std::any::Any;
547}
548
549#[derive(Debug, Copy, Clone, PartialEq, Eq)]
550pub enum IsVimMode {
551 Yes,
552 No,
553}
554
555/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
556///
557/// See the [module level documentation](self) for more information.
558pub struct Editor {
559 focus_handle: FocusHandle,
560 last_focused_descendant: Option<WeakFocusHandle>,
561 /// The text buffer being edited
562 buffer: Model<MultiBuffer>,
563 /// Map of how text in the buffer should be displayed.
564 /// Handles soft wraps, folds, fake inlay text insertions, etc.
565 pub display_map: Model<DisplayMap>,
566 pub selections: SelectionsCollection,
567 pub scroll_manager: ScrollManager,
568 /// When inline assist editors are linked, they all render cursors because
569 /// typing enters text into each of them, even the ones that aren't focused.
570 pub(crate) show_cursor_when_unfocused: bool,
571 columnar_selection_tail: Option<Anchor>,
572 add_selections_state: Option<AddSelectionsState>,
573 select_next_state: Option<SelectNextState>,
574 select_prev_state: Option<SelectNextState>,
575 selection_history: SelectionHistory,
576 autoclose_regions: Vec<AutocloseRegion>,
577 snippet_stack: InvalidationStack<SnippetState>,
578 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
579 ime_transaction: Option<TransactionId>,
580 active_diagnostics: Option<ActiveDiagnosticGroup>,
581 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
582
583 project: Option<Model<Project>>,
584 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
585 completion_provider: Option<Box<dyn CompletionProvider>>,
586 collaboration_hub: Option<Box<dyn CollaborationHub>>,
587 blink_manager: Model<BlinkManager>,
588 show_cursor_names: bool,
589 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
590 pub show_local_selections: bool,
591 mode: EditorMode,
592 show_breadcrumbs: bool,
593 show_gutter: bool,
594 show_line_numbers: Option<bool>,
595 use_relative_line_numbers: Option<bool>,
596 show_git_diff_gutter: Option<bool>,
597 show_code_actions: Option<bool>,
598 show_runnables: Option<bool>,
599 show_wrap_guides: Option<bool>,
600 show_indent_guides: Option<bool>,
601 placeholder_text: Option<Arc<str>>,
602 highlight_order: usize,
603 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
604 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
605 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
606 scrollbar_marker_state: ScrollbarMarkerState,
607 active_indent_guides_state: ActiveIndentGuidesState,
608 nav_history: Option<ItemNavHistory>,
609 context_menu: RwLock<Option<CodeContextMenu>>,
610 mouse_context_menu: Option<MouseContextMenu>,
611 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
612 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
613 signature_help_state: SignatureHelpState,
614 auto_signature_help: Option<bool>,
615 find_all_references_task_sources: Vec<Anchor>,
616 next_completion_id: CompletionId,
617 available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
618 code_actions_task: Option<Task<Result<()>>>,
619 document_highlights_task: Option<Task<()>>,
620 linked_editing_range_task: Option<Task<Option<()>>>,
621 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
622 pending_rename: Option<RenameState>,
623 searchable: bool,
624 cursor_shape: CursorShape,
625 current_line_highlight: Option<CurrentLineHighlight>,
626 collapse_matches: bool,
627 autoindent_mode: Option<AutoindentMode>,
628 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
629 input_enabled: bool,
630 use_modal_editing: bool,
631 read_only: bool,
632 leader_peer_id: Option<PeerId>,
633 remote_id: Option<ViewId>,
634 hover_state: HoverState,
635 gutter_hovered: bool,
636 hovered_link_state: Option<HoveredLinkState>,
637 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
638 code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
639 active_inline_completion: Option<InlineCompletionState>,
640 // enable_inline_completions is a switch that Vim can use to disable
641 // inline completions based on its mode.
642 enable_inline_completions: bool,
643 show_inline_completions_override: Option<bool>,
644 inlay_hint_cache: InlayHintCache,
645 diff_map: DiffMap,
646 next_inlay_id: usize,
647 _subscriptions: Vec<Subscription>,
648 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
649 gutter_dimensions: GutterDimensions,
650 style: Option<EditorStyle>,
651 text_style_refinement: Option<TextStyleRefinement>,
652 next_editor_action_id: EditorActionId,
653 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
654 use_autoclose: bool,
655 use_auto_surround: bool,
656 auto_replace_emoji_shortcode: bool,
657 show_git_blame_gutter: bool,
658 show_git_blame_inline: bool,
659 show_git_blame_inline_delay_task: Option<Task<()>>,
660 git_blame_inline_enabled: bool,
661 serialize_dirty_buffers: bool,
662 show_selection_menu: Option<bool>,
663 blame: Option<Model<GitBlame>>,
664 blame_subscription: Option<Subscription>,
665 custom_context_menu: Option<
666 Box<
667 dyn 'static
668 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
669 >,
670 >,
671 last_bounds: Option<Bounds<Pixels>>,
672 expect_bounds_change: Option<Bounds<Pixels>>,
673 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
674 tasks_update_task: Option<Task<()>>,
675 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
676 breadcrumb_header: Option<String>,
677 focused_block: Option<FocusedBlock>,
678 next_scroll_position: NextScrollCursorCenterTopBottom,
679 addons: HashMap<TypeId, Box<dyn Addon>>,
680 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
681 toggle_fold_multiple_buffers: Task<()>,
682 _scroll_cursor_center_top_bottom_task: Task<()>,
683}
684
685#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
686enum NextScrollCursorCenterTopBottom {
687 #[default]
688 Center,
689 Top,
690 Bottom,
691}
692
693impl NextScrollCursorCenterTopBottom {
694 fn next(&self) -> Self {
695 match self {
696 Self::Center => Self::Top,
697 Self::Top => Self::Bottom,
698 Self::Bottom => Self::Center,
699 }
700 }
701}
702
703#[derive(Clone)]
704pub struct EditorSnapshot {
705 pub mode: EditorMode,
706 show_gutter: bool,
707 show_line_numbers: Option<bool>,
708 show_git_diff_gutter: Option<bool>,
709 show_code_actions: Option<bool>,
710 show_runnables: Option<bool>,
711 git_blame_gutter_max_author_length: Option<usize>,
712 pub display_snapshot: DisplaySnapshot,
713 pub placeholder_text: Option<Arc<str>>,
714 diff_map: DiffMapSnapshot,
715 is_focused: bool,
716 scroll_anchor: ScrollAnchor,
717 ongoing_scroll: OngoingScroll,
718 current_line_highlight: CurrentLineHighlight,
719 gutter_hovered: bool,
720}
721
722const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
723
724#[derive(Default, Debug, Clone, Copy)]
725pub struct GutterDimensions {
726 pub left_padding: Pixels,
727 pub right_padding: Pixels,
728 pub width: Pixels,
729 pub margin: Pixels,
730 pub git_blame_entries_width: Option<Pixels>,
731}
732
733impl GutterDimensions {
734 /// The full width of the space taken up by the gutter.
735 pub fn full_width(&self) -> Pixels {
736 self.margin + self.width
737 }
738
739 /// The width of the space reserved for the fold indicators,
740 /// use alongside 'justify_end' and `gutter_width` to
741 /// right align content with the line numbers
742 pub fn fold_area_width(&self) -> Pixels {
743 self.margin + self.right_padding
744 }
745}
746
747#[derive(Debug)]
748pub struct RemoteSelection {
749 pub replica_id: ReplicaId,
750 pub selection: Selection<Anchor>,
751 pub cursor_shape: CursorShape,
752 pub peer_id: PeerId,
753 pub line_mode: bool,
754 pub participant_index: Option<ParticipantIndex>,
755 pub user_name: Option<SharedString>,
756}
757
758#[derive(Clone, Debug)]
759struct SelectionHistoryEntry {
760 selections: Arc<[Selection<Anchor>]>,
761 select_next_state: Option<SelectNextState>,
762 select_prev_state: Option<SelectNextState>,
763 add_selections_state: Option<AddSelectionsState>,
764}
765
766enum SelectionHistoryMode {
767 Normal,
768 Undoing,
769 Redoing,
770}
771
772#[derive(Clone, PartialEq, Eq, Hash)]
773struct HoveredCursor {
774 replica_id: u16,
775 selection_id: usize,
776}
777
778impl Default for SelectionHistoryMode {
779 fn default() -> Self {
780 Self::Normal
781 }
782}
783
784#[derive(Default)]
785struct SelectionHistory {
786 #[allow(clippy::type_complexity)]
787 selections_by_transaction:
788 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
789 mode: SelectionHistoryMode,
790 undo_stack: VecDeque<SelectionHistoryEntry>,
791 redo_stack: VecDeque<SelectionHistoryEntry>,
792}
793
794impl SelectionHistory {
795 fn insert_transaction(
796 &mut self,
797 transaction_id: TransactionId,
798 selections: Arc<[Selection<Anchor>]>,
799 ) {
800 self.selections_by_transaction
801 .insert(transaction_id, (selections, None));
802 }
803
804 #[allow(clippy::type_complexity)]
805 fn transaction(
806 &self,
807 transaction_id: TransactionId,
808 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
809 self.selections_by_transaction.get(&transaction_id)
810 }
811
812 #[allow(clippy::type_complexity)]
813 fn transaction_mut(
814 &mut self,
815 transaction_id: TransactionId,
816 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
817 self.selections_by_transaction.get_mut(&transaction_id)
818 }
819
820 fn push(&mut self, entry: SelectionHistoryEntry) {
821 if !entry.selections.is_empty() {
822 match self.mode {
823 SelectionHistoryMode::Normal => {
824 self.push_undo(entry);
825 self.redo_stack.clear();
826 }
827 SelectionHistoryMode::Undoing => self.push_redo(entry),
828 SelectionHistoryMode::Redoing => self.push_undo(entry),
829 }
830 }
831 }
832
833 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
834 if self
835 .undo_stack
836 .back()
837 .map_or(true, |e| e.selections != entry.selections)
838 {
839 self.undo_stack.push_back(entry);
840 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
841 self.undo_stack.pop_front();
842 }
843 }
844 }
845
846 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
847 if self
848 .redo_stack
849 .back()
850 .map_or(true, |e| e.selections != entry.selections)
851 {
852 self.redo_stack.push_back(entry);
853 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
854 self.redo_stack.pop_front();
855 }
856 }
857 }
858}
859
860struct RowHighlight {
861 index: usize,
862 range: Range<Anchor>,
863 color: Hsla,
864 should_autoscroll: bool,
865}
866
867#[derive(Clone, Debug)]
868struct AddSelectionsState {
869 above: bool,
870 stack: Vec<usize>,
871}
872
873#[derive(Clone)]
874struct SelectNextState {
875 query: AhoCorasick,
876 wordwise: bool,
877 done: bool,
878}
879
880impl std::fmt::Debug for SelectNextState {
881 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
882 f.debug_struct(std::any::type_name::<Self>())
883 .field("wordwise", &self.wordwise)
884 .field("done", &self.done)
885 .finish()
886 }
887}
888
889#[derive(Debug)]
890struct AutocloseRegion {
891 selection_id: usize,
892 range: Range<Anchor>,
893 pair: BracketPair,
894}
895
896#[derive(Debug)]
897struct SnippetState {
898 ranges: Vec<Vec<Range<Anchor>>>,
899 active_index: usize,
900 choices: Vec<Option<Vec<String>>>,
901}
902
903#[doc(hidden)]
904pub struct RenameState {
905 pub range: Range<Anchor>,
906 pub old_name: Arc<str>,
907 pub editor: View<Editor>,
908 block_id: CustomBlockId,
909}
910
911struct InvalidationStack<T>(Vec<T>);
912
913struct RegisteredInlineCompletionProvider {
914 provider: Arc<dyn InlineCompletionProviderHandle>,
915 _subscription: Subscription,
916}
917
918#[derive(Debug)]
919struct ActiveDiagnosticGroup {
920 primary_range: Range<Anchor>,
921 primary_message: String,
922 group_id: usize,
923 blocks: HashMap<CustomBlockId, Diagnostic>,
924 is_valid: bool,
925}
926
927#[derive(Serialize, Deserialize, Clone, Debug)]
928pub struct ClipboardSelection {
929 pub len: usize,
930 pub is_entire_line: bool,
931 pub first_line_indent: u32,
932}
933
934#[derive(Debug)]
935pub(crate) struct NavigationData {
936 cursor_anchor: Anchor,
937 cursor_position: Point,
938 scroll_anchor: ScrollAnchor,
939 scroll_top_row: u32,
940}
941
942#[derive(Debug, Clone, Copy, PartialEq, Eq)]
943pub enum GotoDefinitionKind {
944 Symbol,
945 Declaration,
946 Type,
947 Implementation,
948}
949
950#[derive(Debug, Clone)]
951enum InlayHintRefreshReason {
952 Toggle(bool),
953 SettingsChange(InlayHintSettings),
954 NewLinesShown,
955 BufferEdited(HashSet<Arc<Language>>),
956 RefreshRequested,
957 ExcerptsRemoved(Vec<ExcerptId>),
958}
959
960impl InlayHintRefreshReason {
961 fn description(&self) -> &'static str {
962 match self {
963 Self::Toggle(_) => "toggle",
964 Self::SettingsChange(_) => "settings change",
965 Self::NewLinesShown => "new lines shown",
966 Self::BufferEdited(_) => "buffer edited",
967 Self::RefreshRequested => "refresh requested",
968 Self::ExcerptsRemoved(_) => "excerpts removed",
969 }
970 }
971}
972
973pub(crate) struct FocusedBlock {
974 id: BlockId,
975 focus_handle: WeakFocusHandle,
976}
977
978#[derive(Clone)]
979struct JumpData {
980 excerpt_id: ExcerptId,
981 position: Point,
982 anchor: text::Anchor,
983 path: Option<project::ProjectPath>,
984 line_offset_from_top: u32,
985}
986
987impl Editor {
988 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
989 let buffer = cx.new_model(|cx| Buffer::local("", cx));
990 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
991 Self::new(
992 EditorMode::SingleLine { auto_width: false },
993 buffer,
994 None,
995 false,
996 cx,
997 )
998 }
999
1000 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1001 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1002 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1003 Self::new(EditorMode::Full, buffer, None, false, cx)
1004 }
1005
1006 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1007 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1008 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1009 Self::new(
1010 EditorMode::SingleLine { auto_width: true },
1011 buffer,
1012 None,
1013 false,
1014 cx,
1015 )
1016 }
1017
1018 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1019 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1020 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1021 Self::new(
1022 EditorMode::AutoHeight { max_lines },
1023 buffer,
1024 None,
1025 false,
1026 cx,
1027 )
1028 }
1029
1030 pub fn for_buffer(
1031 buffer: Model<Buffer>,
1032 project: Option<Model<Project>>,
1033 cx: &mut ViewContext<Self>,
1034 ) -> Self {
1035 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1036 Self::new(EditorMode::Full, buffer, project, false, cx)
1037 }
1038
1039 pub fn for_multibuffer(
1040 buffer: Model<MultiBuffer>,
1041 project: Option<Model<Project>>,
1042 show_excerpt_controls: bool,
1043 cx: &mut ViewContext<Self>,
1044 ) -> Self {
1045 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1046 }
1047
1048 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1049 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1050 let mut clone = Self::new(
1051 self.mode,
1052 self.buffer.clone(),
1053 self.project.clone(),
1054 show_excerpt_controls,
1055 cx,
1056 );
1057 self.display_map.update(cx, |display_map, cx| {
1058 let snapshot = display_map.snapshot(cx);
1059 clone.display_map.update(cx, |display_map, cx| {
1060 display_map.set_state(&snapshot, cx);
1061 });
1062 });
1063 clone.selections.clone_state(&self.selections);
1064 clone.scroll_manager.clone_state(&self.scroll_manager);
1065 clone.searchable = self.searchable;
1066 clone
1067 }
1068
1069 pub fn new(
1070 mode: EditorMode,
1071 buffer: Model<MultiBuffer>,
1072 project: Option<Model<Project>>,
1073 show_excerpt_controls: bool,
1074 cx: &mut ViewContext<Self>,
1075 ) -> Self {
1076 let style = cx.text_style();
1077 let font_size = style.font_size.to_pixels(cx.rem_size());
1078 let editor = cx.view().downgrade();
1079 let fold_placeholder = FoldPlaceholder {
1080 constrain_width: true,
1081 render: Arc::new(move |fold_id, fold_range, cx| {
1082 let editor = editor.clone();
1083 div()
1084 .id(fold_id)
1085 .bg(cx.theme().colors().ghost_element_background)
1086 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1087 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1088 .rounded_sm()
1089 .size_full()
1090 .cursor_pointer()
1091 .child("⋯")
1092 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1093 .on_click(move |_, cx| {
1094 editor
1095 .update(cx, |editor, cx| {
1096 editor.unfold_ranges(
1097 &[fold_range.start..fold_range.end],
1098 true,
1099 false,
1100 cx,
1101 );
1102 cx.stop_propagation();
1103 })
1104 .ok();
1105 })
1106 .into_any()
1107 }),
1108 merge_adjacent: true,
1109 ..Default::default()
1110 };
1111 let display_map = cx.new_model(|cx| {
1112 DisplayMap::new(
1113 buffer.clone(),
1114 style.font(),
1115 font_size,
1116 None,
1117 show_excerpt_controls,
1118 FILE_HEADER_HEIGHT,
1119 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1120 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1121 fold_placeholder,
1122 cx,
1123 )
1124 });
1125
1126 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1127
1128 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1129
1130 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1131 .then(|| language_settings::SoftWrap::None);
1132
1133 let mut project_subscriptions = Vec::new();
1134 if mode == EditorMode::Full {
1135 if let Some(project) = project.as_ref() {
1136 if buffer.read(cx).is_singleton() {
1137 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1138 cx.emit(EditorEvent::TitleChanged);
1139 }));
1140 }
1141 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1142 if let project::Event::RefreshInlayHints = event {
1143 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1144 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1145 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1146 let focus_handle = editor.focus_handle(cx);
1147 if focus_handle.is_focused(cx) {
1148 let snapshot = buffer.read(cx).snapshot();
1149 for (range, snippet) in snippet_edits {
1150 let editor_range =
1151 language::range_from_lsp(*range).to_offset(&snapshot);
1152 editor
1153 .insert_snippet(&[editor_range], snippet.clone(), cx)
1154 .ok();
1155 }
1156 }
1157 }
1158 }
1159 }));
1160 if let Some(task_inventory) = project
1161 .read(cx)
1162 .task_store()
1163 .read(cx)
1164 .task_inventory()
1165 .cloned()
1166 {
1167 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1168 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1169 }));
1170 }
1171 }
1172 }
1173
1174 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1175
1176 let inlay_hint_settings =
1177 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1178 let focus_handle = cx.focus_handle();
1179 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1180 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1181 .detach();
1182 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1183 .detach();
1184 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1185
1186 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1187 Some(false)
1188 } else {
1189 None
1190 };
1191
1192 let mut code_action_providers = Vec::new();
1193 if let Some(project) = project.clone() {
1194 get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
1195 code_action_providers.push(Arc::new(project) as Arc<_>);
1196 }
1197
1198 let mut this = Self {
1199 focus_handle,
1200 show_cursor_when_unfocused: false,
1201 last_focused_descendant: None,
1202 buffer: buffer.clone(),
1203 display_map: display_map.clone(),
1204 selections,
1205 scroll_manager: ScrollManager::new(cx),
1206 columnar_selection_tail: None,
1207 add_selections_state: None,
1208 select_next_state: None,
1209 select_prev_state: None,
1210 selection_history: Default::default(),
1211 autoclose_regions: Default::default(),
1212 snippet_stack: Default::default(),
1213 select_larger_syntax_node_stack: Vec::new(),
1214 ime_transaction: Default::default(),
1215 active_diagnostics: None,
1216 soft_wrap_mode_override,
1217 completion_provider: project.clone().map(|project| Box::new(project) as _),
1218 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1219 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1220 project,
1221 blink_manager: blink_manager.clone(),
1222 show_local_selections: true,
1223 mode,
1224 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1225 show_gutter: mode == EditorMode::Full,
1226 show_line_numbers: None,
1227 use_relative_line_numbers: None,
1228 show_git_diff_gutter: None,
1229 show_code_actions: None,
1230 show_runnables: None,
1231 show_wrap_guides: None,
1232 show_indent_guides,
1233 placeholder_text: None,
1234 highlight_order: 0,
1235 highlighted_rows: HashMap::default(),
1236 background_highlights: Default::default(),
1237 gutter_highlights: TreeMap::default(),
1238 scrollbar_marker_state: ScrollbarMarkerState::default(),
1239 active_indent_guides_state: ActiveIndentGuidesState::default(),
1240 nav_history: None,
1241 context_menu: RwLock::new(None),
1242 mouse_context_menu: None,
1243 hunk_controls_menu_handle: PopoverMenuHandle::default(),
1244 completion_tasks: Default::default(),
1245 signature_help_state: SignatureHelpState::default(),
1246 auto_signature_help: None,
1247 find_all_references_task_sources: Vec::new(),
1248 next_completion_id: 0,
1249 next_inlay_id: 0,
1250 code_action_providers,
1251 available_code_actions: Default::default(),
1252 code_actions_task: Default::default(),
1253 document_highlights_task: Default::default(),
1254 linked_editing_range_task: Default::default(),
1255 pending_rename: Default::default(),
1256 searchable: true,
1257 cursor_shape: EditorSettings::get_global(cx)
1258 .cursor_shape
1259 .unwrap_or_default(),
1260 current_line_highlight: None,
1261 autoindent_mode: Some(AutoindentMode::EachLine),
1262 collapse_matches: false,
1263 workspace: None,
1264 input_enabled: true,
1265 use_modal_editing: mode == EditorMode::Full,
1266 read_only: false,
1267 use_autoclose: true,
1268 use_auto_surround: true,
1269 auto_replace_emoji_shortcode: false,
1270 leader_peer_id: None,
1271 remote_id: None,
1272 hover_state: Default::default(),
1273 hovered_link_state: Default::default(),
1274 inline_completion_provider: None,
1275 active_inline_completion: None,
1276 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1277 diff_map: DiffMap::default(),
1278 gutter_hovered: false,
1279 pixel_position_of_newest_cursor: None,
1280 last_bounds: None,
1281 expect_bounds_change: None,
1282 gutter_dimensions: GutterDimensions::default(),
1283 style: None,
1284 show_cursor_names: false,
1285 hovered_cursors: Default::default(),
1286 next_editor_action_id: EditorActionId::default(),
1287 editor_actions: Rc::default(),
1288 show_inline_completions_override: None,
1289 enable_inline_completions: true,
1290 custom_context_menu: None,
1291 show_git_blame_gutter: false,
1292 show_git_blame_inline: false,
1293 show_selection_menu: None,
1294 show_git_blame_inline_delay_task: None,
1295 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1296 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1297 .session
1298 .restore_unsaved_buffers,
1299 blame: None,
1300 blame_subscription: None,
1301 tasks: Default::default(),
1302 _subscriptions: vec![
1303 cx.observe(&buffer, Self::on_buffer_changed),
1304 cx.subscribe(&buffer, Self::on_buffer_event),
1305 cx.observe(&display_map, Self::on_display_map_changed),
1306 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1307 cx.observe_global::<SettingsStore>(Self::settings_changed),
1308 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1309 cx.observe_window_activation(|editor, cx| {
1310 let active = cx.is_window_active();
1311 editor.blink_manager.update(cx, |blink_manager, cx| {
1312 if active {
1313 blink_manager.enable(cx);
1314 } else {
1315 blink_manager.disable(cx);
1316 }
1317 });
1318 }),
1319 ],
1320 tasks_update_task: None,
1321 linked_edit_ranges: Default::default(),
1322 previous_search_ranges: None,
1323 breadcrumb_header: None,
1324 focused_block: None,
1325 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1326 addons: HashMap::default(),
1327 registered_buffers: HashMap::default(),
1328 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1329 toggle_fold_multiple_buffers: Task::ready(()),
1330 text_style_refinement: None,
1331 };
1332 this.tasks_update_task = Some(this.refresh_runnables(cx));
1333 this._subscriptions.extend(project_subscriptions);
1334
1335 this.end_selection(cx);
1336 this.scroll_manager.show_scrollbar(cx);
1337
1338 if mode == EditorMode::Full {
1339 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1340 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1341
1342 if this.git_blame_inline_enabled {
1343 this.git_blame_inline_enabled = true;
1344 this.start_git_blame_inline(false, cx);
1345 }
1346
1347 if let Some(buffer) = buffer.read(cx).as_singleton() {
1348 if let Some(project) = this.project.as_ref() {
1349 let lsp_store = project.read(cx).lsp_store();
1350 let handle = lsp_store.update(cx, |lsp_store, cx| {
1351 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1352 });
1353 this.registered_buffers
1354 .insert(buffer.read(cx).remote_id(), handle);
1355 }
1356 }
1357 }
1358
1359 this.report_editor_event("open", None, cx);
1360 this
1361 }
1362
1363 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
1364 self.mouse_context_menu
1365 .as_ref()
1366 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1367 }
1368
1369 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
1370 let mut key_context = KeyContext::new_with_defaults();
1371 key_context.add("Editor");
1372 let mode = match self.mode {
1373 EditorMode::SingleLine { .. } => "single_line",
1374 EditorMode::AutoHeight { .. } => "auto_height",
1375 EditorMode::Full => "full",
1376 };
1377
1378 if EditorSettings::jupyter_enabled(cx) {
1379 key_context.add("jupyter");
1380 }
1381
1382 key_context.set("mode", mode);
1383 if self.pending_rename.is_some() {
1384 key_context.add("renaming");
1385 }
1386 if self.context_menu_visible() {
1387 match self.context_menu.read().as_ref() {
1388 Some(CodeContextMenu::Completions(_)) => {
1389 key_context.add("menu");
1390 key_context.add("showing_completions")
1391 }
1392 Some(CodeContextMenu::CodeActions(_)) => {
1393 key_context.add("menu");
1394 key_context.add("showing_code_actions")
1395 }
1396 None => {}
1397 }
1398 }
1399
1400 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1401 if !self.focus_handle(cx).contains_focused(cx)
1402 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
1403 {
1404 for addon in self.addons.values() {
1405 addon.extend_key_context(&mut key_context, cx)
1406 }
1407 }
1408
1409 if let Some(extension) = self
1410 .buffer
1411 .read(cx)
1412 .as_singleton()
1413 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1414 {
1415 key_context.set("extension", extension.to_string());
1416 }
1417
1418 if self.has_active_inline_completion() {
1419 key_context.add("copilot_suggestion");
1420 key_context.add("inline_completion");
1421 }
1422
1423 if !self
1424 .selections
1425 .disjoint
1426 .iter()
1427 .all(|selection| selection.start == selection.end)
1428 {
1429 key_context.add("selection");
1430 }
1431
1432 key_context
1433 }
1434
1435 pub fn new_file(
1436 workspace: &mut Workspace,
1437 _: &workspace::NewFile,
1438 cx: &mut ViewContext<Workspace>,
1439 ) {
1440 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
1441 "Failed to create buffer",
1442 cx,
1443 |e, _| match e.error_code() {
1444 ErrorCode::RemoteUpgradeRequired => Some(format!(
1445 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1446 e.error_tag("required").unwrap_or("the latest version")
1447 )),
1448 _ => None,
1449 },
1450 );
1451 }
1452
1453 pub fn new_in_workspace(
1454 workspace: &mut Workspace,
1455 cx: &mut ViewContext<Workspace>,
1456 ) -> Task<Result<View<Editor>>> {
1457 let project = workspace.project().clone();
1458 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1459
1460 cx.spawn(|workspace, mut cx| async move {
1461 let buffer = create.await?;
1462 workspace.update(&mut cx, |workspace, cx| {
1463 let editor =
1464 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
1465 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
1466 editor
1467 })
1468 })
1469 }
1470
1471 fn new_file_vertical(
1472 workspace: &mut Workspace,
1473 _: &workspace::NewFileSplitVertical,
1474 cx: &mut ViewContext<Workspace>,
1475 ) {
1476 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
1477 }
1478
1479 fn new_file_horizontal(
1480 workspace: &mut Workspace,
1481 _: &workspace::NewFileSplitHorizontal,
1482 cx: &mut ViewContext<Workspace>,
1483 ) {
1484 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
1485 }
1486
1487 fn new_file_in_direction(
1488 workspace: &mut Workspace,
1489 direction: SplitDirection,
1490 cx: &mut ViewContext<Workspace>,
1491 ) {
1492 let project = workspace.project().clone();
1493 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1494
1495 cx.spawn(|workspace, mut cx| async move {
1496 let buffer = create.await?;
1497 workspace.update(&mut cx, move |workspace, cx| {
1498 workspace.split_item(
1499 direction,
1500 Box::new(
1501 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
1502 ),
1503 cx,
1504 )
1505 })?;
1506 anyhow::Ok(())
1507 })
1508 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
1509 ErrorCode::RemoteUpgradeRequired => Some(format!(
1510 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1511 e.error_tag("required").unwrap_or("the latest version")
1512 )),
1513 _ => None,
1514 });
1515 }
1516
1517 pub fn leader_peer_id(&self) -> Option<PeerId> {
1518 self.leader_peer_id
1519 }
1520
1521 pub fn buffer(&self) -> &Model<MultiBuffer> {
1522 &self.buffer
1523 }
1524
1525 pub fn workspace(&self) -> Option<View<Workspace>> {
1526 self.workspace.as_ref()?.0.upgrade()
1527 }
1528
1529 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
1530 self.buffer().read(cx).title(cx)
1531 }
1532
1533 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
1534 let git_blame_gutter_max_author_length = self
1535 .render_git_blame_gutter(cx)
1536 .then(|| {
1537 if let Some(blame) = self.blame.as_ref() {
1538 let max_author_length =
1539 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1540 Some(max_author_length)
1541 } else {
1542 None
1543 }
1544 })
1545 .flatten();
1546
1547 EditorSnapshot {
1548 mode: self.mode,
1549 show_gutter: self.show_gutter,
1550 show_line_numbers: self.show_line_numbers,
1551 show_git_diff_gutter: self.show_git_diff_gutter,
1552 show_code_actions: self.show_code_actions,
1553 show_runnables: self.show_runnables,
1554 git_blame_gutter_max_author_length,
1555 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1556 scroll_anchor: self.scroll_manager.anchor(),
1557 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1558 placeholder_text: self.placeholder_text.clone(),
1559 diff_map: self.diff_map.snapshot(),
1560 is_focused: self.focus_handle.is_focused(cx),
1561 current_line_highlight: self
1562 .current_line_highlight
1563 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1564 gutter_hovered: self.gutter_hovered,
1565 }
1566 }
1567
1568 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
1569 self.buffer.read(cx).language_at(point, cx)
1570 }
1571
1572 pub fn file_at<T: ToOffset>(
1573 &self,
1574 point: T,
1575 cx: &AppContext,
1576 ) -> Option<Arc<dyn language::File>> {
1577 self.buffer.read(cx).read(cx).file_at(point).cloned()
1578 }
1579
1580 pub fn active_excerpt(
1581 &self,
1582 cx: &AppContext,
1583 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
1584 self.buffer
1585 .read(cx)
1586 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1587 }
1588
1589 pub fn mode(&self) -> EditorMode {
1590 self.mode
1591 }
1592
1593 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1594 self.collaboration_hub.as_deref()
1595 }
1596
1597 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1598 self.collaboration_hub = Some(hub);
1599 }
1600
1601 pub fn set_custom_context_menu(
1602 &mut self,
1603 f: impl 'static
1604 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
1605 ) {
1606 self.custom_context_menu = Some(Box::new(f))
1607 }
1608
1609 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1610 self.completion_provider = provider;
1611 }
1612
1613 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1614 self.semantics_provider.clone()
1615 }
1616
1617 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1618 self.semantics_provider = provider;
1619 }
1620
1621 pub fn set_inline_completion_provider<T>(
1622 &mut self,
1623 provider: Option<Model<T>>,
1624 cx: &mut ViewContext<Self>,
1625 ) where
1626 T: InlineCompletionProvider,
1627 {
1628 self.inline_completion_provider =
1629 provider.map(|provider| RegisteredInlineCompletionProvider {
1630 _subscription: cx.observe(&provider, |this, _, cx| {
1631 if this.focus_handle.is_focused(cx) {
1632 this.update_visible_inline_completion(cx);
1633 }
1634 }),
1635 provider: Arc::new(provider),
1636 });
1637 self.refresh_inline_completion(false, false, cx);
1638 }
1639
1640 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
1641 self.placeholder_text.as_deref()
1642 }
1643
1644 pub fn set_placeholder_text(
1645 &mut self,
1646 placeholder_text: impl Into<Arc<str>>,
1647 cx: &mut ViewContext<Self>,
1648 ) {
1649 let placeholder_text = Some(placeholder_text.into());
1650 if self.placeholder_text != placeholder_text {
1651 self.placeholder_text = placeholder_text;
1652 cx.notify();
1653 }
1654 }
1655
1656 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
1657 self.cursor_shape = cursor_shape;
1658
1659 // Disrupt blink for immediate user feedback that the cursor shape has changed
1660 self.blink_manager.update(cx, BlinkManager::show_cursor);
1661
1662 cx.notify();
1663 }
1664
1665 pub fn set_current_line_highlight(
1666 &mut self,
1667 current_line_highlight: Option<CurrentLineHighlight>,
1668 ) {
1669 self.current_line_highlight = current_line_highlight;
1670 }
1671
1672 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1673 self.collapse_matches = collapse_matches;
1674 }
1675
1676 pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
1677 let buffers = self.buffer.read(cx).all_buffers();
1678 let Some(lsp_store) = self.lsp_store(cx) else {
1679 return;
1680 };
1681 lsp_store.update(cx, |lsp_store, cx| {
1682 for buffer in buffers {
1683 self.registered_buffers
1684 .entry(buffer.read(cx).remote_id())
1685 .or_insert_with(|| {
1686 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1687 });
1688 }
1689 })
1690 }
1691
1692 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1693 if self.collapse_matches {
1694 return range.start..range.start;
1695 }
1696 range.clone()
1697 }
1698
1699 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
1700 if self.display_map.read(cx).clip_at_line_ends != clip {
1701 self.display_map
1702 .update(cx, |map, _| map.clip_at_line_ends = clip);
1703 }
1704 }
1705
1706 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1707 self.input_enabled = input_enabled;
1708 }
1709
1710 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
1711 self.enable_inline_completions = enabled;
1712 }
1713
1714 pub fn set_autoindent(&mut self, autoindent: bool) {
1715 if autoindent {
1716 self.autoindent_mode = Some(AutoindentMode::EachLine);
1717 } else {
1718 self.autoindent_mode = None;
1719 }
1720 }
1721
1722 pub fn read_only(&self, cx: &AppContext) -> bool {
1723 self.read_only || self.buffer.read(cx).read_only()
1724 }
1725
1726 pub fn set_read_only(&mut self, read_only: bool) {
1727 self.read_only = read_only;
1728 }
1729
1730 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1731 self.use_autoclose = autoclose;
1732 }
1733
1734 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1735 self.use_auto_surround = auto_surround;
1736 }
1737
1738 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1739 self.auto_replace_emoji_shortcode = auto_replace;
1740 }
1741
1742 pub fn toggle_inline_completions(
1743 &mut self,
1744 _: &ToggleInlineCompletions,
1745 cx: &mut ViewContext<Self>,
1746 ) {
1747 if self.show_inline_completions_override.is_some() {
1748 self.set_show_inline_completions(None, cx);
1749 } else {
1750 let cursor = self.selections.newest_anchor().head();
1751 if let Some((buffer, cursor_buffer_position)) =
1752 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1753 {
1754 let show_inline_completions =
1755 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
1756 self.set_show_inline_completions(Some(show_inline_completions), cx);
1757 }
1758 }
1759 }
1760
1761 pub fn set_show_inline_completions(
1762 &mut self,
1763 show_inline_completions: Option<bool>,
1764 cx: &mut ViewContext<Self>,
1765 ) {
1766 self.show_inline_completions_override = show_inline_completions;
1767 self.refresh_inline_completion(false, true, cx);
1768 }
1769
1770 fn should_show_inline_completions(
1771 &self,
1772 buffer: &Model<Buffer>,
1773 buffer_position: language::Anchor,
1774 cx: &AppContext,
1775 ) -> bool {
1776 if !self.snippet_stack.is_empty() {
1777 return false;
1778 }
1779
1780 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
1781 return false;
1782 }
1783
1784 if let Some(provider) = self.inline_completion_provider() {
1785 if let Some(show_inline_completions) = self.show_inline_completions_override {
1786 show_inline_completions
1787 } else {
1788 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
1789 }
1790 } else {
1791 false
1792 }
1793 }
1794
1795 fn inline_completions_disabled_in_scope(
1796 &self,
1797 buffer: &Model<Buffer>,
1798 buffer_position: language::Anchor,
1799 cx: &AppContext,
1800 ) -> bool {
1801 let snapshot = buffer.read(cx).snapshot();
1802 let settings = snapshot.settings_at(buffer_position, cx);
1803
1804 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1805 return false;
1806 };
1807
1808 scope.override_name().map_or(false, |scope_name| {
1809 settings
1810 .inline_completions_disabled_in
1811 .iter()
1812 .any(|s| s == scope_name)
1813 })
1814 }
1815
1816 pub fn set_use_modal_editing(&mut self, to: bool) {
1817 self.use_modal_editing = to;
1818 }
1819
1820 pub fn use_modal_editing(&self) -> bool {
1821 self.use_modal_editing
1822 }
1823
1824 fn selections_did_change(
1825 &mut self,
1826 local: bool,
1827 old_cursor_position: &Anchor,
1828 show_completions: bool,
1829 cx: &mut ViewContext<Self>,
1830 ) {
1831 cx.invalidate_character_coordinates();
1832
1833 // Copy selections to primary selection buffer
1834 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1835 if local {
1836 let selections = self.selections.all::<usize>(cx);
1837 let buffer_handle = self.buffer.read(cx).read(cx);
1838
1839 let mut text = String::new();
1840 for (index, selection) in selections.iter().enumerate() {
1841 let text_for_selection = buffer_handle
1842 .text_for_range(selection.start..selection.end)
1843 .collect::<String>();
1844
1845 text.push_str(&text_for_selection);
1846 if index != selections.len() - 1 {
1847 text.push('\n');
1848 }
1849 }
1850
1851 if !text.is_empty() {
1852 cx.write_to_primary(ClipboardItem::new_string(text));
1853 }
1854 }
1855
1856 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
1857 self.buffer.update(cx, |buffer, cx| {
1858 buffer.set_active_selections(
1859 &self.selections.disjoint_anchors(),
1860 self.selections.line_mode,
1861 self.cursor_shape,
1862 cx,
1863 )
1864 });
1865 }
1866 let display_map = self
1867 .display_map
1868 .update(cx, |display_map, cx| display_map.snapshot(cx));
1869 let buffer = &display_map.buffer_snapshot;
1870 self.add_selections_state = None;
1871 self.select_next_state = None;
1872 self.select_prev_state = None;
1873 self.select_larger_syntax_node_stack.clear();
1874 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
1875 self.snippet_stack
1876 .invalidate(&self.selections.disjoint_anchors(), buffer);
1877 self.take_rename(false, cx);
1878
1879 let new_cursor_position = self.selections.newest_anchor().head();
1880
1881 self.push_to_nav_history(
1882 *old_cursor_position,
1883 Some(new_cursor_position.to_point(buffer)),
1884 cx,
1885 );
1886
1887 if local {
1888 let new_cursor_position = self.selections.newest_anchor().head();
1889 let mut context_menu = self.context_menu.write();
1890 let completion_menu = match context_menu.as_ref() {
1891 Some(CodeContextMenu::Completions(menu)) => Some(menu),
1892
1893 _ => {
1894 *context_menu = None;
1895 None
1896 }
1897 };
1898
1899 if let Some(completion_menu) = completion_menu {
1900 let cursor_position = new_cursor_position.to_offset(buffer);
1901 let (word_range, kind) =
1902 buffer.surrounding_word(completion_menu.initial_position, true);
1903 if kind == Some(CharKind::Word)
1904 && word_range.to_inclusive().contains(&cursor_position)
1905 {
1906 let mut completion_menu = completion_menu.clone();
1907 drop(context_menu);
1908
1909 let query = Self::completion_query(buffer, cursor_position);
1910 cx.spawn(move |this, mut cx| async move {
1911 completion_menu
1912 .filter(query.as_deref(), cx.background_executor().clone())
1913 .await;
1914
1915 this.update(&mut cx, |this, cx| {
1916 let mut context_menu = this.context_menu.write();
1917 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
1918 else {
1919 return;
1920 };
1921
1922 if menu.id > completion_menu.id {
1923 return;
1924 }
1925
1926 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
1927 drop(context_menu);
1928 cx.notify();
1929 })
1930 })
1931 .detach();
1932
1933 if show_completions {
1934 self.show_completions(&ShowCompletions { trigger: None }, cx);
1935 }
1936 } else {
1937 drop(context_menu);
1938 self.hide_context_menu(cx);
1939 }
1940 } else {
1941 drop(context_menu);
1942 }
1943
1944 hide_hover(self, cx);
1945
1946 if old_cursor_position.to_display_point(&display_map).row()
1947 != new_cursor_position.to_display_point(&display_map).row()
1948 {
1949 self.available_code_actions.take();
1950 }
1951 self.refresh_code_actions(cx);
1952 self.refresh_document_highlights(cx);
1953 refresh_matching_bracket_highlights(self, cx);
1954 self.update_visible_inline_completion(cx);
1955 linked_editing_ranges::refresh_linked_ranges(self, cx);
1956 if self.git_blame_inline_enabled {
1957 self.start_inline_blame_timer(cx);
1958 }
1959 }
1960
1961 self.blink_manager.update(cx, BlinkManager::pause_blinking);
1962 cx.emit(EditorEvent::SelectionsChanged { local });
1963
1964 if self.selections.disjoint_anchors().len() == 1 {
1965 cx.emit(SearchEvent::ActiveMatchChanged)
1966 }
1967 cx.notify();
1968 }
1969
1970 pub fn change_selections<R>(
1971 &mut self,
1972 autoscroll: Option<Autoscroll>,
1973 cx: &mut ViewContext<Self>,
1974 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
1975 ) -> R {
1976 self.change_selections_inner(autoscroll, true, cx, change)
1977 }
1978
1979 pub fn change_selections_inner<R>(
1980 &mut self,
1981 autoscroll: Option<Autoscroll>,
1982 request_completions: bool,
1983 cx: &mut ViewContext<Self>,
1984 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
1985 ) -> R {
1986 let old_cursor_position = self.selections.newest_anchor().head();
1987 self.push_to_selection_history();
1988
1989 let (changed, result) = self.selections.change_with(cx, change);
1990
1991 if changed {
1992 if let Some(autoscroll) = autoscroll {
1993 self.request_autoscroll(autoscroll, cx);
1994 }
1995 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
1996
1997 if self.should_open_signature_help_automatically(
1998 &old_cursor_position,
1999 self.signature_help_state.backspace_pressed(),
2000 cx,
2001 ) {
2002 self.show_signature_help(&ShowSignatureHelp, cx);
2003 }
2004 self.signature_help_state.set_backspace_pressed(false);
2005 }
2006
2007 result
2008 }
2009
2010 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2011 where
2012 I: IntoIterator<Item = (Range<S>, T)>,
2013 S: ToOffset,
2014 T: Into<Arc<str>>,
2015 {
2016 if self.read_only(cx) {
2017 return;
2018 }
2019
2020 self.buffer
2021 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2022 }
2023
2024 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2025 where
2026 I: IntoIterator<Item = (Range<S>, T)>,
2027 S: ToOffset,
2028 T: Into<Arc<str>>,
2029 {
2030 if self.read_only(cx) {
2031 return;
2032 }
2033
2034 self.buffer.update(cx, |buffer, cx| {
2035 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2036 });
2037 }
2038
2039 pub fn edit_with_block_indent<I, S, T>(
2040 &mut self,
2041 edits: I,
2042 original_indent_columns: Vec<u32>,
2043 cx: &mut ViewContext<Self>,
2044 ) where
2045 I: IntoIterator<Item = (Range<S>, T)>,
2046 S: ToOffset,
2047 T: Into<Arc<str>>,
2048 {
2049 if self.read_only(cx) {
2050 return;
2051 }
2052
2053 self.buffer.update(cx, |buffer, cx| {
2054 buffer.edit(
2055 edits,
2056 Some(AutoindentMode::Block {
2057 original_indent_columns,
2058 }),
2059 cx,
2060 )
2061 });
2062 }
2063
2064 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2065 self.hide_context_menu(cx);
2066
2067 match phase {
2068 SelectPhase::Begin {
2069 position,
2070 add,
2071 click_count,
2072 } => self.begin_selection(position, add, click_count, cx),
2073 SelectPhase::BeginColumnar {
2074 position,
2075 goal_column,
2076 reset,
2077 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2078 SelectPhase::Extend {
2079 position,
2080 click_count,
2081 } => self.extend_selection(position, click_count, cx),
2082 SelectPhase::Update {
2083 position,
2084 goal_column,
2085 scroll_delta,
2086 } => self.update_selection(position, goal_column, scroll_delta, cx),
2087 SelectPhase::End => self.end_selection(cx),
2088 }
2089 }
2090
2091 fn extend_selection(
2092 &mut self,
2093 position: DisplayPoint,
2094 click_count: usize,
2095 cx: &mut ViewContext<Self>,
2096 ) {
2097 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2098 let tail = self.selections.newest::<usize>(cx).tail();
2099 self.begin_selection(position, false, click_count, cx);
2100
2101 let position = position.to_offset(&display_map, Bias::Left);
2102 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2103
2104 let mut pending_selection = self
2105 .selections
2106 .pending_anchor()
2107 .expect("extend_selection not called with pending selection");
2108 if position >= tail {
2109 pending_selection.start = tail_anchor;
2110 } else {
2111 pending_selection.end = tail_anchor;
2112 pending_selection.reversed = true;
2113 }
2114
2115 let mut pending_mode = self.selections.pending_mode().unwrap();
2116 match &mut pending_mode {
2117 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2118 _ => {}
2119 }
2120
2121 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2122 s.set_pending(pending_selection, pending_mode)
2123 });
2124 }
2125
2126 fn begin_selection(
2127 &mut self,
2128 position: DisplayPoint,
2129 add: bool,
2130 click_count: usize,
2131 cx: &mut ViewContext<Self>,
2132 ) {
2133 if !self.focus_handle.is_focused(cx) {
2134 self.last_focused_descendant = None;
2135 cx.focus(&self.focus_handle);
2136 }
2137
2138 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2139 let buffer = &display_map.buffer_snapshot;
2140 let newest_selection = self.selections.newest_anchor().clone();
2141 let position = display_map.clip_point(position, Bias::Left);
2142
2143 let start;
2144 let end;
2145 let mode;
2146 let mut auto_scroll;
2147 match click_count {
2148 1 => {
2149 start = buffer.anchor_before(position.to_point(&display_map));
2150 end = start;
2151 mode = SelectMode::Character;
2152 auto_scroll = true;
2153 }
2154 2 => {
2155 let range = movement::surrounding_word(&display_map, position);
2156 start = buffer.anchor_before(range.start.to_point(&display_map));
2157 end = buffer.anchor_before(range.end.to_point(&display_map));
2158 mode = SelectMode::Word(start..end);
2159 auto_scroll = true;
2160 }
2161 3 => {
2162 let position = display_map
2163 .clip_point(position, Bias::Left)
2164 .to_point(&display_map);
2165 let line_start = display_map.prev_line_boundary(position).0;
2166 let next_line_start = buffer.clip_point(
2167 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2168 Bias::Left,
2169 );
2170 start = buffer.anchor_before(line_start);
2171 end = buffer.anchor_before(next_line_start);
2172 mode = SelectMode::Line(start..end);
2173 auto_scroll = true;
2174 }
2175 _ => {
2176 start = buffer.anchor_before(0);
2177 end = buffer.anchor_before(buffer.len());
2178 mode = SelectMode::All;
2179 auto_scroll = false;
2180 }
2181 }
2182 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2183
2184 let point_to_delete: Option<usize> = {
2185 let selected_points: Vec<Selection<Point>> =
2186 self.selections.disjoint_in_range(start..end, cx);
2187
2188 if !add || click_count > 1 {
2189 None
2190 } else if !selected_points.is_empty() {
2191 Some(selected_points[0].id)
2192 } else {
2193 let clicked_point_already_selected =
2194 self.selections.disjoint.iter().find(|selection| {
2195 selection.start.to_point(buffer) == start.to_point(buffer)
2196 || selection.end.to_point(buffer) == end.to_point(buffer)
2197 });
2198
2199 clicked_point_already_selected.map(|selection| selection.id)
2200 }
2201 };
2202
2203 let selections_count = self.selections.count();
2204
2205 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2206 if let Some(point_to_delete) = point_to_delete {
2207 s.delete(point_to_delete);
2208
2209 if selections_count == 1 {
2210 s.set_pending_anchor_range(start..end, mode);
2211 }
2212 } else {
2213 if !add {
2214 s.clear_disjoint();
2215 } else if click_count > 1 {
2216 s.delete(newest_selection.id)
2217 }
2218
2219 s.set_pending_anchor_range(start..end, mode);
2220 }
2221 });
2222 }
2223
2224 fn begin_columnar_selection(
2225 &mut self,
2226 position: DisplayPoint,
2227 goal_column: u32,
2228 reset: bool,
2229 cx: &mut ViewContext<Self>,
2230 ) {
2231 if !self.focus_handle.is_focused(cx) {
2232 self.last_focused_descendant = None;
2233 cx.focus(&self.focus_handle);
2234 }
2235
2236 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2237
2238 if reset {
2239 let pointer_position = display_map
2240 .buffer_snapshot
2241 .anchor_before(position.to_point(&display_map));
2242
2243 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2244 s.clear_disjoint();
2245 s.set_pending_anchor_range(
2246 pointer_position..pointer_position,
2247 SelectMode::Character,
2248 );
2249 });
2250 }
2251
2252 let tail = self.selections.newest::<Point>(cx).tail();
2253 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2254
2255 if !reset {
2256 self.select_columns(
2257 tail.to_display_point(&display_map),
2258 position,
2259 goal_column,
2260 &display_map,
2261 cx,
2262 );
2263 }
2264 }
2265
2266 fn update_selection(
2267 &mut self,
2268 position: DisplayPoint,
2269 goal_column: u32,
2270 scroll_delta: gpui::Point<f32>,
2271 cx: &mut ViewContext<Self>,
2272 ) {
2273 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2274
2275 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2276 let tail = tail.to_display_point(&display_map);
2277 self.select_columns(tail, position, goal_column, &display_map, cx);
2278 } else if let Some(mut pending) = self.selections.pending_anchor() {
2279 let buffer = self.buffer.read(cx).snapshot(cx);
2280 let head;
2281 let tail;
2282 let mode = self.selections.pending_mode().unwrap();
2283 match &mode {
2284 SelectMode::Character => {
2285 head = position.to_point(&display_map);
2286 tail = pending.tail().to_point(&buffer);
2287 }
2288 SelectMode::Word(original_range) => {
2289 let original_display_range = original_range.start.to_display_point(&display_map)
2290 ..original_range.end.to_display_point(&display_map);
2291 let original_buffer_range = original_display_range.start.to_point(&display_map)
2292 ..original_display_range.end.to_point(&display_map);
2293 if movement::is_inside_word(&display_map, position)
2294 || original_display_range.contains(&position)
2295 {
2296 let word_range = movement::surrounding_word(&display_map, position);
2297 if word_range.start < original_display_range.start {
2298 head = word_range.start.to_point(&display_map);
2299 } else {
2300 head = word_range.end.to_point(&display_map);
2301 }
2302 } else {
2303 head = position.to_point(&display_map);
2304 }
2305
2306 if head <= original_buffer_range.start {
2307 tail = original_buffer_range.end;
2308 } else {
2309 tail = original_buffer_range.start;
2310 }
2311 }
2312 SelectMode::Line(original_range) => {
2313 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2314
2315 let position = display_map
2316 .clip_point(position, Bias::Left)
2317 .to_point(&display_map);
2318 let line_start = display_map.prev_line_boundary(position).0;
2319 let next_line_start = buffer.clip_point(
2320 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2321 Bias::Left,
2322 );
2323
2324 if line_start < original_range.start {
2325 head = line_start
2326 } else {
2327 head = next_line_start
2328 }
2329
2330 if head <= original_range.start {
2331 tail = original_range.end;
2332 } else {
2333 tail = original_range.start;
2334 }
2335 }
2336 SelectMode::All => {
2337 return;
2338 }
2339 };
2340
2341 if head < tail {
2342 pending.start = buffer.anchor_before(head);
2343 pending.end = buffer.anchor_before(tail);
2344 pending.reversed = true;
2345 } else {
2346 pending.start = buffer.anchor_before(tail);
2347 pending.end = buffer.anchor_before(head);
2348 pending.reversed = false;
2349 }
2350
2351 self.change_selections(None, cx, |s| {
2352 s.set_pending(pending, mode);
2353 });
2354 } else {
2355 log::error!("update_selection dispatched with no pending selection");
2356 return;
2357 }
2358
2359 self.apply_scroll_delta(scroll_delta, cx);
2360 cx.notify();
2361 }
2362
2363 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2364 self.columnar_selection_tail.take();
2365 if self.selections.pending_anchor().is_some() {
2366 let selections = self.selections.all::<usize>(cx);
2367 self.change_selections(None, cx, |s| {
2368 s.select(selections);
2369 s.clear_pending();
2370 });
2371 }
2372 }
2373
2374 fn select_columns(
2375 &mut self,
2376 tail: DisplayPoint,
2377 head: DisplayPoint,
2378 goal_column: u32,
2379 display_map: &DisplaySnapshot,
2380 cx: &mut ViewContext<Self>,
2381 ) {
2382 let start_row = cmp::min(tail.row(), head.row());
2383 let end_row = cmp::max(tail.row(), head.row());
2384 let start_column = cmp::min(tail.column(), goal_column);
2385 let end_column = cmp::max(tail.column(), goal_column);
2386 let reversed = start_column < tail.column();
2387
2388 let selection_ranges = (start_row.0..=end_row.0)
2389 .map(DisplayRow)
2390 .filter_map(|row| {
2391 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2392 let start = display_map
2393 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2394 .to_point(display_map);
2395 let end = display_map
2396 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2397 .to_point(display_map);
2398 if reversed {
2399 Some(end..start)
2400 } else {
2401 Some(start..end)
2402 }
2403 } else {
2404 None
2405 }
2406 })
2407 .collect::<Vec<_>>();
2408
2409 self.change_selections(None, cx, |s| {
2410 s.select_ranges(selection_ranges);
2411 });
2412 cx.notify();
2413 }
2414
2415 pub fn has_pending_nonempty_selection(&self) -> bool {
2416 let pending_nonempty_selection = match self.selections.pending_anchor() {
2417 Some(Selection { start, end, .. }) => start != end,
2418 None => false,
2419 };
2420
2421 pending_nonempty_selection
2422 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2423 }
2424
2425 pub fn has_pending_selection(&self) -> bool {
2426 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2427 }
2428
2429 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2430 if self.clear_expanded_diff_hunks(cx) {
2431 cx.notify();
2432 return;
2433 }
2434 if self.dismiss_menus_and_popups(true, cx) {
2435 return;
2436 }
2437
2438 if self.mode == EditorMode::Full
2439 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
2440 {
2441 return;
2442 }
2443
2444 cx.propagate();
2445 }
2446
2447 pub fn dismiss_menus_and_popups(
2448 &mut self,
2449 should_report_inline_completion_event: bool,
2450 cx: &mut ViewContext<Self>,
2451 ) -> bool {
2452 if self.take_rename(false, cx).is_some() {
2453 return true;
2454 }
2455
2456 if hide_hover(self, cx) {
2457 return true;
2458 }
2459
2460 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2461 return true;
2462 }
2463
2464 if self.hide_context_menu(cx).is_some() {
2465 return true;
2466 }
2467
2468 if self.mouse_context_menu.take().is_some() {
2469 return true;
2470 }
2471
2472 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2473 return true;
2474 }
2475
2476 if self.snippet_stack.pop().is_some() {
2477 return true;
2478 }
2479
2480 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2481 self.dismiss_diagnostics(cx);
2482 return true;
2483 }
2484
2485 false
2486 }
2487
2488 fn linked_editing_ranges_for(
2489 &self,
2490 selection: Range<text::Anchor>,
2491 cx: &AppContext,
2492 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2493 if self.linked_edit_ranges.is_empty() {
2494 return None;
2495 }
2496 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2497 selection.end.buffer_id.and_then(|end_buffer_id| {
2498 if selection.start.buffer_id != Some(end_buffer_id) {
2499 return None;
2500 }
2501 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2502 let snapshot = buffer.read(cx).snapshot();
2503 self.linked_edit_ranges
2504 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2505 .map(|ranges| (ranges, snapshot, buffer))
2506 })?;
2507 use text::ToOffset as TO;
2508 // find offset from the start of current range to current cursor position
2509 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2510
2511 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2512 let start_difference = start_offset - start_byte_offset;
2513 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2514 let end_difference = end_offset - start_byte_offset;
2515 // Current range has associated linked ranges.
2516 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2517 for range in linked_ranges.iter() {
2518 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2519 let end_offset = start_offset + end_difference;
2520 let start_offset = start_offset + start_difference;
2521 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2522 continue;
2523 }
2524 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
2525 if s.start.buffer_id != selection.start.buffer_id
2526 || s.end.buffer_id != selection.end.buffer_id
2527 {
2528 return false;
2529 }
2530 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2531 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2532 }) {
2533 continue;
2534 }
2535 let start = buffer_snapshot.anchor_after(start_offset);
2536 let end = buffer_snapshot.anchor_after(end_offset);
2537 linked_edits
2538 .entry(buffer.clone())
2539 .or_default()
2540 .push(start..end);
2541 }
2542 Some(linked_edits)
2543 }
2544
2545 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2546 let text: Arc<str> = text.into();
2547
2548 if self.read_only(cx) {
2549 return;
2550 }
2551
2552 let selections = self.selections.all_adjusted(cx);
2553 let mut bracket_inserted = false;
2554 let mut edits = Vec::new();
2555 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2556 let mut new_selections = Vec::with_capacity(selections.len());
2557 let mut new_autoclose_regions = Vec::new();
2558 let snapshot = self.buffer.read(cx).read(cx);
2559
2560 for (selection, autoclose_region) in
2561 self.selections_with_autoclose_regions(selections, &snapshot)
2562 {
2563 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2564 // Determine if the inserted text matches the opening or closing
2565 // bracket of any of this language's bracket pairs.
2566 let mut bracket_pair = None;
2567 let mut is_bracket_pair_start = false;
2568 let mut is_bracket_pair_end = false;
2569 if !text.is_empty() {
2570 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2571 // and they are removing the character that triggered IME popup.
2572 for (pair, enabled) in scope.brackets() {
2573 if !pair.close && !pair.surround {
2574 continue;
2575 }
2576
2577 if enabled && pair.start.ends_with(text.as_ref()) {
2578 let prefix_len = pair.start.len() - text.len();
2579 let preceding_text_matches_prefix = prefix_len == 0
2580 || (selection.start.column >= (prefix_len as u32)
2581 && snapshot.contains_str_at(
2582 Point::new(
2583 selection.start.row,
2584 selection.start.column - (prefix_len as u32),
2585 ),
2586 &pair.start[..prefix_len],
2587 ));
2588 if preceding_text_matches_prefix {
2589 bracket_pair = Some(pair.clone());
2590 is_bracket_pair_start = true;
2591 break;
2592 }
2593 }
2594 if pair.end.as_str() == text.as_ref() {
2595 bracket_pair = Some(pair.clone());
2596 is_bracket_pair_end = true;
2597 break;
2598 }
2599 }
2600 }
2601
2602 if let Some(bracket_pair) = bracket_pair {
2603 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2604 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2605 let auto_surround =
2606 self.use_auto_surround && snapshot_settings.use_auto_surround;
2607 if selection.is_empty() {
2608 if is_bracket_pair_start {
2609 // If the inserted text is a suffix of an opening bracket and the
2610 // selection is preceded by the rest of the opening bracket, then
2611 // insert the closing bracket.
2612 let following_text_allows_autoclose = snapshot
2613 .chars_at(selection.start)
2614 .next()
2615 .map_or(true, |c| scope.should_autoclose_before(c));
2616
2617 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2618 && bracket_pair.start.len() == 1
2619 {
2620 let target = bracket_pair.start.chars().next().unwrap();
2621 let current_line_count = snapshot
2622 .reversed_chars_at(selection.start)
2623 .take_while(|&c| c != '\n')
2624 .filter(|&c| c == target)
2625 .count();
2626 current_line_count % 2 == 1
2627 } else {
2628 false
2629 };
2630
2631 if autoclose
2632 && bracket_pair.close
2633 && following_text_allows_autoclose
2634 && !is_closing_quote
2635 {
2636 let anchor = snapshot.anchor_before(selection.end);
2637 new_selections.push((selection.map(|_| anchor), text.len()));
2638 new_autoclose_regions.push((
2639 anchor,
2640 text.len(),
2641 selection.id,
2642 bracket_pair.clone(),
2643 ));
2644 edits.push((
2645 selection.range(),
2646 format!("{}{}", text, bracket_pair.end).into(),
2647 ));
2648 bracket_inserted = true;
2649 continue;
2650 }
2651 }
2652
2653 if let Some(region) = autoclose_region {
2654 // If the selection is followed by an auto-inserted closing bracket,
2655 // then don't insert that closing bracket again; just move the selection
2656 // past the closing bracket.
2657 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2658 && text.as_ref() == region.pair.end.as_str();
2659 if should_skip {
2660 let anchor = snapshot.anchor_after(selection.end);
2661 new_selections
2662 .push((selection.map(|_| anchor), region.pair.end.len()));
2663 continue;
2664 }
2665 }
2666
2667 let always_treat_brackets_as_autoclosed = snapshot
2668 .settings_at(selection.start, cx)
2669 .always_treat_brackets_as_autoclosed;
2670 if always_treat_brackets_as_autoclosed
2671 && is_bracket_pair_end
2672 && snapshot.contains_str_at(selection.end, text.as_ref())
2673 {
2674 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2675 // and the inserted text is a closing bracket and the selection is followed
2676 // by the closing bracket then move the selection past the closing bracket.
2677 let anchor = snapshot.anchor_after(selection.end);
2678 new_selections.push((selection.map(|_| anchor), text.len()));
2679 continue;
2680 }
2681 }
2682 // If an opening bracket is 1 character long and is typed while
2683 // text is selected, then surround that text with the bracket pair.
2684 else if auto_surround
2685 && bracket_pair.surround
2686 && is_bracket_pair_start
2687 && bracket_pair.start.chars().count() == 1
2688 {
2689 edits.push((selection.start..selection.start, text.clone()));
2690 edits.push((
2691 selection.end..selection.end,
2692 bracket_pair.end.as_str().into(),
2693 ));
2694 bracket_inserted = true;
2695 new_selections.push((
2696 Selection {
2697 id: selection.id,
2698 start: snapshot.anchor_after(selection.start),
2699 end: snapshot.anchor_before(selection.end),
2700 reversed: selection.reversed,
2701 goal: selection.goal,
2702 },
2703 0,
2704 ));
2705 continue;
2706 }
2707 }
2708 }
2709
2710 if self.auto_replace_emoji_shortcode
2711 && selection.is_empty()
2712 && text.as_ref().ends_with(':')
2713 {
2714 if let Some(possible_emoji_short_code) =
2715 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2716 {
2717 if !possible_emoji_short_code.is_empty() {
2718 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2719 let emoji_shortcode_start = Point::new(
2720 selection.start.row,
2721 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2722 );
2723
2724 // Remove shortcode from buffer
2725 edits.push((
2726 emoji_shortcode_start..selection.start,
2727 "".to_string().into(),
2728 ));
2729 new_selections.push((
2730 Selection {
2731 id: selection.id,
2732 start: snapshot.anchor_after(emoji_shortcode_start),
2733 end: snapshot.anchor_before(selection.start),
2734 reversed: selection.reversed,
2735 goal: selection.goal,
2736 },
2737 0,
2738 ));
2739
2740 // Insert emoji
2741 let selection_start_anchor = snapshot.anchor_after(selection.start);
2742 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2743 edits.push((selection.start..selection.end, emoji.to_string().into()));
2744
2745 continue;
2746 }
2747 }
2748 }
2749 }
2750
2751 // If not handling any auto-close operation, then just replace the selected
2752 // text with the given input and move the selection to the end of the
2753 // newly inserted text.
2754 let anchor = snapshot.anchor_after(selection.end);
2755 if !self.linked_edit_ranges.is_empty() {
2756 let start_anchor = snapshot.anchor_before(selection.start);
2757
2758 let is_word_char = text.chars().next().map_or(true, |char| {
2759 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2760 classifier.is_word(char)
2761 });
2762
2763 if is_word_char {
2764 if let Some(ranges) = self
2765 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2766 {
2767 for (buffer, edits) in ranges {
2768 linked_edits
2769 .entry(buffer.clone())
2770 .or_default()
2771 .extend(edits.into_iter().map(|range| (range, text.clone())));
2772 }
2773 }
2774 }
2775 }
2776
2777 new_selections.push((selection.map(|_| anchor), 0));
2778 edits.push((selection.start..selection.end, text.clone()));
2779 }
2780
2781 drop(snapshot);
2782
2783 self.transact(cx, |this, cx| {
2784 this.buffer.update(cx, |buffer, cx| {
2785 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2786 });
2787 for (buffer, edits) in linked_edits {
2788 buffer.update(cx, |buffer, cx| {
2789 let snapshot = buffer.snapshot();
2790 let edits = edits
2791 .into_iter()
2792 .map(|(range, text)| {
2793 use text::ToPoint as TP;
2794 let end_point = TP::to_point(&range.end, &snapshot);
2795 let start_point = TP::to_point(&range.start, &snapshot);
2796 (start_point..end_point, text)
2797 })
2798 .sorted_by_key(|(range, _)| range.start)
2799 .collect::<Vec<_>>();
2800 buffer.edit(edits, None, cx);
2801 })
2802 }
2803 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2804 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2805 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2806 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2807 .zip(new_selection_deltas)
2808 .map(|(selection, delta)| Selection {
2809 id: selection.id,
2810 start: selection.start + delta,
2811 end: selection.end + delta,
2812 reversed: selection.reversed,
2813 goal: SelectionGoal::None,
2814 })
2815 .collect::<Vec<_>>();
2816
2817 let mut i = 0;
2818 for (position, delta, selection_id, pair) in new_autoclose_regions {
2819 let position = position.to_offset(&map.buffer_snapshot) + delta;
2820 let start = map.buffer_snapshot.anchor_before(position);
2821 let end = map.buffer_snapshot.anchor_after(position);
2822 while let Some(existing_state) = this.autoclose_regions.get(i) {
2823 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2824 Ordering::Less => i += 1,
2825 Ordering::Greater => break,
2826 Ordering::Equal => {
2827 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2828 Ordering::Less => i += 1,
2829 Ordering::Equal => break,
2830 Ordering::Greater => break,
2831 }
2832 }
2833 }
2834 }
2835 this.autoclose_regions.insert(
2836 i,
2837 AutocloseRegion {
2838 selection_id,
2839 range: start..end,
2840 pair,
2841 },
2842 );
2843 }
2844
2845 let had_active_inline_completion = this.has_active_inline_completion();
2846 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
2847 s.select(new_selections)
2848 });
2849
2850 if !bracket_inserted {
2851 if let Some(on_type_format_task) =
2852 this.trigger_on_type_formatting(text.to_string(), cx)
2853 {
2854 on_type_format_task.detach_and_log_err(cx);
2855 }
2856 }
2857
2858 let editor_settings = EditorSettings::get_global(cx);
2859 if bracket_inserted
2860 && (editor_settings.auto_signature_help
2861 || editor_settings.show_signature_help_after_edits)
2862 {
2863 this.show_signature_help(&ShowSignatureHelp, cx);
2864 }
2865
2866 let trigger_in_words = !had_active_inline_completion;
2867 this.trigger_completion_on_input(&text, trigger_in_words, cx);
2868 linked_editing_ranges::refresh_linked_ranges(this, cx);
2869 this.refresh_inline_completion(true, false, cx);
2870 });
2871 }
2872
2873 fn find_possible_emoji_shortcode_at_position(
2874 snapshot: &MultiBufferSnapshot,
2875 position: Point,
2876 ) -> Option<String> {
2877 let mut chars = Vec::new();
2878 let mut found_colon = false;
2879 for char in snapshot.reversed_chars_at(position).take(100) {
2880 // Found a possible emoji shortcode in the middle of the buffer
2881 if found_colon {
2882 if char.is_whitespace() {
2883 chars.reverse();
2884 return Some(chars.iter().collect());
2885 }
2886 // If the previous character is not a whitespace, we are in the middle of a word
2887 // and we only want to complete the shortcode if the word is made up of other emojis
2888 let mut containing_word = String::new();
2889 for ch in snapshot
2890 .reversed_chars_at(position)
2891 .skip(chars.len() + 1)
2892 .take(100)
2893 {
2894 if ch.is_whitespace() {
2895 break;
2896 }
2897 containing_word.push(ch);
2898 }
2899 let containing_word = containing_word.chars().rev().collect::<String>();
2900 if util::word_consists_of_emojis(containing_word.as_str()) {
2901 chars.reverse();
2902 return Some(chars.iter().collect());
2903 }
2904 }
2905
2906 if char.is_whitespace() || !char.is_ascii() {
2907 return None;
2908 }
2909 if char == ':' {
2910 found_colon = true;
2911 } else {
2912 chars.push(char);
2913 }
2914 }
2915 // Found a possible emoji shortcode at the beginning of the buffer
2916 chars.reverse();
2917 Some(chars.iter().collect())
2918 }
2919
2920 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
2921 self.transact(cx, |this, cx| {
2922 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
2923 let selections = this.selections.all::<usize>(cx);
2924 let multi_buffer = this.buffer.read(cx);
2925 let buffer = multi_buffer.snapshot(cx);
2926 selections
2927 .iter()
2928 .map(|selection| {
2929 let start_point = selection.start.to_point(&buffer);
2930 let mut indent =
2931 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
2932 indent.len = cmp::min(indent.len, start_point.column);
2933 let start = selection.start;
2934 let end = selection.end;
2935 let selection_is_empty = start == end;
2936 let language_scope = buffer.language_scope_at(start);
2937 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
2938 &language_scope
2939 {
2940 let leading_whitespace_len = buffer
2941 .reversed_chars_at(start)
2942 .take_while(|c| c.is_whitespace() && *c != '\n')
2943 .map(|c| c.len_utf8())
2944 .sum::<usize>();
2945
2946 let trailing_whitespace_len = buffer
2947 .chars_at(end)
2948 .take_while(|c| c.is_whitespace() && *c != '\n')
2949 .map(|c| c.len_utf8())
2950 .sum::<usize>();
2951
2952 let insert_extra_newline =
2953 language.brackets().any(|(pair, enabled)| {
2954 let pair_start = pair.start.trim_end();
2955 let pair_end = pair.end.trim_start();
2956
2957 enabled
2958 && pair.newline
2959 && buffer.contains_str_at(
2960 end + trailing_whitespace_len,
2961 pair_end,
2962 )
2963 && buffer.contains_str_at(
2964 (start - leading_whitespace_len)
2965 .saturating_sub(pair_start.len()),
2966 pair_start,
2967 )
2968 });
2969
2970 // Comment extension on newline is allowed only for cursor selections
2971 let comment_delimiter = maybe!({
2972 if !selection_is_empty {
2973 return None;
2974 }
2975
2976 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
2977 return None;
2978 }
2979
2980 let delimiters = language.line_comment_prefixes();
2981 let max_len_of_delimiter =
2982 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
2983 let (snapshot, range) =
2984 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
2985
2986 let mut index_of_first_non_whitespace = 0;
2987 let comment_candidate = snapshot
2988 .chars_for_range(range)
2989 .skip_while(|c| {
2990 let should_skip = c.is_whitespace();
2991 if should_skip {
2992 index_of_first_non_whitespace += 1;
2993 }
2994 should_skip
2995 })
2996 .take(max_len_of_delimiter)
2997 .collect::<String>();
2998 let comment_prefix = delimiters.iter().find(|comment_prefix| {
2999 comment_candidate.starts_with(comment_prefix.as_ref())
3000 })?;
3001 let cursor_is_placed_after_comment_marker =
3002 index_of_first_non_whitespace + comment_prefix.len()
3003 <= start_point.column as usize;
3004 if cursor_is_placed_after_comment_marker {
3005 Some(comment_prefix.clone())
3006 } else {
3007 None
3008 }
3009 });
3010 (comment_delimiter, insert_extra_newline)
3011 } else {
3012 (None, false)
3013 };
3014
3015 let capacity_for_delimiter = comment_delimiter
3016 .as_deref()
3017 .map(str::len)
3018 .unwrap_or_default();
3019 let mut new_text =
3020 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3021 new_text.push('\n');
3022 new_text.extend(indent.chars());
3023 if let Some(delimiter) = &comment_delimiter {
3024 new_text.push_str(delimiter);
3025 }
3026 if insert_extra_newline {
3027 new_text = new_text.repeat(2);
3028 }
3029
3030 let anchor = buffer.anchor_after(end);
3031 let new_selection = selection.map(|_| anchor);
3032 (
3033 (start..end, new_text),
3034 (insert_extra_newline, new_selection),
3035 )
3036 })
3037 .unzip()
3038 };
3039
3040 this.edit_with_autoindent(edits, cx);
3041 let buffer = this.buffer.read(cx).snapshot(cx);
3042 let new_selections = selection_fixup_info
3043 .into_iter()
3044 .map(|(extra_newline_inserted, new_selection)| {
3045 let mut cursor = new_selection.end.to_point(&buffer);
3046 if extra_newline_inserted {
3047 cursor.row -= 1;
3048 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3049 }
3050 new_selection.map(|_| cursor)
3051 })
3052 .collect();
3053
3054 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3055 this.refresh_inline_completion(true, false, cx);
3056 });
3057 }
3058
3059 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3060 let buffer = self.buffer.read(cx);
3061 let snapshot = buffer.snapshot(cx);
3062
3063 let mut edits = Vec::new();
3064 let mut rows = Vec::new();
3065
3066 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3067 let cursor = selection.head();
3068 let row = cursor.row;
3069
3070 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3071
3072 let newline = "\n".to_string();
3073 edits.push((start_of_line..start_of_line, newline));
3074
3075 rows.push(row + rows_inserted as u32);
3076 }
3077
3078 self.transact(cx, |editor, cx| {
3079 editor.edit(edits, cx);
3080
3081 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3082 let mut index = 0;
3083 s.move_cursors_with(|map, _, _| {
3084 let row = rows[index];
3085 index += 1;
3086
3087 let point = Point::new(row, 0);
3088 let boundary = map.next_line_boundary(point).1;
3089 let clipped = map.clip_point(boundary, Bias::Left);
3090
3091 (clipped, SelectionGoal::None)
3092 });
3093 });
3094
3095 let mut indent_edits = Vec::new();
3096 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3097 for row in rows {
3098 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3099 for (row, indent) in indents {
3100 if indent.len == 0 {
3101 continue;
3102 }
3103
3104 let text = match indent.kind {
3105 IndentKind::Space => " ".repeat(indent.len as usize),
3106 IndentKind::Tab => "\t".repeat(indent.len as usize),
3107 };
3108 let point = Point::new(row.0, 0);
3109 indent_edits.push((point..point, text));
3110 }
3111 }
3112 editor.edit(indent_edits, cx);
3113 });
3114 }
3115
3116 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3117 let buffer = self.buffer.read(cx);
3118 let snapshot = buffer.snapshot(cx);
3119
3120 let mut edits = Vec::new();
3121 let mut rows = Vec::new();
3122 let mut rows_inserted = 0;
3123
3124 for selection in self.selections.all_adjusted(cx) {
3125 let cursor = selection.head();
3126 let row = cursor.row;
3127
3128 let point = Point::new(row + 1, 0);
3129 let start_of_line = snapshot.clip_point(point, Bias::Left);
3130
3131 let newline = "\n".to_string();
3132 edits.push((start_of_line..start_of_line, newline));
3133
3134 rows_inserted += 1;
3135 rows.push(row + rows_inserted);
3136 }
3137
3138 self.transact(cx, |editor, cx| {
3139 editor.edit(edits, cx);
3140
3141 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3142 let mut index = 0;
3143 s.move_cursors_with(|map, _, _| {
3144 let row = rows[index];
3145 index += 1;
3146
3147 let point = Point::new(row, 0);
3148 let boundary = map.next_line_boundary(point).1;
3149 let clipped = map.clip_point(boundary, Bias::Left);
3150
3151 (clipped, SelectionGoal::None)
3152 });
3153 });
3154
3155 let mut indent_edits = Vec::new();
3156 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3157 for row in rows {
3158 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3159 for (row, indent) in indents {
3160 if indent.len == 0 {
3161 continue;
3162 }
3163
3164 let text = match indent.kind {
3165 IndentKind::Space => " ".repeat(indent.len as usize),
3166 IndentKind::Tab => "\t".repeat(indent.len as usize),
3167 };
3168 let point = Point::new(row.0, 0);
3169 indent_edits.push((point..point, text));
3170 }
3171 }
3172 editor.edit(indent_edits, cx);
3173 });
3174 }
3175
3176 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3177 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3178 original_indent_columns: Vec::new(),
3179 });
3180 self.insert_with_autoindent_mode(text, autoindent, cx);
3181 }
3182
3183 fn insert_with_autoindent_mode(
3184 &mut self,
3185 text: &str,
3186 autoindent_mode: Option<AutoindentMode>,
3187 cx: &mut ViewContext<Self>,
3188 ) {
3189 if self.read_only(cx) {
3190 return;
3191 }
3192
3193 let text: Arc<str> = text.into();
3194 self.transact(cx, |this, cx| {
3195 let old_selections = this.selections.all_adjusted(cx);
3196 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3197 let anchors = {
3198 let snapshot = buffer.read(cx);
3199 old_selections
3200 .iter()
3201 .map(|s| {
3202 let anchor = snapshot.anchor_after(s.head());
3203 s.map(|_| anchor)
3204 })
3205 .collect::<Vec<_>>()
3206 };
3207 buffer.edit(
3208 old_selections
3209 .iter()
3210 .map(|s| (s.start..s.end, text.clone())),
3211 autoindent_mode,
3212 cx,
3213 );
3214 anchors
3215 });
3216
3217 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3218 s.select_anchors(selection_anchors);
3219 })
3220 });
3221 }
3222
3223 fn trigger_completion_on_input(
3224 &mut self,
3225 text: &str,
3226 trigger_in_words: bool,
3227 cx: &mut ViewContext<Self>,
3228 ) {
3229 if self.is_completion_trigger(text, trigger_in_words, cx) {
3230 self.show_completions(
3231 &ShowCompletions {
3232 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3233 },
3234 cx,
3235 );
3236 } else {
3237 self.hide_context_menu(cx);
3238 }
3239 }
3240
3241 fn is_completion_trigger(
3242 &self,
3243 text: &str,
3244 trigger_in_words: bool,
3245 cx: &mut ViewContext<Self>,
3246 ) -> bool {
3247 let position = self.selections.newest_anchor().head();
3248 let multibuffer = self.buffer.read(cx);
3249 let Some(buffer) = position
3250 .buffer_id
3251 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3252 else {
3253 return false;
3254 };
3255
3256 if let Some(completion_provider) = &self.completion_provider {
3257 completion_provider.is_completion_trigger(
3258 &buffer,
3259 position.text_anchor,
3260 text,
3261 trigger_in_words,
3262 cx,
3263 )
3264 } else {
3265 false
3266 }
3267 }
3268
3269 /// If any empty selections is touching the start of its innermost containing autoclose
3270 /// region, expand it to select the brackets.
3271 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3272 let selections = self.selections.all::<usize>(cx);
3273 let buffer = self.buffer.read(cx).read(cx);
3274 let new_selections = self
3275 .selections_with_autoclose_regions(selections, &buffer)
3276 .map(|(mut selection, region)| {
3277 if !selection.is_empty() {
3278 return selection;
3279 }
3280
3281 if let Some(region) = region {
3282 let mut range = region.range.to_offset(&buffer);
3283 if selection.start == range.start && range.start >= region.pair.start.len() {
3284 range.start -= region.pair.start.len();
3285 if buffer.contains_str_at(range.start, ®ion.pair.start)
3286 && buffer.contains_str_at(range.end, ®ion.pair.end)
3287 {
3288 range.end += region.pair.end.len();
3289 selection.start = range.start;
3290 selection.end = range.end;
3291
3292 return selection;
3293 }
3294 }
3295 }
3296
3297 let always_treat_brackets_as_autoclosed = buffer
3298 .settings_at(selection.start, cx)
3299 .always_treat_brackets_as_autoclosed;
3300
3301 if !always_treat_brackets_as_autoclosed {
3302 return selection;
3303 }
3304
3305 if let Some(scope) = buffer.language_scope_at(selection.start) {
3306 for (pair, enabled) in scope.brackets() {
3307 if !enabled || !pair.close {
3308 continue;
3309 }
3310
3311 if buffer.contains_str_at(selection.start, &pair.end) {
3312 let pair_start_len = pair.start.len();
3313 if buffer.contains_str_at(
3314 selection.start.saturating_sub(pair_start_len),
3315 &pair.start,
3316 ) {
3317 selection.start -= pair_start_len;
3318 selection.end += pair.end.len();
3319
3320 return selection;
3321 }
3322 }
3323 }
3324 }
3325
3326 selection
3327 })
3328 .collect();
3329
3330 drop(buffer);
3331 self.change_selections(None, cx, |selections| selections.select(new_selections));
3332 }
3333
3334 /// Iterate the given selections, and for each one, find the smallest surrounding
3335 /// autoclose region. This uses the ordering of the selections and the autoclose
3336 /// regions to avoid repeated comparisons.
3337 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3338 &'a self,
3339 selections: impl IntoIterator<Item = Selection<D>>,
3340 buffer: &'a MultiBufferSnapshot,
3341 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3342 let mut i = 0;
3343 let mut regions = self.autoclose_regions.as_slice();
3344 selections.into_iter().map(move |selection| {
3345 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3346
3347 let mut enclosing = None;
3348 while let Some(pair_state) = regions.get(i) {
3349 if pair_state.range.end.to_offset(buffer) < range.start {
3350 regions = ®ions[i + 1..];
3351 i = 0;
3352 } else if pair_state.range.start.to_offset(buffer) > range.end {
3353 break;
3354 } else {
3355 if pair_state.selection_id == selection.id {
3356 enclosing = Some(pair_state);
3357 }
3358 i += 1;
3359 }
3360 }
3361
3362 (selection, enclosing)
3363 })
3364 }
3365
3366 /// Remove any autoclose regions that no longer contain their selection.
3367 fn invalidate_autoclose_regions(
3368 &mut self,
3369 mut selections: &[Selection<Anchor>],
3370 buffer: &MultiBufferSnapshot,
3371 ) {
3372 self.autoclose_regions.retain(|state| {
3373 let mut i = 0;
3374 while let Some(selection) = selections.get(i) {
3375 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3376 selections = &selections[1..];
3377 continue;
3378 }
3379 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3380 break;
3381 }
3382 if selection.id == state.selection_id {
3383 return true;
3384 } else {
3385 i += 1;
3386 }
3387 }
3388 false
3389 });
3390 }
3391
3392 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3393 let offset = position.to_offset(buffer);
3394 let (word_range, kind) = buffer.surrounding_word(offset, true);
3395 if offset > word_range.start && kind == Some(CharKind::Word) {
3396 Some(
3397 buffer
3398 .text_for_range(word_range.start..offset)
3399 .collect::<String>(),
3400 )
3401 } else {
3402 None
3403 }
3404 }
3405
3406 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3407 self.refresh_inlay_hints(
3408 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3409 cx,
3410 );
3411 }
3412
3413 pub fn inlay_hints_enabled(&self) -> bool {
3414 self.inlay_hint_cache.enabled
3415 }
3416
3417 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3418 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3419 return;
3420 }
3421
3422 let reason_description = reason.description();
3423 let ignore_debounce = matches!(
3424 reason,
3425 InlayHintRefreshReason::SettingsChange(_)
3426 | InlayHintRefreshReason::Toggle(_)
3427 | InlayHintRefreshReason::ExcerptsRemoved(_)
3428 );
3429 let (invalidate_cache, required_languages) = match reason {
3430 InlayHintRefreshReason::Toggle(enabled) => {
3431 self.inlay_hint_cache.enabled = enabled;
3432 if enabled {
3433 (InvalidationStrategy::RefreshRequested, None)
3434 } else {
3435 self.inlay_hint_cache.clear();
3436 self.splice_inlays(
3437 self.visible_inlay_hints(cx)
3438 .iter()
3439 .map(|inlay| inlay.id)
3440 .collect(),
3441 Vec::new(),
3442 cx,
3443 );
3444 return;
3445 }
3446 }
3447 InlayHintRefreshReason::SettingsChange(new_settings) => {
3448 match self.inlay_hint_cache.update_settings(
3449 &self.buffer,
3450 new_settings,
3451 self.visible_inlay_hints(cx),
3452 cx,
3453 ) {
3454 ControlFlow::Break(Some(InlaySplice {
3455 to_remove,
3456 to_insert,
3457 })) => {
3458 self.splice_inlays(to_remove, to_insert, cx);
3459 return;
3460 }
3461 ControlFlow::Break(None) => return,
3462 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3463 }
3464 }
3465 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3466 if let Some(InlaySplice {
3467 to_remove,
3468 to_insert,
3469 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3470 {
3471 self.splice_inlays(to_remove, to_insert, cx);
3472 }
3473 return;
3474 }
3475 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3476 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3477 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3478 }
3479 InlayHintRefreshReason::RefreshRequested => {
3480 (InvalidationStrategy::RefreshRequested, None)
3481 }
3482 };
3483
3484 if let Some(InlaySplice {
3485 to_remove,
3486 to_insert,
3487 }) = self.inlay_hint_cache.spawn_hint_refresh(
3488 reason_description,
3489 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3490 invalidate_cache,
3491 ignore_debounce,
3492 cx,
3493 ) {
3494 self.splice_inlays(to_remove, to_insert, cx);
3495 }
3496 }
3497
3498 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
3499 self.display_map
3500 .read(cx)
3501 .current_inlays()
3502 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3503 .cloned()
3504 .collect()
3505 }
3506
3507 pub fn excerpts_for_inlay_hints_query(
3508 &self,
3509 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3510 cx: &mut ViewContext<Editor>,
3511 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3512 let Some(project) = self.project.as_ref() else {
3513 return HashMap::default();
3514 };
3515 let project = project.read(cx);
3516 let multi_buffer = self.buffer().read(cx);
3517 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3518 let multi_buffer_visible_start = self
3519 .scroll_manager
3520 .anchor()
3521 .anchor
3522 .to_point(&multi_buffer_snapshot);
3523 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3524 multi_buffer_visible_start
3525 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3526 Bias::Left,
3527 );
3528 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3529 multi_buffer
3530 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
3531 .into_iter()
3532 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3533 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
3534 let buffer = buffer_handle.read(cx);
3535 let buffer_file = project::File::from_dyn(buffer.file())?;
3536 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3537 let worktree_entry = buffer_worktree
3538 .read(cx)
3539 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3540 if worktree_entry.is_ignored {
3541 return None;
3542 }
3543
3544 let language = buffer.language()?;
3545 if let Some(restrict_to_languages) = restrict_to_languages {
3546 if !restrict_to_languages.contains(language) {
3547 return None;
3548 }
3549 }
3550 Some((
3551 excerpt_id,
3552 (
3553 buffer_handle,
3554 buffer.version().clone(),
3555 excerpt_visible_range,
3556 ),
3557 ))
3558 })
3559 .collect()
3560 }
3561
3562 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3563 TextLayoutDetails {
3564 text_system: cx.text_system().clone(),
3565 editor_style: self.style.clone().unwrap(),
3566 rem_size: cx.rem_size(),
3567 scroll_anchor: self.scroll_manager.anchor(),
3568 visible_rows: self.visible_line_count(),
3569 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3570 }
3571 }
3572
3573 fn splice_inlays(
3574 &self,
3575 to_remove: Vec<InlayId>,
3576 to_insert: Vec<Inlay>,
3577 cx: &mut ViewContext<Self>,
3578 ) {
3579 self.display_map.update(cx, |display_map, cx| {
3580 display_map.splice_inlays(to_remove, to_insert, cx)
3581 });
3582 cx.notify();
3583 }
3584
3585 fn trigger_on_type_formatting(
3586 &self,
3587 input: String,
3588 cx: &mut ViewContext<Self>,
3589 ) -> Option<Task<Result<()>>> {
3590 if input.len() != 1 {
3591 return None;
3592 }
3593
3594 let project = self.project.as_ref()?;
3595 let position = self.selections.newest_anchor().head();
3596 let (buffer, buffer_position) = self
3597 .buffer
3598 .read(cx)
3599 .text_anchor_for_position(position, cx)?;
3600
3601 let settings = language_settings::language_settings(
3602 buffer
3603 .read(cx)
3604 .language_at(buffer_position)
3605 .map(|l| l.name()),
3606 buffer.read(cx).file(),
3607 cx,
3608 );
3609 if !settings.use_on_type_format {
3610 return None;
3611 }
3612
3613 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3614 // hence we do LSP request & edit on host side only — add formats to host's history.
3615 let push_to_lsp_host_history = true;
3616 // If this is not the host, append its history with new edits.
3617 let push_to_client_history = project.read(cx).is_via_collab();
3618
3619 let on_type_formatting = project.update(cx, |project, cx| {
3620 project.on_type_format(
3621 buffer.clone(),
3622 buffer_position,
3623 input,
3624 push_to_lsp_host_history,
3625 cx,
3626 )
3627 });
3628 Some(cx.spawn(|editor, mut cx| async move {
3629 if let Some(transaction) = on_type_formatting.await? {
3630 if push_to_client_history {
3631 buffer
3632 .update(&mut cx, |buffer, _| {
3633 buffer.push_transaction(transaction, Instant::now());
3634 })
3635 .ok();
3636 }
3637 editor.update(&mut cx, |editor, cx| {
3638 editor.refresh_document_highlights(cx);
3639 })?;
3640 }
3641 Ok(())
3642 }))
3643 }
3644
3645 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
3646 if self.pending_rename.is_some() {
3647 return;
3648 }
3649
3650 let Some(provider) = self.completion_provider.as_ref() else {
3651 return;
3652 };
3653
3654 if !self.snippet_stack.is_empty() && self.context_menu.read().as_ref().is_some() {
3655 return;
3656 }
3657
3658 let position = self.selections.newest_anchor().head();
3659 let (buffer, buffer_position) =
3660 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3661 output
3662 } else {
3663 return;
3664 };
3665 let show_completion_documentation = buffer
3666 .read(cx)
3667 .snapshot()
3668 .settings_at(buffer_position, cx)
3669 .show_completion_documentation;
3670
3671 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3672
3673 let aside_was_displayed = match self.context_menu.read().deref() {
3674 Some(CodeContextMenu::Completions(menu)) => menu.aside_was_displayed.get(),
3675 _ => false,
3676 };
3677 let trigger_kind = match &options.trigger {
3678 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3679 CompletionTriggerKind::TRIGGER_CHARACTER
3680 }
3681 _ => CompletionTriggerKind::INVOKED,
3682 };
3683 let completion_context = CompletionContext {
3684 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3685 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3686 Some(String::from(trigger))
3687 } else {
3688 None
3689 }
3690 }),
3691 trigger_kind,
3692 };
3693 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
3694 let sort_completions = provider.sort_completions();
3695
3696 let id = post_inc(&mut self.next_completion_id);
3697 let task = cx.spawn(|editor, mut cx| {
3698 async move {
3699 editor.update(&mut cx, |this, _| {
3700 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3701 })?;
3702 let completions = completions.await.log_err();
3703 let menu = if let Some(completions) = completions {
3704 let mut menu = CompletionsMenu::new(
3705 id,
3706 sort_completions,
3707 show_completion_documentation,
3708 position,
3709 buffer.clone(),
3710 completions.into(),
3711 aside_was_displayed,
3712 );
3713 menu.filter(query.as_deref(), cx.background_executor().clone())
3714 .await;
3715
3716 if menu.matches.is_empty() {
3717 None
3718 } else {
3719 Some(menu)
3720 }
3721 } else {
3722 None
3723 };
3724
3725 editor.update(&mut cx, |editor, cx| {
3726 let mut context_menu = editor.context_menu.write();
3727 match context_menu.as_ref() {
3728 None => {}
3729
3730 Some(CodeContextMenu::Completions(prev_menu)) => {
3731 if prev_menu.id > id {
3732 return;
3733 }
3734 }
3735
3736 _ => return,
3737 }
3738
3739 if editor.focus_handle.is_focused(cx) && menu.is_some() {
3740 let mut menu = menu.unwrap();
3741 menu.resolve_selected_completion(editor.completion_provider.as_deref(), cx);
3742 *context_menu = Some(CodeContextMenu::Completions(menu));
3743 drop(context_menu);
3744 cx.notify();
3745 } else if editor.completion_tasks.len() <= 1 {
3746 // If there are no more completion tasks and the last menu was
3747 // empty, we should hide it. If it was already hidden, we should
3748 // also show the copilot completion when available.
3749 drop(context_menu);
3750 editor.hide_context_menu(cx);
3751 }
3752 })?;
3753
3754 Ok::<_, anyhow::Error>(())
3755 }
3756 .log_err()
3757 });
3758
3759 self.completion_tasks.push((id, task));
3760 }
3761
3762 pub fn confirm_completion(
3763 &mut self,
3764 action: &ConfirmCompletion,
3765 cx: &mut ViewContext<Self>,
3766 ) -> Option<Task<Result<()>>> {
3767 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
3768 }
3769
3770 pub fn compose_completion(
3771 &mut self,
3772 action: &ComposeCompletion,
3773 cx: &mut ViewContext<Self>,
3774 ) -> Option<Task<Result<()>>> {
3775 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
3776 }
3777
3778 fn do_completion(
3779 &mut self,
3780 item_ix: Option<usize>,
3781 intent: CompletionIntent,
3782 cx: &mut ViewContext<Editor>,
3783 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3784 use language::ToOffset as _;
3785
3786 self.discard_inline_completion(true, cx);
3787 let completions_menu =
3788 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3789 menu
3790 } else {
3791 return None;
3792 };
3793
3794 let mat = completions_menu
3795 .matches
3796 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
3797 let buffer_handle = completions_menu.buffer;
3798 let completions = completions_menu.completions.read();
3799 let completion = completions.get(mat.candidate_id)?;
3800 cx.stop_propagation();
3801
3802 let snippet;
3803 let text;
3804
3805 if completion.is_snippet() {
3806 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3807 text = snippet.as_ref().unwrap().text.clone();
3808 } else {
3809 snippet = None;
3810 text = completion.new_text.clone();
3811 };
3812 let selections = self.selections.all::<usize>(cx);
3813 let buffer = buffer_handle.read(cx);
3814 let old_range = completion.old_range.to_offset(buffer);
3815 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3816
3817 let newest_selection = self.selections.newest_anchor();
3818 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3819 return None;
3820 }
3821
3822 let lookbehind = newest_selection
3823 .start
3824 .text_anchor
3825 .to_offset(buffer)
3826 .saturating_sub(old_range.start);
3827 let lookahead = old_range
3828 .end
3829 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3830 let mut common_prefix_len = old_text
3831 .bytes()
3832 .zip(text.bytes())
3833 .take_while(|(a, b)| a == b)
3834 .count();
3835
3836 let snapshot = self.buffer.read(cx).snapshot(cx);
3837 let mut range_to_replace: Option<Range<isize>> = None;
3838 let mut ranges = Vec::new();
3839 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3840 for selection in &selections {
3841 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3842 let start = selection.start.saturating_sub(lookbehind);
3843 let end = selection.end + lookahead;
3844 if selection.id == newest_selection.id {
3845 range_to_replace = Some(
3846 ((start + common_prefix_len) as isize - selection.start as isize)
3847 ..(end as isize - selection.start as isize),
3848 );
3849 }
3850 ranges.push(start + common_prefix_len..end);
3851 } else {
3852 common_prefix_len = 0;
3853 ranges.clear();
3854 ranges.extend(selections.iter().map(|s| {
3855 if s.id == newest_selection.id {
3856 range_to_replace = Some(
3857 old_range.start.to_offset_utf16(&snapshot).0 as isize
3858 - selection.start as isize
3859 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3860 - selection.start as isize,
3861 );
3862 old_range.clone()
3863 } else {
3864 s.start..s.end
3865 }
3866 }));
3867 break;
3868 }
3869 if !self.linked_edit_ranges.is_empty() {
3870 let start_anchor = snapshot.anchor_before(selection.head());
3871 let end_anchor = snapshot.anchor_after(selection.tail());
3872 if let Some(ranges) = self
3873 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
3874 {
3875 for (buffer, edits) in ranges {
3876 linked_edits.entry(buffer.clone()).or_default().extend(
3877 edits
3878 .into_iter()
3879 .map(|range| (range, text[common_prefix_len..].to_owned())),
3880 );
3881 }
3882 }
3883 }
3884 }
3885 let text = &text[common_prefix_len..];
3886
3887 cx.emit(EditorEvent::InputHandled {
3888 utf16_range_to_replace: range_to_replace,
3889 text: text.into(),
3890 });
3891
3892 self.transact(cx, |this, cx| {
3893 if let Some(mut snippet) = snippet {
3894 snippet.text = text.to_string();
3895 for tabstop in snippet
3896 .tabstops
3897 .iter_mut()
3898 .flat_map(|tabstop| tabstop.ranges.iter_mut())
3899 {
3900 tabstop.start -= common_prefix_len as isize;
3901 tabstop.end -= common_prefix_len as isize;
3902 }
3903
3904 this.insert_snippet(&ranges, snippet, cx).log_err();
3905 } else {
3906 this.buffer.update(cx, |buffer, cx| {
3907 buffer.edit(
3908 ranges.iter().map(|range| (range.clone(), text)),
3909 this.autoindent_mode.clone(),
3910 cx,
3911 );
3912 });
3913 }
3914 for (buffer, edits) in linked_edits {
3915 buffer.update(cx, |buffer, cx| {
3916 let snapshot = buffer.snapshot();
3917 let edits = edits
3918 .into_iter()
3919 .map(|(range, text)| {
3920 use text::ToPoint as TP;
3921 let end_point = TP::to_point(&range.end, &snapshot);
3922 let start_point = TP::to_point(&range.start, &snapshot);
3923 (start_point..end_point, text)
3924 })
3925 .sorted_by_key(|(range, _)| range.start)
3926 .collect::<Vec<_>>();
3927 buffer.edit(edits, None, cx);
3928 })
3929 }
3930
3931 this.refresh_inline_completion(true, false, cx);
3932 });
3933
3934 let show_new_completions_on_confirm = completion
3935 .confirm
3936 .as_ref()
3937 .map_or(false, |confirm| confirm(intent, cx));
3938 if show_new_completions_on_confirm {
3939 self.show_completions(&ShowCompletions { trigger: None }, cx);
3940 }
3941
3942 let provider = self.completion_provider.as_ref()?;
3943 let apply_edits = provider.apply_additional_edits_for_completion(
3944 buffer_handle,
3945 completion.clone(),
3946 true,
3947 cx,
3948 );
3949
3950 let editor_settings = EditorSettings::get_global(cx);
3951 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
3952 // After the code completion is finished, users often want to know what signatures are needed.
3953 // so we should automatically call signature_help
3954 self.show_signature_help(&ShowSignatureHelp, cx);
3955 }
3956
3957 Some(cx.foreground_executor().spawn(async move {
3958 apply_edits.await?;
3959 Ok(())
3960 }))
3961 }
3962
3963 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
3964 let mut context_menu = self.context_menu.write();
3965 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
3966 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
3967 // Toggle if we're selecting the same one
3968 *context_menu = None;
3969 cx.notify();
3970 return;
3971 } else {
3972 // Otherwise, clear it and start a new one
3973 *context_menu = None;
3974 cx.notify();
3975 }
3976 }
3977 drop(context_menu);
3978 let snapshot = self.snapshot(cx);
3979 let deployed_from_indicator = action.deployed_from_indicator;
3980 let mut task = self.code_actions_task.take();
3981 let action = action.clone();
3982 cx.spawn(|editor, mut cx| async move {
3983 while let Some(prev_task) = task {
3984 prev_task.await.log_err();
3985 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
3986 }
3987
3988 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
3989 if editor.focus_handle.is_focused(cx) {
3990 let multibuffer_point = action
3991 .deployed_from_indicator
3992 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
3993 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
3994 let (buffer, buffer_row) = snapshot
3995 .buffer_snapshot
3996 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
3997 .and_then(|(buffer_snapshot, range)| {
3998 editor
3999 .buffer
4000 .read(cx)
4001 .buffer(buffer_snapshot.remote_id())
4002 .map(|buffer| (buffer, range.start.row))
4003 })?;
4004 let (_, code_actions) = editor
4005 .available_code_actions
4006 .clone()
4007 .and_then(|(location, code_actions)| {
4008 let snapshot = location.buffer.read(cx).snapshot();
4009 let point_range = location.range.to_point(&snapshot);
4010 let point_range = point_range.start.row..=point_range.end.row;
4011 if point_range.contains(&buffer_row) {
4012 Some((location, code_actions))
4013 } else {
4014 None
4015 }
4016 })
4017 .unzip();
4018 let buffer_id = buffer.read(cx).remote_id();
4019 let tasks = editor
4020 .tasks
4021 .get(&(buffer_id, buffer_row))
4022 .map(|t| Arc::new(t.to_owned()));
4023 if tasks.is_none() && code_actions.is_none() {
4024 return None;
4025 }
4026
4027 editor.completion_tasks.clear();
4028 editor.discard_inline_completion(false, cx);
4029 let task_context =
4030 tasks
4031 .as_ref()
4032 .zip(editor.project.clone())
4033 .map(|(tasks, project)| {
4034 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4035 });
4036
4037 Some(cx.spawn(|editor, mut cx| async move {
4038 let task_context = match task_context {
4039 Some(task_context) => task_context.await,
4040 None => None,
4041 };
4042 let resolved_tasks =
4043 tasks.zip(task_context).map(|(tasks, task_context)| {
4044 Arc::new(ResolvedTasks {
4045 templates: tasks.resolve(&task_context).collect(),
4046 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4047 multibuffer_point.row,
4048 tasks.column,
4049 )),
4050 })
4051 });
4052 let spawn_straight_away = resolved_tasks
4053 .as_ref()
4054 .map_or(false, |tasks| tasks.templates.len() == 1)
4055 && code_actions
4056 .as_ref()
4057 .map_or(true, |actions| actions.is_empty());
4058 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4059 *editor.context_menu.write() =
4060 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4061 buffer,
4062 actions: CodeActionContents {
4063 tasks: resolved_tasks,
4064 actions: code_actions,
4065 },
4066 selected_item: Default::default(),
4067 scroll_handle: UniformListScrollHandle::default(),
4068 deployed_from_indicator,
4069 }));
4070 if spawn_straight_away {
4071 if let Some(task) = editor.confirm_code_action(
4072 &ConfirmCodeAction { item_ix: Some(0) },
4073 cx,
4074 ) {
4075 cx.notify();
4076 return task;
4077 }
4078 }
4079 cx.notify();
4080 Task::ready(Ok(()))
4081 }) {
4082 task.await
4083 } else {
4084 Ok(())
4085 }
4086 }))
4087 } else {
4088 Some(Task::ready(Ok(())))
4089 }
4090 })?;
4091 if let Some(task) = spawned_test_task {
4092 task.await?;
4093 }
4094
4095 Ok::<_, anyhow::Error>(())
4096 })
4097 .detach_and_log_err(cx);
4098 }
4099
4100 pub fn confirm_code_action(
4101 &mut self,
4102 action: &ConfirmCodeAction,
4103 cx: &mut ViewContext<Self>,
4104 ) -> Option<Task<Result<()>>> {
4105 let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4106 menu
4107 } else {
4108 return None;
4109 };
4110 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4111 let action = actions_menu.actions.get(action_ix)?;
4112 let title = action.label();
4113 let buffer = actions_menu.buffer;
4114 let workspace = self.workspace()?;
4115
4116 match action {
4117 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4118 workspace.update(cx, |workspace, cx| {
4119 workspace::tasks::schedule_resolved_task(
4120 workspace,
4121 task_source_kind,
4122 resolved_task,
4123 false,
4124 cx,
4125 );
4126
4127 Some(Task::ready(Ok(())))
4128 })
4129 }
4130 CodeActionsItem::CodeAction {
4131 excerpt_id,
4132 action,
4133 provider,
4134 } => {
4135 let apply_code_action =
4136 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4137 let workspace = workspace.downgrade();
4138 Some(cx.spawn(|editor, cx| async move {
4139 let project_transaction = apply_code_action.await?;
4140 Self::open_project_transaction(
4141 &editor,
4142 workspace,
4143 project_transaction,
4144 title,
4145 cx,
4146 )
4147 .await
4148 }))
4149 }
4150 }
4151 }
4152
4153 pub async fn open_project_transaction(
4154 this: &WeakView<Editor>,
4155 workspace: WeakView<Workspace>,
4156 transaction: ProjectTransaction,
4157 title: String,
4158 mut cx: AsyncWindowContext,
4159 ) -> Result<()> {
4160 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4161 cx.update(|cx| {
4162 entries.sort_unstable_by_key(|(buffer, _)| {
4163 buffer.read(cx).file().map(|f| f.path().clone())
4164 });
4165 })?;
4166
4167 // If the project transaction's edits are all contained within this editor, then
4168 // avoid opening a new editor to display them.
4169
4170 if let Some((buffer, transaction)) = entries.first() {
4171 if entries.len() == 1 {
4172 let excerpt = this.update(&mut cx, |editor, cx| {
4173 editor
4174 .buffer()
4175 .read(cx)
4176 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4177 })?;
4178 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4179 if excerpted_buffer == *buffer {
4180 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4181 let excerpt_range = excerpt_range.to_offset(buffer);
4182 buffer
4183 .edited_ranges_for_transaction::<usize>(transaction)
4184 .all(|range| {
4185 excerpt_range.start <= range.start
4186 && excerpt_range.end >= range.end
4187 })
4188 })?;
4189
4190 if all_edits_within_excerpt {
4191 return Ok(());
4192 }
4193 }
4194 }
4195 }
4196 } else {
4197 return Ok(());
4198 }
4199
4200 let mut ranges_to_highlight = Vec::new();
4201 let excerpt_buffer = cx.new_model(|cx| {
4202 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4203 for (buffer_handle, transaction) in &entries {
4204 let buffer = buffer_handle.read(cx);
4205 ranges_to_highlight.extend(
4206 multibuffer.push_excerpts_with_context_lines(
4207 buffer_handle.clone(),
4208 buffer
4209 .edited_ranges_for_transaction::<usize>(transaction)
4210 .collect(),
4211 DEFAULT_MULTIBUFFER_CONTEXT,
4212 cx,
4213 ),
4214 );
4215 }
4216 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4217 multibuffer
4218 })?;
4219
4220 workspace.update(&mut cx, |workspace, cx| {
4221 let project = workspace.project().clone();
4222 let editor =
4223 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4224 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4225 editor.update(cx, |editor, cx| {
4226 editor.highlight_background::<Self>(
4227 &ranges_to_highlight,
4228 |theme| theme.editor_highlighted_line_background,
4229 cx,
4230 );
4231 });
4232 })?;
4233
4234 Ok(())
4235 }
4236
4237 pub fn clear_code_action_providers(&mut self) {
4238 self.code_action_providers.clear();
4239 self.available_code_actions.take();
4240 }
4241
4242 pub fn push_code_action_provider(
4243 &mut self,
4244 provider: Arc<dyn CodeActionProvider>,
4245 cx: &mut ViewContext<Self>,
4246 ) {
4247 self.code_action_providers.push(provider);
4248 self.refresh_code_actions(cx);
4249 }
4250
4251 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4252 let buffer = self.buffer.read(cx);
4253 let newest_selection = self.selections.newest_anchor().clone();
4254 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4255 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4256 if start_buffer != end_buffer {
4257 return None;
4258 }
4259
4260 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4261 cx.background_executor()
4262 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4263 .await;
4264
4265 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4266 let providers = this.code_action_providers.clone();
4267 let tasks = this
4268 .code_action_providers
4269 .iter()
4270 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4271 .collect::<Vec<_>>();
4272 (providers, tasks)
4273 })?;
4274
4275 let mut actions = Vec::new();
4276 for (provider, provider_actions) in
4277 providers.into_iter().zip(future::join_all(tasks).await)
4278 {
4279 if let Some(provider_actions) = provider_actions.log_err() {
4280 actions.extend(provider_actions.into_iter().map(|action| {
4281 AvailableCodeAction {
4282 excerpt_id: newest_selection.start.excerpt_id,
4283 action,
4284 provider: provider.clone(),
4285 }
4286 }));
4287 }
4288 }
4289
4290 this.update(&mut cx, |this, cx| {
4291 this.available_code_actions = if actions.is_empty() {
4292 None
4293 } else {
4294 Some((
4295 Location {
4296 buffer: start_buffer,
4297 range: start..end,
4298 },
4299 actions.into(),
4300 ))
4301 };
4302 cx.notify();
4303 })
4304 }));
4305 None
4306 }
4307
4308 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4309 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4310 self.show_git_blame_inline = false;
4311
4312 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4313 cx.background_executor().timer(delay).await;
4314
4315 this.update(&mut cx, |this, cx| {
4316 this.show_git_blame_inline = true;
4317 cx.notify();
4318 })
4319 .log_err();
4320 }));
4321 }
4322 }
4323
4324 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4325 if self.pending_rename.is_some() {
4326 return None;
4327 }
4328
4329 let provider = self.semantics_provider.clone()?;
4330 let buffer = self.buffer.read(cx);
4331 let newest_selection = self.selections.newest_anchor().clone();
4332 let cursor_position = newest_selection.head();
4333 let (cursor_buffer, cursor_buffer_position) =
4334 buffer.text_anchor_for_position(cursor_position, cx)?;
4335 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4336 if cursor_buffer != tail_buffer {
4337 return None;
4338 }
4339 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4340 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4341 cx.background_executor()
4342 .timer(Duration::from_millis(debounce))
4343 .await;
4344
4345 let highlights = if let Some(highlights) = cx
4346 .update(|cx| {
4347 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4348 })
4349 .ok()
4350 .flatten()
4351 {
4352 highlights.await.log_err()
4353 } else {
4354 None
4355 };
4356
4357 if let Some(highlights) = highlights {
4358 this.update(&mut cx, |this, cx| {
4359 if this.pending_rename.is_some() {
4360 return;
4361 }
4362
4363 let buffer_id = cursor_position.buffer_id;
4364 let buffer = this.buffer.read(cx);
4365 if !buffer
4366 .text_anchor_for_position(cursor_position, cx)
4367 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4368 {
4369 return;
4370 }
4371
4372 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4373 let mut write_ranges = Vec::new();
4374 let mut read_ranges = Vec::new();
4375 for highlight in highlights {
4376 for (excerpt_id, excerpt_range) in
4377 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4378 {
4379 let start = highlight
4380 .range
4381 .start
4382 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4383 let end = highlight
4384 .range
4385 .end
4386 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4387 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4388 continue;
4389 }
4390
4391 let range = Anchor {
4392 buffer_id,
4393 excerpt_id,
4394 text_anchor: start,
4395 }..Anchor {
4396 buffer_id,
4397 excerpt_id,
4398 text_anchor: end,
4399 };
4400 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4401 write_ranges.push(range);
4402 } else {
4403 read_ranges.push(range);
4404 }
4405 }
4406 }
4407
4408 this.highlight_background::<DocumentHighlightRead>(
4409 &read_ranges,
4410 |theme| theme.editor_document_highlight_read_background,
4411 cx,
4412 );
4413 this.highlight_background::<DocumentHighlightWrite>(
4414 &write_ranges,
4415 |theme| theme.editor_document_highlight_write_background,
4416 cx,
4417 );
4418 cx.notify();
4419 })
4420 .log_err();
4421 }
4422 }));
4423 None
4424 }
4425
4426 pub fn refresh_inline_completion(
4427 &mut self,
4428 debounce: bool,
4429 user_requested: bool,
4430 cx: &mut ViewContext<Self>,
4431 ) -> Option<()> {
4432 let provider = self.inline_completion_provider()?;
4433 let cursor = self.selections.newest_anchor().head();
4434 let (buffer, cursor_buffer_position) =
4435 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4436
4437 if !user_requested
4438 && (!self.enable_inline_completions
4439 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4440 || !self.is_focused(cx))
4441 {
4442 self.discard_inline_completion(false, cx);
4443 return None;
4444 }
4445
4446 self.update_visible_inline_completion(cx);
4447 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4448 Some(())
4449 }
4450
4451 fn cycle_inline_completion(
4452 &mut self,
4453 direction: Direction,
4454 cx: &mut ViewContext<Self>,
4455 ) -> Option<()> {
4456 let provider = self.inline_completion_provider()?;
4457 let cursor = self.selections.newest_anchor().head();
4458 let (buffer, cursor_buffer_position) =
4459 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4460 if !self.enable_inline_completions
4461 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4462 {
4463 return None;
4464 }
4465
4466 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4467 self.update_visible_inline_completion(cx);
4468
4469 Some(())
4470 }
4471
4472 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4473 if !self.has_active_inline_completion() {
4474 self.refresh_inline_completion(false, true, cx);
4475 return;
4476 }
4477
4478 self.update_visible_inline_completion(cx);
4479 }
4480
4481 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4482 self.show_cursor_names(cx);
4483 }
4484
4485 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4486 self.show_cursor_names = true;
4487 cx.notify();
4488 cx.spawn(|this, mut cx| async move {
4489 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4490 this.update(&mut cx, |this, cx| {
4491 this.show_cursor_names = false;
4492 cx.notify()
4493 })
4494 .ok()
4495 })
4496 .detach();
4497 }
4498
4499 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4500 if self.has_active_inline_completion() {
4501 self.cycle_inline_completion(Direction::Next, cx);
4502 } else {
4503 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4504 if is_copilot_disabled {
4505 cx.propagate();
4506 }
4507 }
4508 }
4509
4510 pub fn previous_inline_completion(
4511 &mut self,
4512 _: &PreviousInlineCompletion,
4513 cx: &mut ViewContext<Self>,
4514 ) {
4515 if self.has_active_inline_completion() {
4516 self.cycle_inline_completion(Direction::Prev, cx);
4517 } else {
4518 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4519 if is_copilot_disabled {
4520 cx.propagate();
4521 }
4522 }
4523 }
4524
4525 pub fn accept_inline_completion(
4526 &mut self,
4527 _: &AcceptInlineCompletion,
4528 cx: &mut ViewContext<Self>,
4529 ) {
4530 self.hide_context_menu(cx);
4531
4532 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4533 return;
4534 };
4535
4536 self.report_inline_completion_event(true, cx);
4537
4538 match &active_inline_completion.completion {
4539 InlineCompletion::Move(position) => {
4540 let position = *position;
4541 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4542 selections.select_anchor_ranges([position..position]);
4543 });
4544 }
4545 InlineCompletion::Edit(edits) => {
4546 if let Some(provider) = self.inline_completion_provider() {
4547 provider.accept(cx);
4548 }
4549
4550 let snapshot = self.buffer.read(cx).snapshot(cx);
4551 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4552
4553 self.buffer.update(cx, |buffer, cx| {
4554 buffer.edit(edits.iter().cloned(), None, cx)
4555 });
4556
4557 self.change_selections(None, cx, |s| {
4558 s.select_anchor_ranges([last_edit_end..last_edit_end])
4559 });
4560
4561 self.update_visible_inline_completion(cx);
4562 if self.active_inline_completion.is_none() {
4563 self.refresh_inline_completion(true, true, cx);
4564 }
4565
4566 cx.notify();
4567 }
4568 }
4569 }
4570
4571 pub fn accept_partial_inline_completion(
4572 &mut self,
4573 _: &AcceptPartialInlineCompletion,
4574 cx: &mut ViewContext<Self>,
4575 ) {
4576 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4577 return;
4578 };
4579 if self.selections.count() != 1 {
4580 return;
4581 }
4582
4583 self.report_inline_completion_event(true, cx);
4584
4585 match &active_inline_completion.completion {
4586 InlineCompletion::Move(position) => {
4587 let position = *position;
4588 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4589 selections.select_anchor_ranges([position..position]);
4590 });
4591 }
4592 InlineCompletion::Edit(edits) => {
4593 if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
4594 let text = edits[0].1.as_str();
4595 let mut partial_completion = text
4596 .chars()
4597 .by_ref()
4598 .take_while(|c| c.is_alphabetic())
4599 .collect::<String>();
4600 if partial_completion.is_empty() {
4601 partial_completion = text
4602 .chars()
4603 .by_ref()
4604 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4605 .collect::<String>();
4606 }
4607
4608 cx.emit(EditorEvent::InputHandled {
4609 utf16_range_to_replace: None,
4610 text: partial_completion.clone().into(),
4611 });
4612
4613 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4614
4615 self.refresh_inline_completion(true, true, cx);
4616 cx.notify();
4617 }
4618 }
4619 }
4620 }
4621
4622 fn discard_inline_completion(
4623 &mut self,
4624 should_report_inline_completion_event: bool,
4625 cx: &mut ViewContext<Self>,
4626 ) -> bool {
4627 if should_report_inline_completion_event {
4628 self.report_inline_completion_event(false, cx);
4629 }
4630
4631 if let Some(provider) = self.inline_completion_provider() {
4632 provider.discard(cx);
4633 }
4634
4635 self.take_active_inline_completion(cx).is_some()
4636 }
4637
4638 fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
4639 let Some(provider) = self.inline_completion_provider() else {
4640 return;
4641 };
4642 let Some(project) = self.project.as_ref() else {
4643 return;
4644 };
4645 let Some((_, buffer, _)) = self
4646 .buffer
4647 .read(cx)
4648 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4649 else {
4650 return;
4651 };
4652
4653 let project = project.read(cx);
4654 let extension = buffer
4655 .read(cx)
4656 .file()
4657 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4658 project.client().telemetry().report_inline_completion_event(
4659 provider.name().into(),
4660 accepted,
4661 extension,
4662 );
4663 }
4664
4665 pub fn has_active_inline_completion(&self) -> bool {
4666 self.active_inline_completion.is_some()
4667 }
4668
4669 fn take_active_inline_completion(
4670 &mut self,
4671 cx: &mut ViewContext<Self>,
4672 ) -> Option<InlineCompletion> {
4673 let active_inline_completion = self.active_inline_completion.take()?;
4674 self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
4675 self.clear_highlights::<InlineCompletionHighlight>(cx);
4676 Some(active_inline_completion.completion)
4677 }
4678
4679 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4680 let selection = self.selections.newest_anchor();
4681 let cursor = selection.head();
4682 let multibuffer = self.buffer.read(cx).snapshot(cx);
4683 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
4684 let excerpt_id = cursor.excerpt_id;
4685
4686 if !offset_selection.is_empty()
4687 || self
4688 .active_inline_completion
4689 .as_ref()
4690 .map_or(false, |completion| {
4691 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
4692 let invalidation_range = invalidation_range.start..=invalidation_range.end;
4693 !invalidation_range.contains(&offset_selection.head())
4694 })
4695 {
4696 self.discard_inline_completion(false, cx);
4697 return None;
4698 }
4699
4700 self.take_active_inline_completion(cx);
4701 let provider = self.inline_completion_provider()?;
4702
4703 let (buffer, cursor_buffer_position) =
4704 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4705
4706 let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
4707 let edits = completion
4708 .edits
4709 .into_iter()
4710 .map(|(range, new_text)| {
4711 (
4712 multibuffer
4713 .anchor_in_excerpt(excerpt_id, range.start)
4714 .unwrap()
4715 ..multibuffer
4716 .anchor_in_excerpt(excerpt_id, range.end)
4717 .unwrap(),
4718 new_text,
4719 )
4720 })
4721 .collect::<Vec<_>>();
4722 if edits.is_empty() {
4723 return None;
4724 }
4725
4726 let first_edit_start = edits.first().unwrap().0.start;
4727 let edit_start_row = first_edit_start
4728 .to_point(&multibuffer)
4729 .row
4730 .saturating_sub(2);
4731
4732 let last_edit_end = edits.last().unwrap().0.end;
4733 let edit_end_row = cmp::min(
4734 multibuffer.max_point().row,
4735 last_edit_end.to_point(&multibuffer).row + 2,
4736 );
4737
4738 let cursor_row = cursor.to_point(&multibuffer).row;
4739
4740 let mut inlay_ids = Vec::new();
4741 let invalidation_row_range;
4742 let completion;
4743 if cursor_row < edit_start_row {
4744 invalidation_row_range = cursor_row..edit_end_row;
4745 completion = InlineCompletion::Move(first_edit_start);
4746 } else if cursor_row > edit_end_row {
4747 invalidation_row_range = edit_start_row..cursor_row;
4748 completion = InlineCompletion::Move(first_edit_start);
4749 } else {
4750 if edits
4751 .iter()
4752 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
4753 {
4754 let mut inlays = Vec::new();
4755 for (range, new_text) in &edits {
4756 let inlay = Inlay::inline_completion(
4757 post_inc(&mut self.next_inlay_id),
4758 range.start,
4759 new_text.as_str(),
4760 );
4761 inlay_ids.push(inlay.id);
4762 inlays.push(inlay);
4763 }
4764
4765 self.splice_inlays(vec![], inlays, cx);
4766 } else {
4767 let background_color = cx.theme().status().deleted_background;
4768 self.highlight_text::<InlineCompletionHighlight>(
4769 edits.iter().map(|(range, _)| range.clone()).collect(),
4770 HighlightStyle {
4771 background_color: Some(background_color),
4772 ..Default::default()
4773 },
4774 cx,
4775 );
4776 }
4777
4778 invalidation_row_range = edit_start_row..edit_end_row;
4779 completion = InlineCompletion::Edit(edits);
4780 };
4781
4782 let invalidation_range = multibuffer
4783 .anchor_before(Point::new(invalidation_row_range.start, 0))
4784 ..multibuffer.anchor_after(Point::new(
4785 invalidation_row_range.end,
4786 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
4787 ));
4788
4789 self.active_inline_completion = Some(InlineCompletionState {
4790 inlay_ids,
4791 completion,
4792 invalidation_range,
4793 });
4794 cx.notify();
4795
4796 Some(())
4797 }
4798
4799 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
4800 Some(self.inline_completion_provider.as_ref()?.provider.clone())
4801 }
4802
4803 fn render_code_actions_indicator(
4804 &self,
4805 _style: &EditorStyle,
4806 row: DisplayRow,
4807 is_active: bool,
4808 cx: &mut ViewContext<Self>,
4809 ) -> Option<IconButton> {
4810 if self.available_code_actions.is_some() {
4811 Some(
4812 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
4813 .shape(ui::IconButtonShape::Square)
4814 .icon_size(IconSize::XSmall)
4815 .icon_color(Color::Muted)
4816 .toggle_state(is_active)
4817 .tooltip({
4818 let focus_handle = self.focus_handle.clone();
4819 move |cx| {
4820 Tooltip::for_action_in(
4821 "Toggle Code Actions",
4822 &ToggleCodeActions {
4823 deployed_from_indicator: None,
4824 },
4825 &focus_handle,
4826 cx,
4827 )
4828 }
4829 })
4830 .on_click(cx.listener(move |editor, _e, cx| {
4831 editor.focus(cx);
4832 editor.toggle_code_actions(
4833 &ToggleCodeActions {
4834 deployed_from_indicator: Some(row),
4835 },
4836 cx,
4837 );
4838 })),
4839 )
4840 } else {
4841 None
4842 }
4843 }
4844
4845 fn clear_tasks(&mut self) {
4846 self.tasks.clear()
4847 }
4848
4849 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
4850 if self.tasks.insert(key, value).is_some() {
4851 // This case should hopefully be rare, but just in case...
4852 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
4853 }
4854 }
4855
4856 fn build_tasks_context(
4857 project: &Model<Project>,
4858 buffer: &Model<Buffer>,
4859 buffer_row: u32,
4860 tasks: &Arc<RunnableTasks>,
4861 cx: &mut ViewContext<Self>,
4862 ) -> Task<Option<task::TaskContext>> {
4863 let position = Point::new(buffer_row, tasks.column);
4864 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4865 let location = Location {
4866 buffer: buffer.clone(),
4867 range: range_start..range_start,
4868 };
4869 // Fill in the environmental variables from the tree-sitter captures
4870 let mut captured_task_variables = TaskVariables::default();
4871 for (capture_name, value) in tasks.extra_variables.clone() {
4872 captured_task_variables.insert(
4873 task::VariableName::Custom(capture_name.into()),
4874 value.clone(),
4875 );
4876 }
4877 project.update(cx, |project, cx| {
4878 project.task_store().update(cx, |task_store, cx| {
4879 task_store.task_context_for_location(captured_task_variables, location, cx)
4880 })
4881 })
4882 }
4883
4884 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
4885 let Some((workspace, _)) = self.workspace.clone() else {
4886 return;
4887 };
4888 let Some(project) = self.project.clone() else {
4889 return;
4890 };
4891
4892 // Try to find a closest, enclosing node using tree-sitter that has a
4893 // task
4894 let Some((buffer, buffer_row, tasks)) = self
4895 .find_enclosing_node_task(cx)
4896 // Or find the task that's closest in row-distance.
4897 .or_else(|| self.find_closest_task(cx))
4898 else {
4899 return;
4900 };
4901
4902 let reveal_strategy = action.reveal;
4903 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
4904 cx.spawn(|_, mut cx| async move {
4905 let context = task_context.await?;
4906 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
4907
4908 let resolved = resolved_task.resolved.as_mut()?;
4909 resolved.reveal = reveal_strategy;
4910
4911 workspace
4912 .update(&mut cx, |workspace, cx| {
4913 workspace::tasks::schedule_resolved_task(
4914 workspace,
4915 task_source_kind,
4916 resolved_task,
4917 false,
4918 cx,
4919 );
4920 })
4921 .ok()
4922 })
4923 .detach();
4924 }
4925
4926 fn find_closest_task(
4927 &mut self,
4928 cx: &mut ViewContext<Self>,
4929 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
4930 let cursor_row = self.selections.newest_adjusted(cx).head().row;
4931
4932 let ((buffer_id, row), tasks) = self
4933 .tasks
4934 .iter()
4935 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
4936
4937 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
4938 let tasks = Arc::new(tasks.to_owned());
4939 Some((buffer, *row, tasks))
4940 }
4941
4942 fn find_enclosing_node_task(
4943 &mut self,
4944 cx: &mut ViewContext<Self>,
4945 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
4946 let snapshot = self.buffer.read(cx).snapshot(cx);
4947 let offset = self.selections.newest::<usize>(cx).head();
4948 let excerpt = snapshot.excerpt_containing(offset..offset)?;
4949 let buffer_id = excerpt.buffer().remote_id();
4950
4951 let layer = excerpt.buffer().syntax_layer_at(offset)?;
4952 let mut cursor = layer.node().walk();
4953
4954 while cursor.goto_first_child_for_byte(offset).is_some() {
4955 if cursor.node().end_byte() == offset {
4956 cursor.goto_next_sibling();
4957 }
4958 }
4959
4960 // Ascend to the smallest ancestor that contains the range and has a task.
4961 loop {
4962 let node = cursor.node();
4963 let node_range = node.byte_range();
4964 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
4965
4966 // Check if this node contains our offset
4967 if node_range.start <= offset && node_range.end >= offset {
4968 // If it contains offset, check for task
4969 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
4970 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
4971 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
4972 }
4973 }
4974
4975 if !cursor.goto_parent() {
4976 break;
4977 }
4978 }
4979 None
4980 }
4981
4982 fn render_run_indicator(
4983 &self,
4984 _style: &EditorStyle,
4985 is_active: bool,
4986 row: DisplayRow,
4987 cx: &mut ViewContext<Self>,
4988 ) -> IconButton {
4989 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
4990 .shape(ui::IconButtonShape::Square)
4991 .icon_size(IconSize::XSmall)
4992 .icon_color(Color::Muted)
4993 .toggle_state(is_active)
4994 .on_click(cx.listener(move |editor, _e, cx| {
4995 editor.focus(cx);
4996 editor.toggle_code_actions(
4997 &ToggleCodeActions {
4998 deployed_from_indicator: Some(row),
4999 },
5000 cx,
5001 );
5002 }))
5003 }
5004
5005 pub fn context_menu_visible(&self) -> bool {
5006 self.context_menu
5007 .read()
5008 .as_ref()
5009 .map_or(false, |menu| menu.visible())
5010 }
5011
5012 fn render_context_menu(
5013 &self,
5014 cursor_position: DisplayPoint,
5015 style: &EditorStyle,
5016 max_height: Pixels,
5017 cx: &mut ViewContext<Editor>,
5018 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5019 self.context_menu.read().as_ref().map(|menu| {
5020 menu.render(
5021 cursor_position,
5022 style,
5023 max_height,
5024 self.workspace.as_ref().map(|(w, _)| w.clone()),
5025 cx,
5026 )
5027 })
5028 }
5029
5030 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
5031 cx.notify();
5032 self.completion_tasks.clear();
5033 self.context_menu.write().take()
5034 }
5035
5036 fn show_snippet_choices(
5037 &mut self,
5038 choices: &Vec<String>,
5039 selection: Range<Anchor>,
5040 cx: &mut ViewContext<Self>,
5041 ) {
5042 if selection.start.buffer_id.is_none() {
5043 return;
5044 }
5045 let buffer_id = selection.start.buffer_id.unwrap();
5046 let buffer = self.buffer().read(cx).buffer(buffer_id);
5047 let id = post_inc(&mut self.next_completion_id);
5048
5049 if let Some(buffer) = buffer {
5050 *self.context_menu.write() = Some(CodeContextMenu::Completions(
5051 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5052 ));
5053 }
5054 }
5055
5056 pub fn insert_snippet(
5057 &mut self,
5058 insertion_ranges: &[Range<usize>],
5059 snippet: Snippet,
5060 cx: &mut ViewContext<Self>,
5061 ) -> Result<()> {
5062 struct Tabstop<T> {
5063 is_end_tabstop: bool,
5064 ranges: Vec<Range<T>>,
5065 choices: Option<Vec<String>>,
5066 }
5067
5068 let tabstops = self.buffer.update(cx, |buffer, cx| {
5069 let snippet_text: Arc<str> = snippet.text.clone().into();
5070 buffer.edit(
5071 insertion_ranges
5072 .iter()
5073 .cloned()
5074 .map(|range| (range, snippet_text.clone())),
5075 Some(AutoindentMode::EachLine),
5076 cx,
5077 );
5078
5079 let snapshot = &*buffer.read(cx);
5080 let snippet = &snippet;
5081 snippet
5082 .tabstops
5083 .iter()
5084 .map(|tabstop| {
5085 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5086 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5087 });
5088 let mut tabstop_ranges = tabstop
5089 .ranges
5090 .iter()
5091 .flat_map(|tabstop_range| {
5092 let mut delta = 0_isize;
5093 insertion_ranges.iter().map(move |insertion_range| {
5094 let insertion_start = insertion_range.start as isize + delta;
5095 delta +=
5096 snippet.text.len() as isize - insertion_range.len() as isize;
5097
5098 let start = ((insertion_start + tabstop_range.start) as usize)
5099 .min(snapshot.len());
5100 let end = ((insertion_start + tabstop_range.end) as usize)
5101 .min(snapshot.len());
5102 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5103 })
5104 })
5105 .collect::<Vec<_>>();
5106 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5107
5108 Tabstop {
5109 is_end_tabstop,
5110 ranges: tabstop_ranges,
5111 choices: tabstop.choices.clone(),
5112 }
5113 })
5114 .collect::<Vec<_>>()
5115 });
5116 if let Some(tabstop) = tabstops.first() {
5117 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5118 s.select_ranges(tabstop.ranges.iter().cloned());
5119 });
5120
5121 if let Some(choices) = &tabstop.choices {
5122 if let Some(selection) = tabstop.ranges.first() {
5123 self.show_snippet_choices(choices, selection.clone(), cx)
5124 }
5125 }
5126
5127 // If we're already at the last tabstop and it's at the end of the snippet,
5128 // we're done, we don't need to keep the state around.
5129 if !tabstop.is_end_tabstop {
5130 let choices = tabstops
5131 .iter()
5132 .map(|tabstop| tabstop.choices.clone())
5133 .collect();
5134
5135 let ranges = tabstops
5136 .into_iter()
5137 .map(|tabstop| tabstop.ranges)
5138 .collect::<Vec<_>>();
5139
5140 self.snippet_stack.push(SnippetState {
5141 active_index: 0,
5142 ranges,
5143 choices,
5144 });
5145 }
5146
5147 // Check whether the just-entered snippet ends with an auto-closable bracket.
5148 if self.autoclose_regions.is_empty() {
5149 let snapshot = self.buffer.read(cx).snapshot(cx);
5150 for selection in &mut self.selections.all::<Point>(cx) {
5151 let selection_head = selection.head();
5152 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5153 continue;
5154 };
5155
5156 let mut bracket_pair = None;
5157 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5158 let prev_chars = snapshot
5159 .reversed_chars_at(selection_head)
5160 .collect::<String>();
5161 for (pair, enabled) in scope.brackets() {
5162 if enabled
5163 && pair.close
5164 && prev_chars.starts_with(pair.start.as_str())
5165 && next_chars.starts_with(pair.end.as_str())
5166 {
5167 bracket_pair = Some(pair.clone());
5168 break;
5169 }
5170 }
5171 if let Some(pair) = bracket_pair {
5172 let start = snapshot.anchor_after(selection_head);
5173 let end = snapshot.anchor_after(selection_head);
5174 self.autoclose_regions.push(AutocloseRegion {
5175 selection_id: selection.id,
5176 range: start..end,
5177 pair,
5178 });
5179 }
5180 }
5181 }
5182 }
5183 Ok(())
5184 }
5185
5186 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5187 self.move_to_snippet_tabstop(Bias::Right, cx)
5188 }
5189
5190 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5191 self.move_to_snippet_tabstop(Bias::Left, cx)
5192 }
5193
5194 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5195 if let Some(mut snippet) = self.snippet_stack.pop() {
5196 match bias {
5197 Bias::Left => {
5198 if snippet.active_index > 0 {
5199 snippet.active_index -= 1;
5200 } else {
5201 self.snippet_stack.push(snippet);
5202 return false;
5203 }
5204 }
5205 Bias::Right => {
5206 if snippet.active_index + 1 < snippet.ranges.len() {
5207 snippet.active_index += 1;
5208 } else {
5209 self.snippet_stack.push(snippet);
5210 return false;
5211 }
5212 }
5213 }
5214 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5215 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5216 s.select_anchor_ranges(current_ranges.iter().cloned())
5217 });
5218
5219 if let Some(choices) = &snippet.choices[snippet.active_index] {
5220 if let Some(selection) = current_ranges.first() {
5221 self.show_snippet_choices(&choices, selection.clone(), cx);
5222 }
5223 }
5224
5225 // If snippet state is not at the last tabstop, push it back on the stack
5226 if snippet.active_index + 1 < snippet.ranges.len() {
5227 self.snippet_stack.push(snippet);
5228 }
5229 return true;
5230 }
5231 }
5232
5233 false
5234 }
5235
5236 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5237 self.transact(cx, |this, cx| {
5238 this.select_all(&SelectAll, cx);
5239 this.insert("", cx);
5240 });
5241 }
5242
5243 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5244 self.transact(cx, |this, cx| {
5245 this.select_autoclose_pair(cx);
5246 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5247 if !this.linked_edit_ranges.is_empty() {
5248 let selections = this.selections.all::<MultiBufferPoint>(cx);
5249 let snapshot = this.buffer.read(cx).snapshot(cx);
5250
5251 for selection in selections.iter() {
5252 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5253 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5254 if selection_start.buffer_id != selection_end.buffer_id {
5255 continue;
5256 }
5257 if let Some(ranges) =
5258 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5259 {
5260 for (buffer, entries) in ranges {
5261 linked_ranges.entry(buffer).or_default().extend(entries);
5262 }
5263 }
5264 }
5265 }
5266
5267 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5268 if !this.selections.line_mode {
5269 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5270 for selection in &mut selections {
5271 if selection.is_empty() {
5272 let old_head = selection.head();
5273 let mut new_head =
5274 movement::left(&display_map, old_head.to_display_point(&display_map))
5275 .to_point(&display_map);
5276 if let Some((buffer, line_buffer_range)) = display_map
5277 .buffer_snapshot
5278 .buffer_line_for_row(MultiBufferRow(old_head.row))
5279 {
5280 let indent_size =
5281 buffer.indent_size_for_line(line_buffer_range.start.row);
5282 let indent_len = match indent_size.kind {
5283 IndentKind::Space => {
5284 buffer.settings_at(line_buffer_range.start, cx).tab_size
5285 }
5286 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5287 };
5288 if old_head.column <= indent_size.len && old_head.column > 0 {
5289 let indent_len = indent_len.get();
5290 new_head = cmp::min(
5291 new_head,
5292 MultiBufferPoint::new(
5293 old_head.row,
5294 ((old_head.column - 1) / indent_len) * indent_len,
5295 ),
5296 );
5297 }
5298 }
5299
5300 selection.set_head(new_head, SelectionGoal::None);
5301 }
5302 }
5303 }
5304
5305 this.signature_help_state.set_backspace_pressed(true);
5306 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5307 this.insert("", cx);
5308 let empty_str: Arc<str> = Arc::from("");
5309 for (buffer, edits) in linked_ranges {
5310 let snapshot = buffer.read(cx).snapshot();
5311 use text::ToPoint as TP;
5312
5313 let edits = edits
5314 .into_iter()
5315 .map(|range| {
5316 let end_point = TP::to_point(&range.end, &snapshot);
5317 let mut start_point = TP::to_point(&range.start, &snapshot);
5318
5319 if end_point == start_point {
5320 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5321 .saturating_sub(1);
5322 start_point = TP::to_point(&offset, &snapshot);
5323 };
5324
5325 (start_point..end_point, empty_str.clone())
5326 })
5327 .sorted_by_key(|(range, _)| range.start)
5328 .collect::<Vec<_>>();
5329 buffer.update(cx, |this, cx| {
5330 this.edit(edits, None, cx);
5331 })
5332 }
5333 this.refresh_inline_completion(true, false, cx);
5334 linked_editing_ranges::refresh_linked_ranges(this, cx);
5335 });
5336 }
5337
5338 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5339 self.transact(cx, |this, cx| {
5340 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5341 let line_mode = s.line_mode;
5342 s.move_with(|map, selection| {
5343 if selection.is_empty() && !line_mode {
5344 let cursor = movement::right(map, selection.head());
5345 selection.end = cursor;
5346 selection.reversed = true;
5347 selection.goal = SelectionGoal::None;
5348 }
5349 })
5350 });
5351 this.insert("", cx);
5352 this.refresh_inline_completion(true, false, cx);
5353 });
5354 }
5355
5356 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5357 if self.move_to_prev_snippet_tabstop(cx) {
5358 return;
5359 }
5360
5361 self.outdent(&Outdent, cx);
5362 }
5363
5364 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5365 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5366 return;
5367 }
5368
5369 let mut selections = self.selections.all_adjusted(cx);
5370 let buffer = self.buffer.read(cx);
5371 let snapshot = buffer.snapshot(cx);
5372 let rows_iter = selections.iter().map(|s| s.head().row);
5373 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5374
5375 let mut edits = Vec::new();
5376 let mut prev_edited_row = 0;
5377 let mut row_delta = 0;
5378 for selection in &mut selections {
5379 if selection.start.row != prev_edited_row {
5380 row_delta = 0;
5381 }
5382 prev_edited_row = selection.end.row;
5383
5384 // If the selection is non-empty, then increase the indentation of the selected lines.
5385 if !selection.is_empty() {
5386 row_delta =
5387 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5388 continue;
5389 }
5390
5391 // If the selection is empty and the cursor is in the leading whitespace before the
5392 // suggested indentation, then auto-indent the line.
5393 let cursor = selection.head();
5394 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5395 if let Some(suggested_indent) =
5396 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5397 {
5398 if cursor.column < suggested_indent.len
5399 && cursor.column <= current_indent.len
5400 && current_indent.len <= suggested_indent.len
5401 {
5402 selection.start = Point::new(cursor.row, suggested_indent.len);
5403 selection.end = selection.start;
5404 if row_delta == 0 {
5405 edits.extend(Buffer::edit_for_indent_size_adjustment(
5406 cursor.row,
5407 current_indent,
5408 suggested_indent,
5409 ));
5410 row_delta = suggested_indent.len - current_indent.len;
5411 }
5412 continue;
5413 }
5414 }
5415
5416 // Otherwise, insert a hard or soft tab.
5417 let settings = buffer.settings_at(cursor, cx);
5418 let tab_size = if settings.hard_tabs {
5419 IndentSize::tab()
5420 } else {
5421 let tab_size = settings.tab_size.get();
5422 let char_column = snapshot
5423 .text_for_range(Point::new(cursor.row, 0)..cursor)
5424 .flat_map(str::chars)
5425 .count()
5426 + row_delta as usize;
5427 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5428 IndentSize::spaces(chars_to_next_tab_stop)
5429 };
5430 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5431 selection.end = selection.start;
5432 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5433 row_delta += tab_size.len;
5434 }
5435
5436 self.transact(cx, |this, cx| {
5437 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5438 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5439 this.refresh_inline_completion(true, false, cx);
5440 });
5441 }
5442
5443 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5444 if self.read_only(cx) {
5445 return;
5446 }
5447 let mut selections = self.selections.all::<Point>(cx);
5448 let mut prev_edited_row = 0;
5449 let mut row_delta = 0;
5450 let mut edits = Vec::new();
5451 let buffer = self.buffer.read(cx);
5452 let snapshot = buffer.snapshot(cx);
5453 for selection in &mut selections {
5454 if selection.start.row != prev_edited_row {
5455 row_delta = 0;
5456 }
5457 prev_edited_row = selection.end.row;
5458
5459 row_delta =
5460 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5461 }
5462
5463 self.transact(cx, |this, cx| {
5464 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5465 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5466 });
5467 }
5468
5469 fn indent_selection(
5470 buffer: &MultiBuffer,
5471 snapshot: &MultiBufferSnapshot,
5472 selection: &mut Selection<Point>,
5473 edits: &mut Vec<(Range<Point>, String)>,
5474 delta_for_start_row: u32,
5475 cx: &AppContext,
5476 ) -> u32 {
5477 let settings = buffer.settings_at(selection.start, cx);
5478 let tab_size = settings.tab_size.get();
5479 let indent_kind = if settings.hard_tabs {
5480 IndentKind::Tab
5481 } else {
5482 IndentKind::Space
5483 };
5484 let mut start_row = selection.start.row;
5485 let mut end_row = selection.end.row + 1;
5486
5487 // If a selection ends at the beginning of a line, don't indent
5488 // that last line.
5489 if selection.end.column == 0 && selection.end.row > selection.start.row {
5490 end_row -= 1;
5491 }
5492
5493 // Avoid re-indenting a row that has already been indented by a
5494 // previous selection, but still update this selection's column
5495 // to reflect that indentation.
5496 if delta_for_start_row > 0 {
5497 start_row += 1;
5498 selection.start.column += delta_for_start_row;
5499 if selection.end.row == selection.start.row {
5500 selection.end.column += delta_for_start_row;
5501 }
5502 }
5503
5504 let mut delta_for_end_row = 0;
5505 let has_multiple_rows = start_row + 1 != end_row;
5506 for row in start_row..end_row {
5507 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5508 let indent_delta = match (current_indent.kind, indent_kind) {
5509 (IndentKind::Space, IndentKind::Space) => {
5510 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5511 IndentSize::spaces(columns_to_next_tab_stop)
5512 }
5513 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5514 (_, IndentKind::Tab) => IndentSize::tab(),
5515 };
5516
5517 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5518 0
5519 } else {
5520 selection.start.column
5521 };
5522 let row_start = Point::new(row, start);
5523 edits.push((
5524 row_start..row_start,
5525 indent_delta.chars().collect::<String>(),
5526 ));
5527
5528 // Update this selection's endpoints to reflect the indentation.
5529 if row == selection.start.row {
5530 selection.start.column += indent_delta.len;
5531 }
5532 if row == selection.end.row {
5533 selection.end.column += indent_delta.len;
5534 delta_for_end_row = indent_delta.len;
5535 }
5536 }
5537
5538 if selection.start.row == selection.end.row {
5539 delta_for_start_row + delta_for_end_row
5540 } else {
5541 delta_for_end_row
5542 }
5543 }
5544
5545 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5546 if self.read_only(cx) {
5547 return;
5548 }
5549 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5550 let selections = self.selections.all::<Point>(cx);
5551 let mut deletion_ranges = Vec::new();
5552 let mut last_outdent = None;
5553 {
5554 let buffer = self.buffer.read(cx);
5555 let snapshot = buffer.snapshot(cx);
5556 for selection in &selections {
5557 let settings = buffer.settings_at(selection.start, cx);
5558 let tab_size = settings.tab_size.get();
5559 let mut rows = selection.spanned_rows(false, &display_map);
5560
5561 // Avoid re-outdenting a row that has already been outdented by a
5562 // previous selection.
5563 if let Some(last_row) = last_outdent {
5564 if last_row == rows.start {
5565 rows.start = rows.start.next_row();
5566 }
5567 }
5568 let has_multiple_rows = rows.len() > 1;
5569 for row in rows.iter_rows() {
5570 let indent_size = snapshot.indent_size_for_line(row);
5571 if indent_size.len > 0 {
5572 let deletion_len = match indent_size.kind {
5573 IndentKind::Space => {
5574 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5575 if columns_to_prev_tab_stop == 0 {
5576 tab_size
5577 } else {
5578 columns_to_prev_tab_stop
5579 }
5580 }
5581 IndentKind::Tab => 1,
5582 };
5583 let start = if has_multiple_rows
5584 || deletion_len > selection.start.column
5585 || indent_size.len < selection.start.column
5586 {
5587 0
5588 } else {
5589 selection.start.column - deletion_len
5590 };
5591 deletion_ranges.push(
5592 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5593 );
5594 last_outdent = Some(row);
5595 }
5596 }
5597 }
5598 }
5599
5600 self.transact(cx, |this, cx| {
5601 this.buffer.update(cx, |buffer, cx| {
5602 let empty_str: Arc<str> = Arc::default();
5603 buffer.edit(
5604 deletion_ranges
5605 .into_iter()
5606 .map(|range| (range, empty_str.clone())),
5607 None,
5608 cx,
5609 );
5610 });
5611 let selections = this.selections.all::<usize>(cx);
5612 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5613 });
5614 }
5615
5616 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
5617 if self.read_only(cx) {
5618 return;
5619 }
5620 let selections = self
5621 .selections
5622 .all::<usize>(cx)
5623 .into_iter()
5624 .map(|s| s.range());
5625
5626 self.transact(cx, |this, cx| {
5627 this.buffer.update(cx, |buffer, cx| {
5628 buffer.autoindent_ranges(selections, cx);
5629 });
5630 let selections = this.selections.all::<usize>(cx);
5631 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5632 });
5633 }
5634
5635 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5636 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5637 let selections = self.selections.all::<Point>(cx);
5638
5639 let mut new_cursors = Vec::new();
5640 let mut edit_ranges = Vec::new();
5641 let mut selections = selections.iter().peekable();
5642 while let Some(selection) = selections.next() {
5643 let mut rows = selection.spanned_rows(false, &display_map);
5644 let goal_display_column = selection.head().to_display_point(&display_map).column();
5645
5646 // Accumulate contiguous regions of rows that we want to delete.
5647 while let Some(next_selection) = selections.peek() {
5648 let next_rows = next_selection.spanned_rows(false, &display_map);
5649 if next_rows.start <= rows.end {
5650 rows.end = next_rows.end;
5651 selections.next().unwrap();
5652 } else {
5653 break;
5654 }
5655 }
5656
5657 let buffer = &display_map.buffer_snapshot;
5658 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5659 let edit_end;
5660 let cursor_buffer_row;
5661 if buffer.max_point().row >= rows.end.0 {
5662 // If there's a line after the range, delete the \n from the end of the row range
5663 // and position the cursor on the next line.
5664 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5665 cursor_buffer_row = rows.end;
5666 } else {
5667 // If there isn't a line after the range, delete the \n from the line before the
5668 // start of the row range and position the cursor there.
5669 edit_start = edit_start.saturating_sub(1);
5670 edit_end = buffer.len();
5671 cursor_buffer_row = rows.start.previous_row();
5672 }
5673
5674 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5675 *cursor.column_mut() =
5676 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5677
5678 new_cursors.push((
5679 selection.id,
5680 buffer.anchor_after(cursor.to_point(&display_map)),
5681 ));
5682 edit_ranges.push(edit_start..edit_end);
5683 }
5684
5685 self.transact(cx, |this, cx| {
5686 let buffer = this.buffer.update(cx, |buffer, cx| {
5687 let empty_str: Arc<str> = Arc::default();
5688 buffer.edit(
5689 edit_ranges
5690 .into_iter()
5691 .map(|range| (range, empty_str.clone())),
5692 None,
5693 cx,
5694 );
5695 buffer.snapshot(cx)
5696 });
5697 let new_selections = new_cursors
5698 .into_iter()
5699 .map(|(id, cursor)| {
5700 let cursor = cursor.to_point(&buffer);
5701 Selection {
5702 id,
5703 start: cursor,
5704 end: cursor,
5705 reversed: false,
5706 goal: SelectionGoal::None,
5707 }
5708 })
5709 .collect();
5710
5711 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5712 s.select(new_selections);
5713 });
5714 });
5715 }
5716
5717 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5718 if self.read_only(cx) {
5719 return;
5720 }
5721 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5722 for selection in self.selections.all::<Point>(cx) {
5723 let start = MultiBufferRow(selection.start.row);
5724 // Treat single line selections as if they include the next line. Otherwise this action
5725 // would do nothing for single line selections individual cursors.
5726 let end = if selection.start.row == selection.end.row {
5727 MultiBufferRow(selection.start.row + 1)
5728 } else {
5729 MultiBufferRow(selection.end.row)
5730 };
5731
5732 if let Some(last_row_range) = row_ranges.last_mut() {
5733 if start <= last_row_range.end {
5734 last_row_range.end = end;
5735 continue;
5736 }
5737 }
5738 row_ranges.push(start..end);
5739 }
5740
5741 let snapshot = self.buffer.read(cx).snapshot(cx);
5742 let mut cursor_positions = Vec::new();
5743 for row_range in &row_ranges {
5744 let anchor = snapshot.anchor_before(Point::new(
5745 row_range.end.previous_row().0,
5746 snapshot.line_len(row_range.end.previous_row()),
5747 ));
5748 cursor_positions.push(anchor..anchor);
5749 }
5750
5751 self.transact(cx, |this, cx| {
5752 for row_range in row_ranges.into_iter().rev() {
5753 for row in row_range.iter_rows().rev() {
5754 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5755 let next_line_row = row.next_row();
5756 let indent = snapshot.indent_size_for_line(next_line_row);
5757 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5758
5759 let replace = if snapshot.line_len(next_line_row) > indent.len {
5760 " "
5761 } else {
5762 ""
5763 };
5764
5765 this.buffer.update(cx, |buffer, cx| {
5766 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5767 });
5768 }
5769 }
5770
5771 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5772 s.select_anchor_ranges(cursor_positions)
5773 });
5774 });
5775 }
5776
5777 pub fn sort_lines_case_sensitive(
5778 &mut self,
5779 _: &SortLinesCaseSensitive,
5780 cx: &mut ViewContext<Self>,
5781 ) {
5782 self.manipulate_lines(cx, |lines| lines.sort())
5783 }
5784
5785 pub fn sort_lines_case_insensitive(
5786 &mut self,
5787 _: &SortLinesCaseInsensitive,
5788 cx: &mut ViewContext<Self>,
5789 ) {
5790 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5791 }
5792
5793 pub fn unique_lines_case_insensitive(
5794 &mut self,
5795 _: &UniqueLinesCaseInsensitive,
5796 cx: &mut ViewContext<Self>,
5797 ) {
5798 self.manipulate_lines(cx, |lines| {
5799 let mut seen = HashSet::default();
5800 lines.retain(|line| seen.insert(line.to_lowercase()));
5801 })
5802 }
5803
5804 pub fn unique_lines_case_sensitive(
5805 &mut self,
5806 _: &UniqueLinesCaseSensitive,
5807 cx: &mut ViewContext<Self>,
5808 ) {
5809 self.manipulate_lines(cx, |lines| {
5810 let mut seen = HashSet::default();
5811 lines.retain(|line| seen.insert(*line));
5812 })
5813 }
5814
5815 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
5816 let mut revert_changes = HashMap::default();
5817 let snapshot = self.snapshot(cx);
5818 for hunk in hunks_for_ranges(
5819 Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
5820 &snapshot,
5821 ) {
5822 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
5823 }
5824 if !revert_changes.is_empty() {
5825 self.transact(cx, |editor, cx| {
5826 editor.revert(revert_changes, cx);
5827 });
5828 }
5829 }
5830
5831 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
5832 let Some(project) = self.project.clone() else {
5833 return;
5834 };
5835 self.reload(project, cx).detach_and_notify_err(cx);
5836 }
5837
5838 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
5839 let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
5840 if !revert_changes.is_empty() {
5841 self.transact(cx, |editor, cx| {
5842 editor.revert(revert_changes, cx);
5843 });
5844 }
5845 }
5846
5847 fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
5848 let snapshot = self.buffer.read(cx).read(cx);
5849 if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
5850 drop(snapshot);
5851 let mut revert_changes = HashMap::default();
5852 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
5853 if !revert_changes.is_empty() {
5854 self.revert(revert_changes, cx)
5855 }
5856 }
5857 }
5858
5859 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
5860 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
5861 let project_path = buffer.read(cx).project_path(cx)?;
5862 let project = self.project.as_ref()?.read(cx);
5863 let entry = project.entry_for_path(&project_path, cx)?;
5864 let parent = match &entry.canonical_path {
5865 Some(canonical_path) => canonical_path.to_path_buf(),
5866 None => project.absolute_path(&project_path, cx)?,
5867 }
5868 .parent()?
5869 .to_path_buf();
5870 Some(parent)
5871 }) {
5872 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
5873 }
5874 }
5875
5876 fn gather_revert_changes(
5877 &mut self,
5878 selections: &[Selection<Point>],
5879 cx: &mut ViewContext<'_, Editor>,
5880 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
5881 let mut revert_changes = HashMap::default();
5882 let snapshot = self.snapshot(cx);
5883 for hunk in hunks_for_selections(&snapshot, selections) {
5884 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
5885 }
5886 revert_changes
5887 }
5888
5889 pub fn prepare_revert_change(
5890 &mut self,
5891 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
5892 hunk: &MultiBufferDiffHunk,
5893 cx: &AppContext,
5894 ) -> Option<()> {
5895 let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
5896 let buffer = buffer.read(cx);
5897 let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
5898 let original_text = change_set
5899 .read(cx)
5900 .base_text
5901 .as_ref()?
5902 .read(cx)
5903 .as_rope()
5904 .slice(hunk.diff_base_byte_range.clone());
5905 let buffer_snapshot = buffer.snapshot();
5906 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
5907 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
5908 probe
5909 .0
5910 .start
5911 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
5912 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
5913 }) {
5914 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
5915 Some(())
5916 } else {
5917 None
5918 }
5919 }
5920
5921 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
5922 self.manipulate_lines(cx, |lines| lines.reverse())
5923 }
5924
5925 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
5926 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
5927 }
5928
5929 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
5930 where
5931 Fn: FnMut(&mut Vec<&str>),
5932 {
5933 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5934 let buffer = self.buffer.read(cx).snapshot(cx);
5935
5936 let mut edits = Vec::new();
5937
5938 let selections = self.selections.all::<Point>(cx);
5939 let mut selections = selections.iter().peekable();
5940 let mut contiguous_row_selections = Vec::new();
5941 let mut new_selections = Vec::new();
5942 let mut added_lines = 0;
5943 let mut removed_lines = 0;
5944
5945 while let Some(selection) = selections.next() {
5946 let (start_row, end_row) = consume_contiguous_rows(
5947 &mut contiguous_row_selections,
5948 selection,
5949 &display_map,
5950 &mut selections,
5951 );
5952
5953 let start_point = Point::new(start_row.0, 0);
5954 let end_point = Point::new(
5955 end_row.previous_row().0,
5956 buffer.line_len(end_row.previous_row()),
5957 );
5958 let text = buffer
5959 .text_for_range(start_point..end_point)
5960 .collect::<String>();
5961
5962 let mut lines = text.split('\n').collect_vec();
5963
5964 let lines_before = lines.len();
5965 callback(&mut lines);
5966 let lines_after = lines.len();
5967
5968 edits.push((start_point..end_point, lines.join("\n")));
5969
5970 // Selections must change based on added and removed line count
5971 let start_row =
5972 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
5973 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
5974 new_selections.push(Selection {
5975 id: selection.id,
5976 start: start_row,
5977 end: end_row,
5978 goal: SelectionGoal::None,
5979 reversed: selection.reversed,
5980 });
5981
5982 if lines_after > lines_before {
5983 added_lines += lines_after - lines_before;
5984 } else if lines_before > lines_after {
5985 removed_lines += lines_before - lines_after;
5986 }
5987 }
5988
5989 self.transact(cx, |this, cx| {
5990 let buffer = this.buffer.update(cx, |buffer, cx| {
5991 buffer.edit(edits, None, cx);
5992 buffer.snapshot(cx)
5993 });
5994
5995 // Recalculate offsets on newly edited buffer
5996 let new_selections = new_selections
5997 .iter()
5998 .map(|s| {
5999 let start_point = Point::new(s.start.0, 0);
6000 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6001 Selection {
6002 id: s.id,
6003 start: buffer.point_to_offset(start_point),
6004 end: buffer.point_to_offset(end_point),
6005 goal: s.goal,
6006 reversed: s.reversed,
6007 }
6008 })
6009 .collect();
6010
6011 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6012 s.select(new_selections);
6013 });
6014
6015 this.request_autoscroll(Autoscroll::fit(), cx);
6016 });
6017 }
6018
6019 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6020 self.manipulate_text(cx, |text| text.to_uppercase())
6021 }
6022
6023 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6024 self.manipulate_text(cx, |text| text.to_lowercase())
6025 }
6026
6027 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6028 self.manipulate_text(cx, |text| {
6029 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6030 // https://github.com/rutrum/convert-case/issues/16
6031 text.split('\n')
6032 .map(|line| line.to_case(Case::Title))
6033 .join("\n")
6034 })
6035 }
6036
6037 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6038 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6039 }
6040
6041 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6042 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6043 }
6044
6045 pub fn convert_to_upper_camel_case(
6046 &mut self,
6047 _: &ConvertToUpperCamelCase,
6048 cx: &mut ViewContext<Self>,
6049 ) {
6050 self.manipulate_text(cx, |text| {
6051 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6052 // https://github.com/rutrum/convert-case/issues/16
6053 text.split('\n')
6054 .map(|line| line.to_case(Case::UpperCamel))
6055 .join("\n")
6056 })
6057 }
6058
6059 pub fn convert_to_lower_camel_case(
6060 &mut self,
6061 _: &ConvertToLowerCamelCase,
6062 cx: &mut ViewContext<Self>,
6063 ) {
6064 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6065 }
6066
6067 pub fn convert_to_opposite_case(
6068 &mut self,
6069 _: &ConvertToOppositeCase,
6070 cx: &mut ViewContext<Self>,
6071 ) {
6072 self.manipulate_text(cx, |text| {
6073 text.chars()
6074 .fold(String::with_capacity(text.len()), |mut t, c| {
6075 if c.is_uppercase() {
6076 t.extend(c.to_lowercase());
6077 } else {
6078 t.extend(c.to_uppercase());
6079 }
6080 t
6081 })
6082 })
6083 }
6084
6085 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6086 where
6087 Fn: FnMut(&str) -> String,
6088 {
6089 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6090 let buffer = self.buffer.read(cx).snapshot(cx);
6091
6092 let mut new_selections = Vec::new();
6093 let mut edits = Vec::new();
6094 let mut selection_adjustment = 0i32;
6095
6096 for selection in self.selections.all::<usize>(cx) {
6097 let selection_is_empty = selection.is_empty();
6098
6099 let (start, end) = if selection_is_empty {
6100 let word_range = movement::surrounding_word(
6101 &display_map,
6102 selection.start.to_display_point(&display_map),
6103 );
6104 let start = word_range.start.to_offset(&display_map, Bias::Left);
6105 let end = word_range.end.to_offset(&display_map, Bias::Left);
6106 (start, end)
6107 } else {
6108 (selection.start, selection.end)
6109 };
6110
6111 let text = buffer.text_for_range(start..end).collect::<String>();
6112 let old_length = text.len() as i32;
6113 let text = callback(&text);
6114
6115 new_selections.push(Selection {
6116 start: (start as i32 - selection_adjustment) as usize,
6117 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6118 goal: SelectionGoal::None,
6119 ..selection
6120 });
6121
6122 selection_adjustment += old_length - text.len() as i32;
6123
6124 edits.push((start..end, text));
6125 }
6126
6127 self.transact(cx, |this, cx| {
6128 this.buffer.update(cx, |buffer, cx| {
6129 buffer.edit(edits, None, cx);
6130 });
6131
6132 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6133 s.select(new_selections);
6134 });
6135
6136 this.request_autoscroll(Autoscroll::fit(), cx);
6137 });
6138 }
6139
6140 pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
6141 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6142 let buffer = &display_map.buffer_snapshot;
6143 let selections = self.selections.all::<Point>(cx);
6144
6145 let mut edits = Vec::new();
6146 let mut selections_iter = selections.iter().peekable();
6147 while let Some(selection) = selections_iter.next() {
6148 let mut rows = selection.spanned_rows(false, &display_map);
6149 // duplicate line-wise
6150 if whole_lines || selection.start == selection.end {
6151 // Avoid duplicating the same lines twice.
6152 while let Some(next_selection) = selections_iter.peek() {
6153 let next_rows = next_selection.spanned_rows(false, &display_map);
6154 if next_rows.start < rows.end {
6155 rows.end = next_rows.end;
6156 selections_iter.next().unwrap();
6157 } else {
6158 break;
6159 }
6160 }
6161
6162 // Copy the text from the selected row region and splice it either at the start
6163 // or end of the region.
6164 let start = Point::new(rows.start.0, 0);
6165 let end = Point::new(
6166 rows.end.previous_row().0,
6167 buffer.line_len(rows.end.previous_row()),
6168 );
6169 let text = buffer
6170 .text_for_range(start..end)
6171 .chain(Some("\n"))
6172 .collect::<String>();
6173 let insert_location = if upwards {
6174 Point::new(rows.end.0, 0)
6175 } else {
6176 start
6177 };
6178 edits.push((insert_location..insert_location, text));
6179 } else {
6180 // duplicate character-wise
6181 let start = selection.start;
6182 let end = selection.end;
6183 let text = buffer.text_for_range(start..end).collect::<String>();
6184 edits.push((selection.end..selection.end, text));
6185 }
6186 }
6187
6188 self.transact(cx, |this, cx| {
6189 this.buffer.update(cx, |buffer, cx| {
6190 buffer.edit(edits, None, cx);
6191 });
6192
6193 this.request_autoscroll(Autoscroll::fit(), cx);
6194 });
6195 }
6196
6197 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6198 self.duplicate(true, true, cx);
6199 }
6200
6201 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6202 self.duplicate(false, true, cx);
6203 }
6204
6205 pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
6206 self.duplicate(false, false, cx);
6207 }
6208
6209 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6210 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6211 let buffer = self.buffer.read(cx).snapshot(cx);
6212
6213 let mut edits = Vec::new();
6214 let mut unfold_ranges = Vec::new();
6215 let mut refold_creases = Vec::new();
6216
6217 let selections = self.selections.all::<Point>(cx);
6218 let mut selections = selections.iter().peekable();
6219 let mut contiguous_row_selections = Vec::new();
6220 let mut new_selections = Vec::new();
6221
6222 while let Some(selection) = selections.next() {
6223 // Find all the selections that span a contiguous row range
6224 let (start_row, end_row) = consume_contiguous_rows(
6225 &mut contiguous_row_selections,
6226 selection,
6227 &display_map,
6228 &mut selections,
6229 );
6230
6231 // Move the text spanned by the row range to be before the line preceding the row range
6232 if start_row.0 > 0 {
6233 let range_to_move = Point::new(
6234 start_row.previous_row().0,
6235 buffer.line_len(start_row.previous_row()),
6236 )
6237 ..Point::new(
6238 end_row.previous_row().0,
6239 buffer.line_len(end_row.previous_row()),
6240 );
6241 let insertion_point = display_map
6242 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6243 .0;
6244
6245 // Don't move lines across excerpts
6246 if buffer
6247 .excerpt_boundaries_in_range((
6248 Bound::Excluded(insertion_point),
6249 Bound::Included(range_to_move.end),
6250 ))
6251 .next()
6252 .is_none()
6253 {
6254 let text = buffer
6255 .text_for_range(range_to_move.clone())
6256 .flat_map(|s| s.chars())
6257 .skip(1)
6258 .chain(['\n'])
6259 .collect::<String>();
6260
6261 edits.push((
6262 buffer.anchor_after(range_to_move.start)
6263 ..buffer.anchor_before(range_to_move.end),
6264 String::new(),
6265 ));
6266 let insertion_anchor = buffer.anchor_after(insertion_point);
6267 edits.push((insertion_anchor..insertion_anchor, text));
6268
6269 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6270
6271 // Move selections up
6272 new_selections.extend(contiguous_row_selections.drain(..).map(
6273 |mut selection| {
6274 selection.start.row -= row_delta;
6275 selection.end.row -= row_delta;
6276 selection
6277 },
6278 ));
6279
6280 // Move folds up
6281 unfold_ranges.push(range_to_move.clone());
6282 for fold in display_map.folds_in_range(
6283 buffer.anchor_before(range_to_move.start)
6284 ..buffer.anchor_after(range_to_move.end),
6285 ) {
6286 let mut start = fold.range.start.to_point(&buffer);
6287 let mut end = fold.range.end.to_point(&buffer);
6288 start.row -= row_delta;
6289 end.row -= row_delta;
6290 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6291 }
6292 }
6293 }
6294
6295 // If we didn't move line(s), preserve the existing selections
6296 new_selections.append(&mut contiguous_row_selections);
6297 }
6298
6299 self.transact(cx, |this, cx| {
6300 this.unfold_ranges(&unfold_ranges, true, true, cx);
6301 this.buffer.update(cx, |buffer, cx| {
6302 for (range, text) in edits {
6303 buffer.edit([(range, text)], None, cx);
6304 }
6305 });
6306 this.fold_creases(refold_creases, true, cx);
6307 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6308 s.select(new_selections);
6309 })
6310 });
6311 }
6312
6313 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6314 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6315 let buffer = self.buffer.read(cx).snapshot(cx);
6316
6317 let mut edits = Vec::new();
6318 let mut unfold_ranges = Vec::new();
6319 let mut refold_creases = Vec::new();
6320
6321 let selections = self.selections.all::<Point>(cx);
6322 let mut selections = selections.iter().peekable();
6323 let mut contiguous_row_selections = Vec::new();
6324 let mut new_selections = Vec::new();
6325
6326 while let Some(selection) = selections.next() {
6327 // Find all the selections that span a contiguous row range
6328 let (start_row, end_row) = consume_contiguous_rows(
6329 &mut contiguous_row_selections,
6330 selection,
6331 &display_map,
6332 &mut selections,
6333 );
6334
6335 // Move the text spanned by the row range to be after the last line of the row range
6336 if end_row.0 <= buffer.max_point().row {
6337 let range_to_move =
6338 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6339 let insertion_point = display_map
6340 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6341 .0;
6342
6343 // Don't move lines across excerpt boundaries
6344 if buffer
6345 .excerpt_boundaries_in_range((
6346 Bound::Excluded(range_to_move.start),
6347 Bound::Included(insertion_point),
6348 ))
6349 .next()
6350 .is_none()
6351 {
6352 let mut text = String::from("\n");
6353 text.extend(buffer.text_for_range(range_to_move.clone()));
6354 text.pop(); // Drop trailing newline
6355 edits.push((
6356 buffer.anchor_after(range_to_move.start)
6357 ..buffer.anchor_before(range_to_move.end),
6358 String::new(),
6359 ));
6360 let insertion_anchor = buffer.anchor_after(insertion_point);
6361 edits.push((insertion_anchor..insertion_anchor, text));
6362
6363 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6364
6365 // Move selections down
6366 new_selections.extend(contiguous_row_selections.drain(..).map(
6367 |mut selection| {
6368 selection.start.row += row_delta;
6369 selection.end.row += row_delta;
6370 selection
6371 },
6372 ));
6373
6374 // Move folds down
6375 unfold_ranges.push(range_to_move.clone());
6376 for fold in display_map.folds_in_range(
6377 buffer.anchor_before(range_to_move.start)
6378 ..buffer.anchor_after(range_to_move.end),
6379 ) {
6380 let mut start = fold.range.start.to_point(&buffer);
6381 let mut end = fold.range.end.to_point(&buffer);
6382 start.row += row_delta;
6383 end.row += row_delta;
6384 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6385 }
6386 }
6387 }
6388
6389 // If we didn't move line(s), preserve the existing selections
6390 new_selections.append(&mut contiguous_row_selections);
6391 }
6392
6393 self.transact(cx, |this, cx| {
6394 this.unfold_ranges(&unfold_ranges, true, true, cx);
6395 this.buffer.update(cx, |buffer, cx| {
6396 for (range, text) in edits {
6397 buffer.edit([(range, text)], None, cx);
6398 }
6399 });
6400 this.fold_creases(refold_creases, true, cx);
6401 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6402 });
6403 }
6404
6405 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6406 let text_layout_details = &self.text_layout_details(cx);
6407 self.transact(cx, |this, cx| {
6408 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6409 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6410 let line_mode = s.line_mode;
6411 s.move_with(|display_map, selection| {
6412 if !selection.is_empty() || line_mode {
6413 return;
6414 }
6415
6416 let mut head = selection.head();
6417 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6418 if head.column() == display_map.line_len(head.row()) {
6419 transpose_offset = display_map
6420 .buffer_snapshot
6421 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6422 }
6423
6424 if transpose_offset == 0 {
6425 return;
6426 }
6427
6428 *head.column_mut() += 1;
6429 head = display_map.clip_point(head, Bias::Right);
6430 let goal = SelectionGoal::HorizontalPosition(
6431 display_map
6432 .x_for_display_point(head, text_layout_details)
6433 .into(),
6434 );
6435 selection.collapse_to(head, goal);
6436
6437 let transpose_start = display_map
6438 .buffer_snapshot
6439 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6440 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6441 let transpose_end = display_map
6442 .buffer_snapshot
6443 .clip_offset(transpose_offset + 1, Bias::Right);
6444 if let Some(ch) =
6445 display_map.buffer_snapshot.chars_at(transpose_start).next()
6446 {
6447 edits.push((transpose_start..transpose_offset, String::new()));
6448 edits.push((transpose_end..transpose_end, ch.to_string()));
6449 }
6450 }
6451 });
6452 edits
6453 });
6454 this.buffer
6455 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6456 let selections = this.selections.all::<usize>(cx);
6457 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6458 s.select(selections);
6459 });
6460 });
6461 }
6462
6463 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6464 self.rewrap_impl(IsVimMode::No, cx)
6465 }
6466
6467 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
6468 let buffer = self.buffer.read(cx).snapshot(cx);
6469 let selections = self.selections.all::<Point>(cx);
6470 let mut selections = selections.iter().peekable();
6471
6472 let mut edits = Vec::new();
6473 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6474
6475 while let Some(selection) = selections.next() {
6476 let mut start_row = selection.start.row;
6477 let mut end_row = selection.end.row;
6478
6479 // Skip selections that overlap with a range that has already been rewrapped.
6480 let selection_range = start_row..end_row;
6481 if rewrapped_row_ranges
6482 .iter()
6483 .any(|range| range.overlaps(&selection_range))
6484 {
6485 continue;
6486 }
6487
6488 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
6489
6490 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6491 match language_scope.language_name().0.as_ref() {
6492 "Markdown" | "Plain Text" => {
6493 should_rewrap = true;
6494 }
6495 _ => {}
6496 }
6497 }
6498
6499 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
6500
6501 // Since not all lines in the selection may be at the same indent
6502 // level, choose the indent size that is the most common between all
6503 // of the lines.
6504 //
6505 // If there is a tie, we use the deepest indent.
6506 let (indent_size, indent_end) = {
6507 let mut indent_size_occurrences = HashMap::default();
6508 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6509
6510 for row in start_row..=end_row {
6511 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6512 rows_by_indent_size.entry(indent).or_default().push(row);
6513 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6514 }
6515
6516 let indent_size = indent_size_occurrences
6517 .into_iter()
6518 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
6519 .map(|(indent, _)| indent)
6520 .unwrap_or_default();
6521 let row = rows_by_indent_size[&indent_size][0];
6522 let indent_end = Point::new(row, indent_size.len);
6523
6524 (indent_size, indent_end)
6525 };
6526
6527 let mut line_prefix = indent_size.chars().collect::<String>();
6528
6529 if let Some(comment_prefix) =
6530 buffer
6531 .language_scope_at(selection.head())
6532 .and_then(|language| {
6533 language
6534 .line_comment_prefixes()
6535 .iter()
6536 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6537 .cloned()
6538 })
6539 {
6540 line_prefix.push_str(&comment_prefix);
6541 should_rewrap = true;
6542 }
6543
6544 if !should_rewrap {
6545 continue;
6546 }
6547
6548 if selection.is_empty() {
6549 'expand_upwards: while start_row > 0 {
6550 let prev_row = start_row - 1;
6551 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6552 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6553 {
6554 start_row = prev_row;
6555 } else {
6556 break 'expand_upwards;
6557 }
6558 }
6559
6560 'expand_downwards: while end_row < buffer.max_point().row {
6561 let next_row = end_row + 1;
6562 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6563 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6564 {
6565 end_row = next_row;
6566 } else {
6567 break 'expand_downwards;
6568 }
6569 }
6570 }
6571
6572 let start = Point::new(start_row, 0);
6573 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6574 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6575 let Some(lines_without_prefixes) = selection_text
6576 .lines()
6577 .map(|line| {
6578 line.strip_prefix(&line_prefix)
6579 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6580 .ok_or_else(|| {
6581 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6582 })
6583 })
6584 .collect::<Result<Vec<_>, _>>()
6585 .log_err()
6586 else {
6587 continue;
6588 };
6589
6590 let wrap_column = buffer
6591 .settings_at(Point::new(start_row, 0), cx)
6592 .preferred_line_length as usize;
6593 let wrapped_text = wrap_with_prefix(
6594 line_prefix,
6595 lines_without_prefixes.join(" "),
6596 wrap_column,
6597 tab_size,
6598 );
6599
6600 // TODO: should always use char-based diff while still supporting cursor behavior that
6601 // matches vim.
6602 let diff = match is_vim_mode {
6603 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
6604 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
6605 };
6606 let mut offset = start.to_offset(&buffer);
6607 let mut moved_since_edit = true;
6608
6609 for change in diff.iter_all_changes() {
6610 let value = change.value();
6611 match change.tag() {
6612 ChangeTag::Equal => {
6613 offset += value.len();
6614 moved_since_edit = true;
6615 }
6616 ChangeTag::Delete => {
6617 let start = buffer.anchor_after(offset);
6618 let end = buffer.anchor_before(offset + value.len());
6619
6620 if moved_since_edit {
6621 edits.push((start..end, String::new()));
6622 } else {
6623 edits.last_mut().unwrap().0.end = end;
6624 }
6625
6626 offset += value.len();
6627 moved_since_edit = false;
6628 }
6629 ChangeTag::Insert => {
6630 if moved_since_edit {
6631 let anchor = buffer.anchor_after(offset);
6632 edits.push((anchor..anchor, value.to_string()));
6633 } else {
6634 edits.last_mut().unwrap().1.push_str(value);
6635 }
6636
6637 moved_since_edit = false;
6638 }
6639 }
6640 }
6641
6642 rewrapped_row_ranges.push(start_row..=end_row);
6643 }
6644
6645 self.buffer
6646 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6647 }
6648
6649 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
6650 let mut text = String::new();
6651 let buffer = self.buffer.read(cx).snapshot(cx);
6652 let mut selections = self.selections.all::<Point>(cx);
6653 let mut clipboard_selections = Vec::with_capacity(selections.len());
6654 {
6655 let max_point = buffer.max_point();
6656 let mut is_first = true;
6657 for selection in &mut selections {
6658 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6659 if is_entire_line {
6660 selection.start = Point::new(selection.start.row, 0);
6661 if !selection.is_empty() && selection.end.column == 0 {
6662 selection.end = cmp::min(max_point, selection.end);
6663 } else {
6664 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6665 }
6666 selection.goal = SelectionGoal::None;
6667 }
6668 if is_first {
6669 is_first = false;
6670 } else {
6671 text += "\n";
6672 }
6673 let mut len = 0;
6674 for chunk in buffer.text_for_range(selection.start..selection.end) {
6675 text.push_str(chunk);
6676 len += chunk.len();
6677 }
6678 clipboard_selections.push(ClipboardSelection {
6679 len,
6680 is_entire_line,
6681 first_line_indent: buffer
6682 .indent_size_for_line(MultiBufferRow(selection.start.row))
6683 .len,
6684 });
6685 }
6686 }
6687
6688 self.transact(cx, |this, cx| {
6689 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6690 s.select(selections);
6691 });
6692 this.insert("", cx);
6693 });
6694 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
6695 }
6696
6697 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6698 let item = self.cut_common(cx);
6699 cx.write_to_clipboard(item);
6700 }
6701
6702 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
6703 self.change_selections(None, cx, |s| {
6704 s.move_with(|snapshot, sel| {
6705 if sel.is_empty() {
6706 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
6707 }
6708 });
6709 });
6710 let item = self.cut_common(cx);
6711 cx.set_global(KillRing(item))
6712 }
6713
6714 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
6715 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
6716 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
6717 (kill_ring.text().to_string(), kill_ring.metadata_json())
6718 } else {
6719 return;
6720 }
6721 } else {
6722 return;
6723 };
6724 self.do_paste(&text, metadata, false, cx);
6725 }
6726
6727 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6728 let selections = self.selections.all::<Point>(cx);
6729 let buffer = self.buffer.read(cx).read(cx);
6730 let mut text = String::new();
6731
6732 let mut clipboard_selections = Vec::with_capacity(selections.len());
6733 {
6734 let max_point = buffer.max_point();
6735 let mut is_first = true;
6736 for selection in selections.iter() {
6737 let mut start = selection.start;
6738 let mut end = selection.end;
6739 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6740 if is_entire_line {
6741 start = Point::new(start.row, 0);
6742 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6743 }
6744 if is_first {
6745 is_first = false;
6746 } else {
6747 text += "\n";
6748 }
6749 let mut len = 0;
6750 for chunk in buffer.text_for_range(start..end) {
6751 text.push_str(chunk);
6752 len += chunk.len();
6753 }
6754 clipboard_selections.push(ClipboardSelection {
6755 len,
6756 is_entire_line,
6757 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6758 });
6759 }
6760 }
6761
6762 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6763 text,
6764 clipboard_selections,
6765 ));
6766 }
6767
6768 pub fn do_paste(
6769 &mut self,
6770 text: &String,
6771 clipboard_selections: Option<Vec<ClipboardSelection>>,
6772 handle_entire_lines: bool,
6773 cx: &mut ViewContext<Self>,
6774 ) {
6775 if self.read_only(cx) {
6776 return;
6777 }
6778
6779 let clipboard_text = Cow::Borrowed(text);
6780
6781 self.transact(cx, |this, cx| {
6782 if let Some(mut clipboard_selections) = clipboard_selections {
6783 let old_selections = this.selections.all::<usize>(cx);
6784 let all_selections_were_entire_line =
6785 clipboard_selections.iter().all(|s| s.is_entire_line);
6786 let first_selection_indent_column =
6787 clipboard_selections.first().map(|s| s.first_line_indent);
6788 if clipboard_selections.len() != old_selections.len() {
6789 clipboard_selections.drain(..);
6790 }
6791 let cursor_offset = this.selections.last::<usize>(cx).head();
6792 let mut auto_indent_on_paste = true;
6793
6794 this.buffer.update(cx, |buffer, cx| {
6795 let snapshot = buffer.read(cx);
6796 auto_indent_on_paste =
6797 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
6798
6799 let mut start_offset = 0;
6800 let mut edits = Vec::new();
6801 let mut original_indent_columns = Vec::new();
6802 for (ix, selection) in old_selections.iter().enumerate() {
6803 let to_insert;
6804 let entire_line;
6805 let original_indent_column;
6806 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6807 let end_offset = start_offset + clipboard_selection.len;
6808 to_insert = &clipboard_text[start_offset..end_offset];
6809 entire_line = clipboard_selection.is_entire_line;
6810 start_offset = end_offset + 1;
6811 original_indent_column = Some(clipboard_selection.first_line_indent);
6812 } else {
6813 to_insert = clipboard_text.as_str();
6814 entire_line = all_selections_were_entire_line;
6815 original_indent_column = first_selection_indent_column
6816 }
6817
6818 // If the corresponding selection was empty when this slice of the
6819 // clipboard text was written, then the entire line containing the
6820 // selection was copied. If this selection is also currently empty,
6821 // then paste the line before the current line of the buffer.
6822 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6823 let column = selection.start.to_point(&snapshot).column as usize;
6824 let line_start = selection.start - column;
6825 line_start..line_start
6826 } else {
6827 selection.range()
6828 };
6829
6830 edits.push((range, to_insert));
6831 original_indent_columns.extend(original_indent_column);
6832 }
6833 drop(snapshot);
6834
6835 buffer.edit(
6836 edits,
6837 if auto_indent_on_paste {
6838 Some(AutoindentMode::Block {
6839 original_indent_columns,
6840 })
6841 } else {
6842 None
6843 },
6844 cx,
6845 );
6846 });
6847
6848 let selections = this.selections.all::<usize>(cx);
6849 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6850 } else {
6851 this.insert(&clipboard_text, cx);
6852 }
6853 });
6854 }
6855
6856 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
6857 if let Some(item) = cx.read_from_clipboard() {
6858 let entries = item.entries();
6859
6860 match entries.first() {
6861 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
6862 // of all the pasted entries.
6863 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
6864 .do_paste(
6865 clipboard_string.text(),
6866 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
6867 true,
6868 cx,
6869 ),
6870 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
6871 }
6872 }
6873 }
6874
6875 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
6876 if self.read_only(cx) {
6877 return;
6878 }
6879
6880 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
6881 if let Some((selections, _)) =
6882 self.selection_history.transaction(transaction_id).cloned()
6883 {
6884 self.change_selections(None, cx, |s| {
6885 s.select_anchors(selections.to_vec());
6886 });
6887 }
6888 self.request_autoscroll(Autoscroll::fit(), cx);
6889 self.unmark_text(cx);
6890 self.refresh_inline_completion(true, false, cx);
6891 cx.emit(EditorEvent::Edited { transaction_id });
6892 cx.emit(EditorEvent::TransactionUndone { transaction_id });
6893 }
6894 }
6895
6896 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
6897 if self.read_only(cx) {
6898 return;
6899 }
6900
6901 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
6902 if let Some((_, Some(selections))) =
6903 self.selection_history.transaction(transaction_id).cloned()
6904 {
6905 self.change_selections(None, cx, |s| {
6906 s.select_anchors(selections.to_vec());
6907 });
6908 }
6909 self.request_autoscroll(Autoscroll::fit(), cx);
6910 self.unmark_text(cx);
6911 self.refresh_inline_completion(true, false, cx);
6912 cx.emit(EditorEvent::Edited { transaction_id });
6913 }
6914 }
6915
6916 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
6917 self.buffer
6918 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
6919 }
6920
6921 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
6922 self.buffer
6923 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
6924 }
6925
6926 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
6927 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6928 let line_mode = s.line_mode;
6929 s.move_with(|map, selection| {
6930 let cursor = if selection.is_empty() && !line_mode {
6931 movement::left(map, selection.start)
6932 } else {
6933 selection.start
6934 };
6935 selection.collapse_to(cursor, SelectionGoal::None);
6936 });
6937 })
6938 }
6939
6940 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
6941 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6942 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
6943 })
6944 }
6945
6946 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
6947 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6948 let line_mode = s.line_mode;
6949 s.move_with(|map, selection| {
6950 let cursor = if selection.is_empty() && !line_mode {
6951 movement::right(map, selection.end)
6952 } else {
6953 selection.end
6954 };
6955 selection.collapse_to(cursor, SelectionGoal::None)
6956 });
6957 })
6958 }
6959
6960 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
6961 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6962 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
6963 })
6964 }
6965
6966 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
6967 if self.take_rename(true, cx).is_some() {
6968 return;
6969 }
6970
6971 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6972 cx.propagate();
6973 return;
6974 }
6975
6976 let text_layout_details = &self.text_layout_details(cx);
6977 let selection_count = self.selections.count();
6978 let first_selection = self.selections.first_anchor();
6979
6980 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6981 let line_mode = s.line_mode;
6982 s.move_with(|map, selection| {
6983 if !selection.is_empty() && !line_mode {
6984 selection.goal = SelectionGoal::None;
6985 }
6986 let (cursor, goal) = movement::up(
6987 map,
6988 selection.start,
6989 selection.goal,
6990 false,
6991 text_layout_details,
6992 );
6993 selection.collapse_to(cursor, goal);
6994 });
6995 });
6996
6997 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
6998 {
6999 cx.propagate();
7000 }
7001 }
7002
7003 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7004 if self.take_rename(true, cx).is_some() {
7005 return;
7006 }
7007
7008 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7009 cx.propagate();
7010 return;
7011 }
7012
7013 let text_layout_details = &self.text_layout_details(cx);
7014
7015 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7016 let line_mode = s.line_mode;
7017 s.move_with(|map, selection| {
7018 if !selection.is_empty() && !line_mode {
7019 selection.goal = SelectionGoal::None;
7020 }
7021 let (cursor, goal) = movement::up_by_rows(
7022 map,
7023 selection.start,
7024 action.lines,
7025 selection.goal,
7026 false,
7027 text_layout_details,
7028 );
7029 selection.collapse_to(cursor, goal);
7030 });
7031 })
7032 }
7033
7034 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7035 if self.take_rename(true, cx).is_some() {
7036 return;
7037 }
7038
7039 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7040 cx.propagate();
7041 return;
7042 }
7043
7044 let text_layout_details = &self.text_layout_details(cx);
7045
7046 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7047 let line_mode = s.line_mode;
7048 s.move_with(|map, selection| {
7049 if !selection.is_empty() && !line_mode {
7050 selection.goal = SelectionGoal::None;
7051 }
7052 let (cursor, goal) = movement::down_by_rows(
7053 map,
7054 selection.start,
7055 action.lines,
7056 selection.goal,
7057 false,
7058 text_layout_details,
7059 );
7060 selection.collapse_to(cursor, goal);
7061 });
7062 })
7063 }
7064
7065 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7066 let text_layout_details = &self.text_layout_details(cx);
7067 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7068 s.move_heads_with(|map, head, goal| {
7069 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7070 })
7071 })
7072 }
7073
7074 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7075 let text_layout_details = &self.text_layout_details(cx);
7076 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7077 s.move_heads_with(|map, head, goal| {
7078 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7079 })
7080 })
7081 }
7082
7083 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7084 let Some(row_count) = self.visible_row_count() else {
7085 return;
7086 };
7087
7088 let text_layout_details = &self.text_layout_details(cx);
7089
7090 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7091 s.move_heads_with(|map, head, goal| {
7092 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7093 })
7094 })
7095 }
7096
7097 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7098 if self.take_rename(true, cx).is_some() {
7099 return;
7100 }
7101
7102 if self
7103 .context_menu
7104 .write()
7105 .as_mut()
7106 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7107 .unwrap_or(false)
7108 {
7109 return;
7110 }
7111
7112 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7113 cx.propagate();
7114 return;
7115 }
7116
7117 let Some(row_count) = self.visible_row_count() else {
7118 return;
7119 };
7120
7121 let autoscroll = if action.center_cursor {
7122 Autoscroll::center()
7123 } else {
7124 Autoscroll::fit()
7125 };
7126
7127 let text_layout_details = &self.text_layout_details(cx);
7128
7129 self.change_selections(Some(autoscroll), cx, |s| {
7130 let line_mode = s.line_mode;
7131 s.move_with(|map, selection| {
7132 if !selection.is_empty() && !line_mode {
7133 selection.goal = SelectionGoal::None;
7134 }
7135 let (cursor, goal) = movement::up_by_rows(
7136 map,
7137 selection.end,
7138 row_count,
7139 selection.goal,
7140 false,
7141 text_layout_details,
7142 );
7143 selection.collapse_to(cursor, goal);
7144 });
7145 });
7146 }
7147
7148 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7149 let text_layout_details = &self.text_layout_details(cx);
7150 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7151 s.move_heads_with(|map, head, goal| {
7152 movement::up(map, head, goal, false, text_layout_details)
7153 })
7154 })
7155 }
7156
7157 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7158 self.take_rename(true, cx);
7159
7160 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7161 cx.propagate();
7162 return;
7163 }
7164
7165 let text_layout_details = &self.text_layout_details(cx);
7166 let selection_count = self.selections.count();
7167 let first_selection = self.selections.first_anchor();
7168
7169 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7170 let line_mode = s.line_mode;
7171 s.move_with(|map, selection| {
7172 if !selection.is_empty() && !line_mode {
7173 selection.goal = SelectionGoal::None;
7174 }
7175 let (cursor, goal) = movement::down(
7176 map,
7177 selection.end,
7178 selection.goal,
7179 false,
7180 text_layout_details,
7181 );
7182 selection.collapse_to(cursor, goal);
7183 });
7184 });
7185
7186 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7187 {
7188 cx.propagate();
7189 }
7190 }
7191
7192 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7193 let Some(row_count) = self.visible_row_count() else {
7194 return;
7195 };
7196
7197 let text_layout_details = &self.text_layout_details(cx);
7198
7199 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7200 s.move_heads_with(|map, head, goal| {
7201 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7202 })
7203 })
7204 }
7205
7206 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7207 if self.take_rename(true, cx).is_some() {
7208 return;
7209 }
7210
7211 if self
7212 .context_menu
7213 .write()
7214 .as_mut()
7215 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7216 .unwrap_or(false)
7217 {
7218 return;
7219 }
7220
7221 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7222 cx.propagate();
7223 return;
7224 }
7225
7226 let Some(row_count) = self.visible_row_count() else {
7227 return;
7228 };
7229
7230 let autoscroll = if action.center_cursor {
7231 Autoscroll::center()
7232 } else {
7233 Autoscroll::fit()
7234 };
7235
7236 let text_layout_details = &self.text_layout_details(cx);
7237 self.change_selections(Some(autoscroll), cx, |s| {
7238 let line_mode = s.line_mode;
7239 s.move_with(|map, selection| {
7240 if !selection.is_empty() && !line_mode {
7241 selection.goal = SelectionGoal::None;
7242 }
7243 let (cursor, goal) = movement::down_by_rows(
7244 map,
7245 selection.end,
7246 row_count,
7247 selection.goal,
7248 false,
7249 text_layout_details,
7250 );
7251 selection.collapse_to(cursor, goal);
7252 });
7253 });
7254 }
7255
7256 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7257 let text_layout_details = &self.text_layout_details(cx);
7258 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7259 s.move_heads_with(|map, head, goal| {
7260 movement::down(map, head, goal, false, text_layout_details)
7261 })
7262 });
7263 }
7264
7265 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7266 if let Some(context_menu) = self.context_menu.write().as_mut() {
7267 context_menu.select_first(self.completion_provider.as_deref(), cx);
7268 }
7269 }
7270
7271 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7272 if let Some(context_menu) = self.context_menu.write().as_mut() {
7273 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7274 }
7275 }
7276
7277 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7278 if let Some(context_menu) = self.context_menu.write().as_mut() {
7279 context_menu.select_next(self.completion_provider.as_deref(), cx);
7280 }
7281 }
7282
7283 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7284 if let Some(context_menu) = self.context_menu.write().as_mut() {
7285 context_menu.select_last(self.completion_provider.as_deref(), cx);
7286 }
7287 }
7288
7289 pub fn move_to_previous_word_start(
7290 &mut self,
7291 _: &MoveToPreviousWordStart,
7292 cx: &mut ViewContext<Self>,
7293 ) {
7294 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7295 s.move_cursors_with(|map, head, _| {
7296 (
7297 movement::previous_word_start(map, head),
7298 SelectionGoal::None,
7299 )
7300 });
7301 })
7302 }
7303
7304 pub fn move_to_previous_subword_start(
7305 &mut self,
7306 _: &MoveToPreviousSubwordStart,
7307 cx: &mut ViewContext<Self>,
7308 ) {
7309 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7310 s.move_cursors_with(|map, head, _| {
7311 (
7312 movement::previous_subword_start(map, head),
7313 SelectionGoal::None,
7314 )
7315 });
7316 })
7317 }
7318
7319 pub fn select_to_previous_word_start(
7320 &mut self,
7321 _: &SelectToPreviousWordStart,
7322 cx: &mut ViewContext<Self>,
7323 ) {
7324 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7325 s.move_heads_with(|map, head, _| {
7326 (
7327 movement::previous_word_start(map, head),
7328 SelectionGoal::None,
7329 )
7330 });
7331 })
7332 }
7333
7334 pub fn select_to_previous_subword_start(
7335 &mut self,
7336 _: &SelectToPreviousSubwordStart,
7337 cx: &mut ViewContext<Self>,
7338 ) {
7339 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7340 s.move_heads_with(|map, head, _| {
7341 (
7342 movement::previous_subword_start(map, head),
7343 SelectionGoal::None,
7344 )
7345 });
7346 })
7347 }
7348
7349 pub fn delete_to_previous_word_start(
7350 &mut self,
7351 action: &DeleteToPreviousWordStart,
7352 cx: &mut ViewContext<Self>,
7353 ) {
7354 self.transact(cx, |this, cx| {
7355 this.select_autoclose_pair(cx);
7356 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7357 let line_mode = s.line_mode;
7358 s.move_with(|map, selection| {
7359 if selection.is_empty() && !line_mode {
7360 let cursor = if action.ignore_newlines {
7361 movement::previous_word_start(map, selection.head())
7362 } else {
7363 movement::previous_word_start_or_newline(map, selection.head())
7364 };
7365 selection.set_head(cursor, SelectionGoal::None);
7366 }
7367 });
7368 });
7369 this.insert("", cx);
7370 });
7371 }
7372
7373 pub fn delete_to_previous_subword_start(
7374 &mut self,
7375 _: &DeleteToPreviousSubwordStart,
7376 cx: &mut ViewContext<Self>,
7377 ) {
7378 self.transact(cx, |this, cx| {
7379 this.select_autoclose_pair(cx);
7380 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7381 let line_mode = s.line_mode;
7382 s.move_with(|map, selection| {
7383 if selection.is_empty() && !line_mode {
7384 let cursor = movement::previous_subword_start(map, selection.head());
7385 selection.set_head(cursor, SelectionGoal::None);
7386 }
7387 });
7388 });
7389 this.insert("", cx);
7390 });
7391 }
7392
7393 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7394 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7395 s.move_cursors_with(|map, head, _| {
7396 (movement::next_word_end(map, head), SelectionGoal::None)
7397 });
7398 })
7399 }
7400
7401 pub fn move_to_next_subword_end(
7402 &mut self,
7403 _: &MoveToNextSubwordEnd,
7404 cx: &mut ViewContext<Self>,
7405 ) {
7406 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7407 s.move_cursors_with(|map, head, _| {
7408 (movement::next_subword_end(map, head), SelectionGoal::None)
7409 });
7410 })
7411 }
7412
7413 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7414 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7415 s.move_heads_with(|map, head, _| {
7416 (movement::next_word_end(map, head), SelectionGoal::None)
7417 });
7418 })
7419 }
7420
7421 pub fn select_to_next_subword_end(
7422 &mut self,
7423 _: &SelectToNextSubwordEnd,
7424 cx: &mut ViewContext<Self>,
7425 ) {
7426 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7427 s.move_heads_with(|map, head, _| {
7428 (movement::next_subword_end(map, head), SelectionGoal::None)
7429 });
7430 })
7431 }
7432
7433 pub fn delete_to_next_word_end(
7434 &mut self,
7435 action: &DeleteToNextWordEnd,
7436 cx: &mut ViewContext<Self>,
7437 ) {
7438 self.transact(cx, |this, cx| {
7439 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7440 let line_mode = s.line_mode;
7441 s.move_with(|map, selection| {
7442 if selection.is_empty() && !line_mode {
7443 let cursor = if action.ignore_newlines {
7444 movement::next_word_end(map, selection.head())
7445 } else {
7446 movement::next_word_end_or_newline(map, selection.head())
7447 };
7448 selection.set_head(cursor, SelectionGoal::None);
7449 }
7450 });
7451 });
7452 this.insert("", cx);
7453 });
7454 }
7455
7456 pub fn delete_to_next_subword_end(
7457 &mut self,
7458 _: &DeleteToNextSubwordEnd,
7459 cx: &mut ViewContext<Self>,
7460 ) {
7461 self.transact(cx, |this, cx| {
7462 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7463 s.move_with(|map, selection| {
7464 if selection.is_empty() {
7465 let cursor = movement::next_subword_end(map, selection.head());
7466 selection.set_head(cursor, SelectionGoal::None);
7467 }
7468 });
7469 });
7470 this.insert("", cx);
7471 });
7472 }
7473
7474 pub fn move_to_beginning_of_line(
7475 &mut self,
7476 action: &MoveToBeginningOfLine,
7477 cx: &mut ViewContext<Self>,
7478 ) {
7479 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7480 s.move_cursors_with(|map, head, _| {
7481 (
7482 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7483 SelectionGoal::None,
7484 )
7485 });
7486 })
7487 }
7488
7489 pub fn select_to_beginning_of_line(
7490 &mut self,
7491 action: &SelectToBeginningOfLine,
7492 cx: &mut ViewContext<Self>,
7493 ) {
7494 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7495 s.move_heads_with(|map, head, _| {
7496 (
7497 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7498 SelectionGoal::None,
7499 )
7500 });
7501 });
7502 }
7503
7504 pub fn delete_to_beginning_of_line(
7505 &mut self,
7506 _: &DeleteToBeginningOfLine,
7507 cx: &mut ViewContext<Self>,
7508 ) {
7509 self.transact(cx, |this, cx| {
7510 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7511 s.move_with(|_, selection| {
7512 selection.reversed = true;
7513 });
7514 });
7515
7516 this.select_to_beginning_of_line(
7517 &SelectToBeginningOfLine {
7518 stop_at_soft_wraps: false,
7519 },
7520 cx,
7521 );
7522 this.backspace(&Backspace, cx);
7523 });
7524 }
7525
7526 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7527 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7528 s.move_cursors_with(|map, head, _| {
7529 (
7530 movement::line_end(map, head, action.stop_at_soft_wraps),
7531 SelectionGoal::None,
7532 )
7533 });
7534 })
7535 }
7536
7537 pub fn select_to_end_of_line(
7538 &mut self,
7539 action: &SelectToEndOfLine,
7540 cx: &mut ViewContext<Self>,
7541 ) {
7542 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7543 s.move_heads_with(|map, head, _| {
7544 (
7545 movement::line_end(map, head, action.stop_at_soft_wraps),
7546 SelectionGoal::None,
7547 )
7548 });
7549 })
7550 }
7551
7552 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7553 self.transact(cx, |this, cx| {
7554 this.select_to_end_of_line(
7555 &SelectToEndOfLine {
7556 stop_at_soft_wraps: false,
7557 },
7558 cx,
7559 );
7560 this.delete(&Delete, cx);
7561 });
7562 }
7563
7564 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7565 self.transact(cx, |this, cx| {
7566 this.select_to_end_of_line(
7567 &SelectToEndOfLine {
7568 stop_at_soft_wraps: false,
7569 },
7570 cx,
7571 );
7572 this.cut(&Cut, cx);
7573 });
7574 }
7575
7576 pub fn move_to_start_of_paragraph(
7577 &mut self,
7578 _: &MoveToStartOfParagraph,
7579 cx: &mut ViewContext<Self>,
7580 ) {
7581 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7582 cx.propagate();
7583 return;
7584 }
7585
7586 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7587 s.move_with(|map, selection| {
7588 selection.collapse_to(
7589 movement::start_of_paragraph(map, selection.head(), 1),
7590 SelectionGoal::None,
7591 )
7592 });
7593 })
7594 }
7595
7596 pub fn move_to_end_of_paragraph(
7597 &mut self,
7598 _: &MoveToEndOfParagraph,
7599 cx: &mut ViewContext<Self>,
7600 ) {
7601 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7602 cx.propagate();
7603 return;
7604 }
7605
7606 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7607 s.move_with(|map, selection| {
7608 selection.collapse_to(
7609 movement::end_of_paragraph(map, selection.head(), 1),
7610 SelectionGoal::None,
7611 )
7612 });
7613 })
7614 }
7615
7616 pub fn select_to_start_of_paragraph(
7617 &mut self,
7618 _: &SelectToStartOfParagraph,
7619 cx: &mut ViewContext<Self>,
7620 ) {
7621 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7622 cx.propagate();
7623 return;
7624 }
7625
7626 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7627 s.move_heads_with(|map, head, _| {
7628 (
7629 movement::start_of_paragraph(map, head, 1),
7630 SelectionGoal::None,
7631 )
7632 });
7633 })
7634 }
7635
7636 pub fn select_to_end_of_paragraph(
7637 &mut self,
7638 _: &SelectToEndOfParagraph,
7639 cx: &mut ViewContext<Self>,
7640 ) {
7641 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7642 cx.propagate();
7643 return;
7644 }
7645
7646 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7647 s.move_heads_with(|map, head, _| {
7648 (
7649 movement::end_of_paragraph(map, head, 1),
7650 SelectionGoal::None,
7651 )
7652 });
7653 })
7654 }
7655
7656 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7657 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7658 cx.propagate();
7659 return;
7660 }
7661
7662 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7663 s.select_ranges(vec![0..0]);
7664 });
7665 }
7666
7667 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7668 let mut selection = self.selections.last::<Point>(cx);
7669 selection.set_head(Point::zero(), SelectionGoal::None);
7670
7671 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7672 s.select(vec![selection]);
7673 });
7674 }
7675
7676 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7677 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7678 cx.propagate();
7679 return;
7680 }
7681
7682 let cursor = self.buffer.read(cx).read(cx).len();
7683 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7684 s.select_ranges(vec![cursor..cursor])
7685 });
7686 }
7687
7688 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7689 self.nav_history = nav_history;
7690 }
7691
7692 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7693 self.nav_history.as_ref()
7694 }
7695
7696 fn push_to_nav_history(
7697 &mut self,
7698 cursor_anchor: Anchor,
7699 new_position: Option<Point>,
7700 cx: &mut ViewContext<Self>,
7701 ) {
7702 if let Some(nav_history) = self.nav_history.as_mut() {
7703 let buffer = self.buffer.read(cx).read(cx);
7704 let cursor_position = cursor_anchor.to_point(&buffer);
7705 let scroll_state = self.scroll_manager.anchor();
7706 let scroll_top_row = scroll_state.top_row(&buffer);
7707 drop(buffer);
7708
7709 if let Some(new_position) = new_position {
7710 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7711 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7712 return;
7713 }
7714 }
7715
7716 nav_history.push(
7717 Some(NavigationData {
7718 cursor_anchor,
7719 cursor_position,
7720 scroll_anchor: scroll_state,
7721 scroll_top_row,
7722 }),
7723 cx,
7724 );
7725 }
7726 }
7727
7728 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7729 let buffer = self.buffer.read(cx).snapshot(cx);
7730 let mut selection = self.selections.first::<usize>(cx);
7731 selection.set_head(buffer.len(), SelectionGoal::None);
7732 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7733 s.select(vec![selection]);
7734 });
7735 }
7736
7737 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7738 let end = self.buffer.read(cx).read(cx).len();
7739 self.change_selections(None, cx, |s| {
7740 s.select_ranges(vec![0..end]);
7741 });
7742 }
7743
7744 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7745 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7746 let mut selections = self.selections.all::<Point>(cx);
7747 let max_point = display_map.buffer_snapshot.max_point();
7748 for selection in &mut selections {
7749 let rows = selection.spanned_rows(true, &display_map);
7750 selection.start = Point::new(rows.start.0, 0);
7751 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7752 selection.reversed = false;
7753 }
7754 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7755 s.select(selections);
7756 });
7757 }
7758
7759 pub fn split_selection_into_lines(
7760 &mut self,
7761 _: &SplitSelectionIntoLines,
7762 cx: &mut ViewContext<Self>,
7763 ) {
7764 let mut to_unfold = Vec::new();
7765 let mut new_selection_ranges = Vec::new();
7766 {
7767 let selections = self.selections.all::<Point>(cx);
7768 let buffer = self.buffer.read(cx).read(cx);
7769 for selection in selections {
7770 for row in selection.start.row..selection.end.row {
7771 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7772 new_selection_ranges.push(cursor..cursor);
7773 }
7774 new_selection_ranges.push(selection.end..selection.end);
7775 to_unfold.push(selection.start..selection.end);
7776 }
7777 }
7778 self.unfold_ranges(&to_unfold, true, true, cx);
7779 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7780 s.select_ranges(new_selection_ranges);
7781 });
7782 }
7783
7784 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7785 self.add_selection(true, cx);
7786 }
7787
7788 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7789 self.add_selection(false, cx);
7790 }
7791
7792 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7793 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7794 let mut selections = self.selections.all::<Point>(cx);
7795 let text_layout_details = self.text_layout_details(cx);
7796 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7797 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7798 let range = oldest_selection.display_range(&display_map).sorted();
7799
7800 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7801 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7802 let positions = start_x.min(end_x)..start_x.max(end_x);
7803
7804 selections.clear();
7805 let mut stack = Vec::new();
7806 for row in range.start.row().0..=range.end.row().0 {
7807 if let Some(selection) = self.selections.build_columnar_selection(
7808 &display_map,
7809 DisplayRow(row),
7810 &positions,
7811 oldest_selection.reversed,
7812 &text_layout_details,
7813 ) {
7814 stack.push(selection.id);
7815 selections.push(selection);
7816 }
7817 }
7818
7819 if above {
7820 stack.reverse();
7821 }
7822
7823 AddSelectionsState { above, stack }
7824 });
7825
7826 let last_added_selection = *state.stack.last().unwrap();
7827 let mut new_selections = Vec::new();
7828 if above == state.above {
7829 let end_row = if above {
7830 DisplayRow(0)
7831 } else {
7832 display_map.max_point().row()
7833 };
7834
7835 'outer: for selection in selections {
7836 if selection.id == last_added_selection {
7837 let range = selection.display_range(&display_map).sorted();
7838 debug_assert_eq!(range.start.row(), range.end.row());
7839 let mut row = range.start.row();
7840 let positions =
7841 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7842 px(start)..px(end)
7843 } else {
7844 let start_x =
7845 display_map.x_for_display_point(range.start, &text_layout_details);
7846 let end_x =
7847 display_map.x_for_display_point(range.end, &text_layout_details);
7848 start_x.min(end_x)..start_x.max(end_x)
7849 };
7850
7851 while row != end_row {
7852 if above {
7853 row.0 -= 1;
7854 } else {
7855 row.0 += 1;
7856 }
7857
7858 if let Some(new_selection) = self.selections.build_columnar_selection(
7859 &display_map,
7860 row,
7861 &positions,
7862 selection.reversed,
7863 &text_layout_details,
7864 ) {
7865 state.stack.push(new_selection.id);
7866 if above {
7867 new_selections.push(new_selection);
7868 new_selections.push(selection);
7869 } else {
7870 new_selections.push(selection);
7871 new_selections.push(new_selection);
7872 }
7873
7874 continue 'outer;
7875 }
7876 }
7877 }
7878
7879 new_selections.push(selection);
7880 }
7881 } else {
7882 new_selections = selections;
7883 new_selections.retain(|s| s.id != last_added_selection);
7884 state.stack.pop();
7885 }
7886
7887 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7888 s.select(new_selections);
7889 });
7890 if state.stack.len() > 1 {
7891 self.add_selections_state = Some(state);
7892 }
7893 }
7894
7895 pub fn select_next_match_internal(
7896 &mut self,
7897 display_map: &DisplaySnapshot,
7898 replace_newest: bool,
7899 autoscroll: Option<Autoscroll>,
7900 cx: &mut ViewContext<Self>,
7901 ) -> Result<()> {
7902 fn select_next_match_ranges(
7903 this: &mut Editor,
7904 range: Range<usize>,
7905 replace_newest: bool,
7906 auto_scroll: Option<Autoscroll>,
7907 cx: &mut ViewContext<Editor>,
7908 ) {
7909 this.unfold_ranges(&[range.clone()], false, true, cx);
7910 this.change_selections(auto_scroll, cx, |s| {
7911 if replace_newest {
7912 s.delete(s.newest_anchor().id);
7913 }
7914 s.insert_range(range.clone());
7915 });
7916 }
7917
7918 let buffer = &display_map.buffer_snapshot;
7919 let mut selections = self.selections.all::<usize>(cx);
7920 if let Some(mut select_next_state) = self.select_next_state.take() {
7921 let query = &select_next_state.query;
7922 if !select_next_state.done {
7923 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7924 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7925 let mut next_selected_range = None;
7926
7927 let bytes_after_last_selection =
7928 buffer.bytes_in_range(last_selection.end..buffer.len());
7929 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
7930 let query_matches = query
7931 .stream_find_iter(bytes_after_last_selection)
7932 .map(|result| (last_selection.end, result))
7933 .chain(
7934 query
7935 .stream_find_iter(bytes_before_first_selection)
7936 .map(|result| (0, result)),
7937 );
7938
7939 for (start_offset, query_match) in query_matches {
7940 let query_match = query_match.unwrap(); // can only fail due to I/O
7941 let offset_range =
7942 start_offset + query_match.start()..start_offset + query_match.end();
7943 let display_range = offset_range.start.to_display_point(display_map)
7944 ..offset_range.end.to_display_point(display_map);
7945
7946 if !select_next_state.wordwise
7947 || (!movement::is_inside_word(display_map, display_range.start)
7948 && !movement::is_inside_word(display_map, display_range.end))
7949 {
7950 // TODO: This is n^2, because we might check all the selections
7951 if !selections
7952 .iter()
7953 .any(|selection| selection.range().overlaps(&offset_range))
7954 {
7955 next_selected_range = Some(offset_range);
7956 break;
7957 }
7958 }
7959 }
7960
7961 if let Some(next_selected_range) = next_selected_range {
7962 select_next_match_ranges(
7963 self,
7964 next_selected_range,
7965 replace_newest,
7966 autoscroll,
7967 cx,
7968 );
7969 } else {
7970 select_next_state.done = true;
7971 }
7972 }
7973
7974 self.select_next_state = Some(select_next_state);
7975 } else {
7976 let mut only_carets = true;
7977 let mut same_text_selected = true;
7978 let mut selected_text = None;
7979
7980 let mut selections_iter = selections.iter().peekable();
7981 while let Some(selection) = selections_iter.next() {
7982 if selection.start != selection.end {
7983 only_carets = false;
7984 }
7985
7986 if same_text_selected {
7987 if selected_text.is_none() {
7988 selected_text =
7989 Some(buffer.text_for_range(selection.range()).collect::<String>());
7990 }
7991
7992 if let Some(next_selection) = selections_iter.peek() {
7993 if next_selection.range().len() == selection.range().len() {
7994 let next_selected_text = buffer
7995 .text_for_range(next_selection.range())
7996 .collect::<String>();
7997 if Some(next_selected_text) != selected_text {
7998 same_text_selected = false;
7999 selected_text = None;
8000 }
8001 } else {
8002 same_text_selected = false;
8003 selected_text = None;
8004 }
8005 }
8006 }
8007 }
8008
8009 if only_carets {
8010 for selection in &mut selections {
8011 let word_range = movement::surrounding_word(
8012 display_map,
8013 selection.start.to_display_point(display_map),
8014 );
8015 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8016 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8017 selection.goal = SelectionGoal::None;
8018 selection.reversed = false;
8019 select_next_match_ranges(
8020 self,
8021 selection.start..selection.end,
8022 replace_newest,
8023 autoscroll,
8024 cx,
8025 );
8026 }
8027
8028 if selections.len() == 1 {
8029 let selection = selections
8030 .last()
8031 .expect("ensured that there's only one selection");
8032 let query = buffer
8033 .text_for_range(selection.start..selection.end)
8034 .collect::<String>();
8035 let is_empty = query.is_empty();
8036 let select_state = SelectNextState {
8037 query: AhoCorasick::new(&[query])?,
8038 wordwise: true,
8039 done: is_empty,
8040 };
8041 self.select_next_state = Some(select_state);
8042 } else {
8043 self.select_next_state = None;
8044 }
8045 } else if let Some(selected_text) = selected_text {
8046 self.select_next_state = Some(SelectNextState {
8047 query: AhoCorasick::new(&[selected_text])?,
8048 wordwise: false,
8049 done: false,
8050 });
8051 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8052 }
8053 }
8054 Ok(())
8055 }
8056
8057 pub fn select_all_matches(
8058 &mut self,
8059 _action: &SelectAllMatches,
8060 cx: &mut ViewContext<Self>,
8061 ) -> Result<()> {
8062 self.push_to_selection_history();
8063 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8064
8065 self.select_next_match_internal(&display_map, false, None, cx)?;
8066 let Some(select_next_state) = self.select_next_state.as_mut() else {
8067 return Ok(());
8068 };
8069 if select_next_state.done {
8070 return Ok(());
8071 }
8072
8073 let mut new_selections = self.selections.all::<usize>(cx);
8074
8075 let buffer = &display_map.buffer_snapshot;
8076 let query_matches = select_next_state
8077 .query
8078 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8079
8080 for query_match in query_matches {
8081 let query_match = query_match.unwrap(); // can only fail due to I/O
8082 let offset_range = query_match.start()..query_match.end();
8083 let display_range = offset_range.start.to_display_point(&display_map)
8084 ..offset_range.end.to_display_point(&display_map);
8085
8086 if !select_next_state.wordwise
8087 || (!movement::is_inside_word(&display_map, display_range.start)
8088 && !movement::is_inside_word(&display_map, display_range.end))
8089 {
8090 self.selections.change_with(cx, |selections| {
8091 new_selections.push(Selection {
8092 id: selections.new_selection_id(),
8093 start: offset_range.start,
8094 end: offset_range.end,
8095 reversed: false,
8096 goal: SelectionGoal::None,
8097 });
8098 });
8099 }
8100 }
8101
8102 new_selections.sort_by_key(|selection| selection.start);
8103 let mut ix = 0;
8104 while ix + 1 < new_selections.len() {
8105 let current_selection = &new_selections[ix];
8106 let next_selection = &new_selections[ix + 1];
8107 if current_selection.range().overlaps(&next_selection.range()) {
8108 if current_selection.id < next_selection.id {
8109 new_selections.remove(ix + 1);
8110 } else {
8111 new_selections.remove(ix);
8112 }
8113 } else {
8114 ix += 1;
8115 }
8116 }
8117
8118 select_next_state.done = true;
8119 self.unfold_ranges(
8120 &new_selections
8121 .iter()
8122 .map(|selection| selection.range())
8123 .collect::<Vec<_>>(),
8124 false,
8125 false,
8126 cx,
8127 );
8128 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8129 selections.select(new_selections)
8130 });
8131
8132 Ok(())
8133 }
8134
8135 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8136 self.push_to_selection_history();
8137 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8138 self.select_next_match_internal(
8139 &display_map,
8140 action.replace_newest,
8141 Some(Autoscroll::newest()),
8142 cx,
8143 )?;
8144 Ok(())
8145 }
8146
8147 pub fn select_previous(
8148 &mut self,
8149 action: &SelectPrevious,
8150 cx: &mut ViewContext<Self>,
8151 ) -> Result<()> {
8152 self.push_to_selection_history();
8153 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8154 let buffer = &display_map.buffer_snapshot;
8155 let mut selections = self.selections.all::<usize>(cx);
8156 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8157 let query = &select_prev_state.query;
8158 if !select_prev_state.done {
8159 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8160 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8161 let mut next_selected_range = None;
8162 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8163 let bytes_before_last_selection =
8164 buffer.reversed_bytes_in_range(0..last_selection.start);
8165 let bytes_after_first_selection =
8166 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8167 let query_matches = query
8168 .stream_find_iter(bytes_before_last_selection)
8169 .map(|result| (last_selection.start, result))
8170 .chain(
8171 query
8172 .stream_find_iter(bytes_after_first_selection)
8173 .map(|result| (buffer.len(), result)),
8174 );
8175 for (end_offset, query_match) in query_matches {
8176 let query_match = query_match.unwrap(); // can only fail due to I/O
8177 let offset_range =
8178 end_offset - query_match.end()..end_offset - query_match.start();
8179 let display_range = offset_range.start.to_display_point(&display_map)
8180 ..offset_range.end.to_display_point(&display_map);
8181
8182 if !select_prev_state.wordwise
8183 || (!movement::is_inside_word(&display_map, display_range.start)
8184 && !movement::is_inside_word(&display_map, display_range.end))
8185 {
8186 next_selected_range = Some(offset_range);
8187 break;
8188 }
8189 }
8190
8191 if let Some(next_selected_range) = next_selected_range {
8192 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8193 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8194 if action.replace_newest {
8195 s.delete(s.newest_anchor().id);
8196 }
8197 s.insert_range(next_selected_range);
8198 });
8199 } else {
8200 select_prev_state.done = true;
8201 }
8202 }
8203
8204 self.select_prev_state = Some(select_prev_state);
8205 } else {
8206 let mut only_carets = true;
8207 let mut same_text_selected = true;
8208 let mut selected_text = None;
8209
8210 let mut selections_iter = selections.iter().peekable();
8211 while let Some(selection) = selections_iter.next() {
8212 if selection.start != selection.end {
8213 only_carets = false;
8214 }
8215
8216 if same_text_selected {
8217 if selected_text.is_none() {
8218 selected_text =
8219 Some(buffer.text_for_range(selection.range()).collect::<String>());
8220 }
8221
8222 if let Some(next_selection) = selections_iter.peek() {
8223 if next_selection.range().len() == selection.range().len() {
8224 let next_selected_text = buffer
8225 .text_for_range(next_selection.range())
8226 .collect::<String>();
8227 if Some(next_selected_text) != selected_text {
8228 same_text_selected = false;
8229 selected_text = None;
8230 }
8231 } else {
8232 same_text_selected = false;
8233 selected_text = None;
8234 }
8235 }
8236 }
8237 }
8238
8239 if only_carets {
8240 for selection in &mut selections {
8241 let word_range = movement::surrounding_word(
8242 &display_map,
8243 selection.start.to_display_point(&display_map),
8244 );
8245 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8246 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8247 selection.goal = SelectionGoal::None;
8248 selection.reversed = false;
8249 }
8250 if selections.len() == 1 {
8251 let selection = selections
8252 .last()
8253 .expect("ensured that there's only one selection");
8254 let query = buffer
8255 .text_for_range(selection.start..selection.end)
8256 .collect::<String>();
8257 let is_empty = query.is_empty();
8258 let select_state = SelectNextState {
8259 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8260 wordwise: true,
8261 done: is_empty,
8262 };
8263 self.select_prev_state = Some(select_state);
8264 } else {
8265 self.select_prev_state = None;
8266 }
8267
8268 self.unfold_ranges(
8269 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8270 false,
8271 true,
8272 cx,
8273 );
8274 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8275 s.select(selections);
8276 });
8277 } else if let Some(selected_text) = selected_text {
8278 self.select_prev_state = Some(SelectNextState {
8279 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8280 wordwise: false,
8281 done: false,
8282 });
8283 self.select_previous(action, cx)?;
8284 }
8285 }
8286 Ok(())
8287 }
8288
8289 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8290 if self.read_only(cx) {
8291 return;
8292 }
8293 let text_layout_details = &self.text_layout_details(cx);
8294 self.transact(cx, |this, cx| {
8295 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8296 let mut edits = Vec::new();
8297 let mut selection_edit_ranges = Vec::new();
8298 let mut last_toggled_row = None;
8299 let snapshot = this.buffer.read(cx).read(cx);
8300 let empty_str: Arc<str> = Arc::default();
8301 let mut suffixes_inserted = Vec::new();
8302 let ignore_indent = action.ignore_indent;
8303
8304 fn comment_prefix_range(
8305 snapshot: &MultiBufferSnapshot,
8306 row: MultiBufferRow,
8307 comment_prefix: &str,
8308 comment_prefix_whitespace: &str,
8309 ignore_indent: bool,
8310 ) -> Range<Point> {
8311 let indent_size = if ignore_indent {
8312 0
8313 } else {
8314 snapshot.indent_size_for_line(row).len
8315 };
8316
8317 let start = Point::new(row.0, indent_size);
8318
8319 let mut line_bytes = snapshot
8320 .bytes_in_range(start..snapshot.max_point())
8321 .flatten()
8322 .copied();
8323
8324 // If this line currently begins with the line comment prefix, then record
8325 // the range containing the prefix.
8326 if line_bytes
8327 .by_ref()
8328 .take(comment_prefix.len())
8329 .eq(comment_prefix.bytes())
8330 {
8331 // Include any whitespace that matches the comment prefix.
8332 let matching_whitespace_len = line_bytes
8333 .zip(comment_prefix_whitespace.bytes())
8334 .take_while(|(a, b)| a == b)
8335 .count() as u32;
8336 let end = Point::new(
8337 start.row,
8338 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8339 );
8340 start..end
8341 } else {
8342 start..start
8343 }
8344 }
8345
8346 fn comment_suffix_range(
8347 snapshot: &MultiBufferSnapshot,
8348 row: MultiBufferRow,
8349 comment_suffix: &str,
8350 comment_suffix_has_leading_space: bool,
8351 ) -> Range<Point> {
8352 let end = Point::new(row.0, snapshot.line_len(row));
8353 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8354
8355 let mut line_end_bytes = snapshot
8356 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8357 .flatten()
8358 .copied();
8359
8360 let leading_space_len = if suffix_start_column > 0
8361 && line_end_bytes.next() == Some(b' ')
8362 && comment_suffix_has_leading_space
8363 {
8364 1
8365 } else {
8366 0
8367 };
8368
8369 // If this line currently begins with the line comment prefix, then record
8370 // the range containing the prefix.
8371 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8372 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8373 start..end
8374 } else {
8375 end..end
8376 }
8377 }
8378
8379 // TODO: Handle selections that cross excerpts
8380 for selection in &mut selections {
8381 let start_column = snapshot
8382 .indent_size_for_line(MultiBufferRow(selection.start.row))
8383 .len;
8384 let language = if let Some(language) =
8385 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8386 {
8387 language
8388 } else {
8389 continue;
8390 };
8391
8392 selection_edit_ranges.clear();
8393
8394 // If multiple selections contain a given row, avoid processing that
8395 // row more than once.
8396 let mut start_row = MultiBufferRow(selection.start.row);
8397 if last_toggled_row == Some(start_row) {
8398 start_row = start_row.next_row();
8399 }
8400 let end_row =
8401 if selection.end.row > selection.start.row && selection.end.column == 0 {
8402 MultiBufferRow(selection.end.row - 1)
8403 } else {
8404 MultiBufferRow(selection.end.row)
8405 };
8406 last_toggled_row = Some(end_row);
8407
8408 if start_row > end_row {
8409 continue;
8410 }
8411
8412 // If the language has line comments, toggle those.
8413 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8414
8415 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8416 if ignore_indent {
8417 full_comment_prefixes = full_comment_prefixes
8418 .into_iter()
8419 .map(|s| Arc::from(s.trim_end()))
8420 .collect();
8421 }
8422
8423 if !full_comment_prefixes.is_empty() {
8424 let first_prefix = full_comment_prefixes
8425 .first()
8426 .expect("prefixes is non-empty");
8427 let prefix_trimmed_lengths = full_comment_prefixes
8428 .iter()
8429 .map(|p| p.trim_end_matches(' ').len())
8430 .collect::<SmallVec<[usize; 4]>>();
8431
8432 let mut all_selection_lines_are_comments = true;
8433
8434 for row in start_row.0..=end_row.0 {
8435 let row = MultiBufferRow(row);
8436 if start_row < end_row && snapshot.is_line_blank(row) {
8437 continue;
8438 }
8439
8440 let prefix_range = full_comment_prefixes
8441 .iter()
8442 .zip(prefix_trimmed_lengths.iter().copied())
8443 .map(|(prefix, trimmed_prefix_len)| {
8444 comment_prefix_range(
8445 snapshot.deref(),
8446 row,
8447 &prefix[..trimmed_prefix_len],
8448 &prefix[trimmed_prefix_len..],
8449 ignore_indent,
8450 )
8451 })
8452 .max_by_key(|range| range.end.column - range.start.column)
8453 .expect("prefixes is non-empty");
8454
8455 if prefix_range.is_empty() {
8456 all_selection_lines_are_comments = false;
8457 }
8458
8459 selection_edit_ranges.push(prefix_range);
8460 }
8461
8462 if all_selection_lines_are_comments {
8463 edits.extend(
8464 selection_edit_ranges
8465 .iter()
8466 .cloned()
8467 .map(|range| (range, empty_str.clone())),
8468 );
8469 } else {
8470 let min_column = selection_edit_ranges
8471 .iter()
8472 .map(|range| range.start.column)
8473 .min()
8474 .unwrap_or(0);
8475 edits.extend(selection_edit_ranges.iter().map(|range| {
8476 let position = Point::new(range.start.row, min_column);
8477 (position..position, first_prefix.clone())
8478 }));
8479 }
8480 } else if let Some((full_comment_prefix, comment_suffix)) =
8481 language.block_comment_delimiters()
8482 {
8483 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8484 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8485 let prefix_range = comment_prefix_range(
8486 snapshot.deref(),
8487 start_row,
8488 comment_prefix,
8489 comment_prefix_whitespace,
8490 ignore_indent,
8491 );
8492 let suffix_range = comment_suffix_range(
8493 snapshot.deref(),
8494 end_row,
8495 comment_suffix.trim_start_matches(' '),
8496 comment_suffix.starts_with(' '),
8497 );
8498
8499 if prefix_range.is_empty() || suffix_range.is_empty() {
8500 edits.push((
8501 prefix_range.start..prefix_range.start,
8502 full_comment_prefix.clone(),
8503 ));
8504 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8505 suffixes_inserted.push((end_row, comment_suffix.len()));
8506 } else {
8507 edits.push((prefix_range, empty_str.clone()));
8508 edits.push((suffix_range, empty_str.clone()));
8509 }
8510 } else {
8511 continue;
8512 }
8513 }
8514
8515 drop(snapshot);
8516 this.buffer.update(cx, |buffer, cx| {
8517 buffer.edit(edits, None, cx);
8518 });
8519
8520 // Adjust selections so that they end before any comment suffixes that
8521 // were inserted.
8522 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8523 let mut selections = this.selections.all::<Point>(cx);
8524 let snapshot = this.buffer.read(cx).read(cx);
8525 for selection in &mut selections {
8526 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8527 match row.cmp(&MultiBufferRow(selection.end.row)) {
8528 Ordering::Less => {
8529 suffixes_inserted.next();
8530 continue;
8531 }
8532 Ordering::Greater => break,
8533 Ordering::Equal => {
8534 if selection.end.column == snapshot.line_len(row) {
8535 if selection.is_empty() {
8536 selection.start.column -= suffix_len as u32;
8537 }
8538 selection.end.column -= suffix_len as u32;
8539 }
8540 break;
8541 }
8542 }
8543 }
8544 }
8545
8546 drop(snapshot);
8547 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8548
8549 let selections = this.selections.all::<Point>(cx);
8550 let selections_on_single_row = selections.windows(2).all(|selections| {
8551 selections[0].start.row == selections[1].start.row
8552 && selections[0].end.row == selections[1].end.row
8553 && selections[0].start.row == selections[0].end.row
8554 });
8555 let selections_selecting = selections
8556 .iter()
8557 .any(|selection| selection.start != selection.end);
8558 let advance_downwards = action.advance_downwards
8559 && selections_on_single_row
8560 && !selections_selecting
8561 && !matches!(this.mode, EditorMode::SingleLine { .. });
8562
8563 if advance_downwards {
8564 let snapshot = this.buffer.read(cx).snapshot(cx);
8565
8566 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8567 s.move_cursors_with(|display_snapshot, display_point, _| {
8568 let mut point = display_point.to_point(display_snapshot);
8569 point.row += 1;
8570 point = snapshot.clip_point(point, Bias::Left);
8571 let display_point = point.to_display_point(display_snapshot);
8572 let goal = SelectionGoal::HorizontalPosition(
8573 display_snapshot
8574 .x_for_display_point(display_point, text_layout_details)
8575 .into(),
8576 );
8577 (display_point, goal)
8578 })
8579 });
8580 }
8581 });
8582 }
8583
8584 pub fn select_enclosing_symbol(
8585 &mut self,
8586 _: &SelectEnclosingSymbol,
8587 cx: &mut ViewContext<Self>,
8588 ) {
8589 let buffer = self.buffer.read(cx).snapshot(cx);
8590 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8591
8592 fn update_selection(
8593 selection: &Selection<usize>,
8594 buffer_snap: &MultiBufferSnapshot,
8595 ) -> Option<Selection<usize>> {
8596 let cursor = selection.head();
8597 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8598 for symbol in symbols.iter().rev() {
8599 let start = symbol.range.start.to_offset(buffer_snap);
8600 let end = symbol.range.end.to_offset(buffer_snap);
8601 let new_range = start..end;
8602 if start < selection.start || end > selection.end {
8603 return Some(Selection {
8604 id: selection.id,
8605 start: new_range.start,
8606 end: new_range.end,
8607 goal: SelectionGoal::None,
8608 reversed: selection.reversed,
8609 });
8610 }
8611 }
8612 None
8613 }
8614
8615 let mut selected_larger_symbol = false;
8616 let new_selections = old_selections
8617 .iter()
8618 .map(|selection| match update_selection(selection, &buffer) {
8619 Some(new_selection) => {
8620 if new_selection.range() != selection.range() {
8621 selected_larger_symbol = true;
8622 }
8623 new_selection
8624 }
8625 None => selection.clone(),
8626 })
8627 .collect::<Vec<_>>();
8628
8629 if selected_larger_symbol {
8630 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8631 s.select(new_selections);
8632 });
8633 }
8634 }
8635
8636 pub fn select_larger_syntax_node(
8637 &mut self,
8638 _: &SelectLargerSyntaxNode,
8639 cx: &mut ViewContext<Self>,
8640 ) {
8641 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8642 let buffer = self.buffer.read(cx).snapshot(cx);
8643 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8644
8645 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8646 let mut selected_larger_node = false;
8647 let new_selections = old_selections
8648 .iter()
8649 .map(|selection| {
8650 let old_range = selection.start..selection.end;
8651 let mut new_range = old_range.clone();
8652 while let Some(containing_range) =
8653 buffer.range_for_syntax_ancestor(new_range.clone())
8654 {
8655 new_range = containing_range;
8656 if !display_map.intersects_fold(new_range.start)
8657 && !display_map.intersects_fold(new_range.end)
8658 {
8659 break;
8660 }
8661 }
8662
8663 selected_larger_node |= new_range != old_range;
8664 Selection {
8665 id: selection.id,
8666 start: new_range.start,
8667 end: new_range.end,
8668 goal: SelectionGoal::None,
8669 reversed: selection.reversed,
8670 }
8671 })
8672 .collect::<Vec<_>>();
8673
8674 if selected_larger_node {
8675 stack.push(old_selections);
8676 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8677 s.select(new_selections);
8678 });
8679 }
8680 self.select_larger_syntax_node_stack = stack;
8681 }
8682
8683 pub fn select_smaller_syntax_node(
8684 &mut self,
8685 _: &SelectSmallerSyntaxNode,
8686 cx: &mut ViewContext<Self>,
8687 ) {
8688 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8689 if let Some(selections) = stack.pop() {
8690 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8691 s.select(selections.to_vec());
8692 });
8693 }
8694 self.select_larger_syntax_node_stack = stack;
8695 }
8696
8697 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8698 if !EditorSettings::get_global(cx).gutter.runnables {
8699 self.clear_tasks();
8700 return Task::ready(());
8701 }
8702 let project = self.project.as_ref().map(Model::downgrade);
8703 cx.spawn(|this, mut cx| async move {
8704 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
8705 let Some(project) = project.and_then(|p| p.upgrade()) else {
8706 return;
8707 };
8708 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8709 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8710 }) else {
8711 return;
8712 };
8713
8714 let hide_runnables = project
8715 .update(&mut cx, |project, cx| {
8716 // Do not display any test indicators in non-dev server remote projects.
8717 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8718 })
8719 .unwrap_or(true);
8720 if hide_runnables {
8721 return;
8722 }
8723 let new_rows =
8724 cx.background_executor()
8725 .spawn({
8726 let snapshot = display_snapshot.clone();
8727 async move {
8728 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8729 }
8730 })
8731 .await;
8732 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8733
8734 this.update(&mut cx, |this, _| {
8735 this.clear_tasks();
8736 for (key, value) in rows {
8737 this.insert_tasks(key, value);
8738 }
8739 })
8740 .ok();
8741 })
8742 }
8743 fn fetch_runnable_ranges(
8744 snapshot: &DisplaySnapshot,
8745 range: Range<Anchor>,
8746 ) -> Vec<language::RunnableRange> {
8747 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8748 }
8749
8750 fn runnable_rows(
8751 project: Model<Project>,
8752 snapshot: DisplaySnapshot,
8753 runnable_ranges: Vec<RunnableRange>,
8754 mut cx: AsyncWindowContext,
8755 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8756 runnable_ranges
8757 .into_iter()
8758 .filter_map(|mut runnable| {
8759 let tasks = cx
8760 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8761 .ok()?;
8762 if tasks.is_empty() {
8763 return None;
8764 }
8765
8766 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8767
8768 let row = snapshot
8769 .buffer_snapshot
8770 .buffer_line_for_row(MultiBufferRow(point.row))?
8771 .1
8772 .start
8773 .row;
8774
8775 let context_range =
8776 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8777 Some((
8778 (runnable.buffer_id, row),
8779 RunnableTasks {
8780 templates: tasks,
8781 offset: MultiBufferOffset(runnable.run_range.start),
8782 context_range,
8783 column: point.column,
8784 extra_variables: runnable.extra_captures,
8785 },
8786 ))
8787 })
8788 .collect()
8789 }
8790
8791 fn templates_with_tags(
8792 project: &Model<Project>,
8793 runnable: &mut Runnable,
8794 cx: &WindowContext<'_>,
8795 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8796 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8797 let (worktree_id, file) = project
8798 .buffer_for_id(runnable.buffer, cx)
8799 .and_then(|buffer| buffer.read(cx).file())
8800 .map(|file| (file.worktree_id(cx), file.clone()))
8801 .unzip();
8802
8803 (
8804 project.task_store().read(cx).task_inventory().cloned(),
8805 worktree_id,
8806 file,
8807 )
8808 });
8809
8810 let tags = mem::take(&mut runnable.tags);
8811 let mut tags: Vec<_> = tags
8812 .into_iter()
8813 .flat_map(|tag| {
8814 let tag = tag.0.clone();
8815 inventory
8816 .as_ref()
8817 .into_iter()
8818 .flat_map(|inventory| {
8819 inventory.read(cx).list_tasks(
8820 file.clone(),
8821 Some(runnable.language.clone()),
8822 worktree_id,
8823 cx,
8824 )
8825 })
8826 .filter(move |(_, template)| {
8827 template.tags.iter().any(|source_tag| source_tag == &tag)
8828 })
8829 })
8830 .sorted_by_key(|(kind, _)| kind.to_owned())
8831 .collect();
8832 if let Some((leading_tag_source, _)) = tags.first() {
8833 // Strongest source wins; if we have worktree tag binding, prefer that to
8834 // global and language bindings;
8835 // if we have a global binding, prefer that to language binding.
8836 let first_mismatch = tags
8837 .iter()
8838 .position(|(tag_source, _)| tag_source != leading_tag_source);
8839 if let Some(index) = first_mismatch {
8840 tags.truncate(index);
8841 }
8842 }
8843
8844 tags
8845 }
8846
8847 pub fn move_to_enclosing_bracket(
8848 &mut self,
8849 _: &MoveToEnclosingBracket,
8850 cx: &mut ViewContext<Self>,
8851 ) {
8852 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8853 s.move_offsets_with(|snapshot, selection| {
8854 let Some(enclosing_bracket_ranges) =
8855 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
8856 else {
8857 return;
8858 };
8859
8860 let mut best_length = usize::MAX;
8861 let mut best_inside = false;
8862 let mut best_in_bracket_range = false;
8863 let mut best_destination = None;
8864 for (open, close) in enclosing_bracket_ranges {
8865 let close = close.to_inclusive();
8866 let length = close.end() - open.start;
8867 let inside = selection.start >= open.end && selection.end <= *close.start();
8868 let in_bracket_range = open.to_inclusive().contains(&selection.head())
8869 || close.contains(&selection.head());
8870
8871 // If best is next to a bracket and current isn't, skip
8872 if !in_bracket_range && best_in_bracket_range {
8873 continue;
8874 }
8875
8876 // Prefer smaller lengths unless best is inside and current isn't
8877 if length > best_length && (best_inside || !inside) {
8878 continue;
8879 }
8880
8881 best_length = length;
8882 best_inside = inside;
8883 best_in_bracket_range = in_bracket_range;
8884 best_destination = Some(
8885 if close.contains(&selection.start) && close.contains(&selection.end) {
8886 if inside {
8887 open.end
8888 } else {
8889 open.start
8890 }
8891 } else if inside {
8892 *close.start()
8893 } else {
8894 *close.end()
8895 },
8896 );
8897 }
8898
8899 if let Some(destination) = best_destination {
8900 selection.collapse_to(destination, SelectionGoal::None);
8901 }
8902 })
8903 });
8904 }
8905
8906 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
8907 self.end_selection(cx);
8908 self.selection_history.mode = SelectionHistoryMode::Undoing;
8909 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
8910 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8911 self.select_next_state = entry.select_next_state;
8912 self.select_prev_state = entry.select_prev_state;
8913 self.add_selections_state = entry.add_selections_state;
8914 self.request_autoscroll(Autoscroll::newest(), cx);
8915 }
8916 self.selection_history.mode = SelectionHistoryMode::Normal;
8917 }
8918
8919 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
8920 self.end_selection(cx);
8921 self.selection_history.mode = SelectionHistoryMode::Redoing;
8922 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
8923 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8924 self.select_next_state = entry.select_next_state;
8925 self.select_prev_state = entry.select_prev_state;
8926 self.add_selections_state = entry.add_selections_state;
8927 self.request_autoscroll(Autoscroll::newest(), cx);
8928 }
8929 self.selection_history.mode = SelectionHistoryMode::Normal;
8930 }
8931
8932 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
8933 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
8934 }
8935
8936 pub fn expand_excerpts_down(
8937 &mut self,
8938 action: &ExpandExcerptsDown,
8939 cx: &mut ViewContext<Self>,
8940 ) {
8941 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
8942 }
8943
8944 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
8945 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
8946 }
8947
8948 pub fn expand_excerpts_for_direction(
8949 &mut self,
8950 lines: u32,
8951 direction: ExpandExcerptDirection,
8952 cx: &mut ViewContext<Self>,
8953 ) {
8954 let selections = self.selections.disjoint_anchors();
8955
8956 let lines = if lines == 0 {
8957 EditorSettings::get_global(cx).expand_excerpt_lines
8958 } else {
8959 lines
8960 };
8961
8962 self.buffer.update(cx, |buffer, cx| {
8963 buffer.expand_excerpts(
8964 selections
8965 .iter()
8966 .map(|selection| selection.head().excerpt_id)
8967 .dedup(),
8968 lines,
8969 direction,
8970 cx,
8971 )
8972 })
8973 }
8974
8975 pub fn expand_excerpt(
8976 &mut self,
8977 excerpt: ExcerptId,
8978 direction: ExpandExcerptDirection,
8979 cx: &mut ViewContext<Self>,
8980 ) {
8981 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
8982 self.buffer.update(cx, |buffer, cx| {
8983 buffer.expand_excerpts([excerpt], lines, direction, cx)
8984 })
8985 }
8986
8987 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
8988 self.go_to_diagnostic_impl(Direction::Next, cx)
8989 }
8990
8991 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
8992 self.go_to_diagnostic_impl(Direction::Prev, cx)
8993 }
8994
8995 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
8996 let buffer = self.buffer.read(cx).snapshot(cx);
8997 let selection = self.selections.newest::<usize>(cx);
8998
8999 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9000 if direction == Direction::Next {
9001 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9002 let (group_id, jump_to) = popover.activation_info();
9003 if self.activate_diagnostics(group_id, cx) {
9004 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9005 let mut new_selection = s.newest_anchor().clone();
9006 new_selection.collapse_to(jump_to, SelectionGoal::None);
9007 s.select_anchors(vec![new_selection.clone()]);
9008 });
9009 }
9010 return;
9011 }
9012 }
9013
9014 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9015 active_diagnostics
9016 .primary_range
9017 .to_offset(&buffer)
9018 .to_inclusive()
9019 });
9020 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9021 if active_primary_range.contains(&selection.head()) {
9022 *active_primary_range.start()
9023 } else {
9024 selection.head()
9025 }
9026 } else {
9027 selection.head()
9028 };
9029 let snapshot = self.snapshot(cx);
9030 loop {
9031 let diagnostics = if direction == Direction::Prev {
9032 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9033 } else {
9034 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9035 }
9036 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9037 let group = diagnostics
9038 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9039 // be sorted in a stable way
9040 // skip until we are at current active diagnostic, if it exists
9041 .skip_while(|entry| {
9042 (match direction {
9043 Direction::Prev => entry.range.start >= search_start,
9044 Direction::Next => entry.range.start <= search_start,
9045 }) && self
9046 .active_diagnostics
9047 .as_ref()
9048 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9049 })
9050 .find_map(|entry| {
9051 if entry.diagnostic.is_primary
9052 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9053 && !entry.range.is_empty()
9054 // if we match with the active diagnostic, skip it
9055 && Some(entry.diagnostic.group_id)
9056 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9057 {
9058 Some((entry.range, entry.diagnostic.group_id))
9059 } else {
9060 None
9061 }
9062 });
9063
9064 if let Some((primary_range, group_id)) = group {
9065 if self.activate_diagnostics(group_id, cx) {
9066 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9067 s.select(vec![Selection {
9068 id: selection.id,
9069 start: primary_range.start,
9070 end: primary_range.start,
9071 reversed: false,
9072 goal: SelectionGoal::None,
9073 }]);
9074 });
9075 }
9076 break;
9077 } else {
9078 // Cycle around to the start of the buffer, potentially moving back to the start of
9079 // the currently active diagnostic.
9080 active_primary_range.take();
9081 if direction == Direction::Prev {
9082 if search_start == buffer.len() {
9083 break;
9084 } else {
9085 search_start = buffer.len();
9086 }
9087 } else if search_start == 0 {
9088 break;
9089 } else {
9090 search_start = 0;
9091 }
9092 }
9093 }
9094 }
9095
9096 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9097 let snapshot = self.snapshot(cx);
9098 let selection = self.selections.newest::<Point>(cx);
9099 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9100 }
9101
9102 fn go_to_hunk_after_position(
9103 &mut self,
9104 snapshot: &EditorSnapshot,
9105 position: Point,
9106 cx: &mut ViewContext<'_, Editor>,
9107 ) -> Option<MultiBufferDiffHunk> {
9108 for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
9109 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9110 snapshot,
9111 position,
9112 ix > 0,
9113 snapshot.diff_map.diff_hunks_in_range(
9114 position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
9115 &snapshot.buffer_snapshot,
9116 ),
9117 cx,
9118 ) {
9119 return Some(hunk);
9120 }
9121 }
9122 None
9123 }
9124
9125 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9126 let snapshot = self.snapshot(cx);
9127 let selection = self.selections.newest::<Point>(cx);
9128 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9129 }
9130
9131 fn go_to_hunk_before_position(
9132 &mut self,
9133 snapshot: &EditorSnapshot,
9134 position: Point,
9135 cx: &mut ViewContext<'_, Editor>,
9136 ) -> Option<MultiBufferDiffHunk> {
9137 for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
9138 .into_iter()
9139 .enumerate()
9140 {
9141 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9142 snapshot,
9143 position,
9144 ix > 0,
9145 snapshot
9146 .diff_map
9147 .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
9148 cx,
9149 ) {
9150 return Some(hunk);
9151 }
9152 }
9153 None
9154 }
9155
9156 fn go_to_next_hunk_in_direction(
9157 &mut self,
9158 snapshot: &DisplaySnapshot,
9159 initial_point: Point,
9160 is_wrapped: bool,
9161 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9162 cx: &mut ViewContext<Editor>,
9163 ) -> Option<MultiBufferDiffHunk> {
9164 let display_point = initial_point.to_display_point(snapshot);
9165 let mut hunks = hunks
9166 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9167 .filter(|(display_hunk, _)| {
9168 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9169 })
9170 .dedup();
9171
9172 if let Some((display_hunk, hunk)) = hunks.next() {
9173 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9174 let row = display_hunk.start_display_row();
9175 let point = DisplayPoint::new(row, 0);
9176 s.select_display_ranges([point..point]);
9177 });
9178
9179 Some(hunk)
9180 } else {
9181 None
9182 }
9183 }
9184
9185 pub fn go_to_definition(
9186 &mut self,
9187 _: &GoToDefinition,
9188 cx: &mut ViewContext<Self>,
9189 ) -> Task<Result<Navigated>> {
9190 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9191 cx.spawn(|editor, mut cx| async move {
9192 if definition.await? == Navigated::Yes {
9193 return Ok(Navigated::Yes);
9194 }
9195 match editor.update(&mut cx, |editor, cx| {
9196 editor.find_all_references(&FindAllReferences, cx)
9197 })? {
9198 Some(references) => references.await,
9199 None => Ok(Navigated::No),
9200 }
9201 })
9202 }
9203
9204 pub fn go_to_declaration(
9205 &mut self,
9206 _: &GoToDeclaration,
9207 cx: &mut ViewContext<Self>,
9208 ) -> Task<Result<Navigated>> {
9209 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9210 }
9211
9212 pub fn go_to_declaration_split(
9213 &mut self,
9214 _: &GoToDeclaration,
9215 cx: &mut ViewContext<Self>,
9216 ) -> Task<Result<Navigated>> {
9217 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9218 }
9219
9220 pub fn go_to_implementation(
9221 &mut self,
9222 _: &GoToImplementation,
9223 cx: &mut ViewContext<Self>,
9224 ) -> Task<Result<Navigated>> {
9225 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9226 }
9227
9228 pub fn go_to_implementation_split(
9229 &mut self,
9230 _: &GoToImplementationSplit,
9231 cx: &mut ViewContext<Self>,
9232 ) -> Task<Result<Navigated>> {
9233 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9234 }
9235
9236 pub fn go_to_type_definition(
9237 &mut self,
9238 _: &GoToTypeDefinition,
9239 cx: &mut ViewContext<Self>,
9240 ) -> Task<Result<Navigated>> {
9241 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9242 }
9243
9244 pub fn go_to_definition_split(
9245 &mut self,
9246 _: &GoToDefinitionSplit,
9247 cx: &mut ViewContext<Self>,
9248 ) -> Task<Result<Navigated>> {
9249 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9250 }
9251
9252 pub fn go_to_type_definition_split(
9253 &mut self,
9254 _: &GoToTypeDefinitionSplit,
9255 cx: &mut ViewContext<Self>,
9256 ) -> Task<Result<Navigated>> {
9257 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9258 }
9259
9260 fn go_to_definition_of_kind(
9261 &mut self,
9262 kind: GotoDefinitionKind,
9263 split: bool,
9264 cx: &mut ViewContext<Self>,
9265 ) -> Task<Result<Navigated>> {
9266 let Some(provider) = self.semantics_provider.clone() else {
9267 return Task::ready(Ok(Navigated::No));
9268 };
9269 let head = self.selections.newest::<usize>(cx).head();
9270 let buffer = self.buffer.read(cx);
9271 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9272 text_anchor
9273 } else {
9274 return Task::ready(Ok(Navigated::No));
9275 };
9276
9277 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9278 return Task::ready(Ok(Navigated::No));
9279 };
9280
9281 cx.spawn(|editor, mut cx| async move {
9282 let definitions = definitions.await?;
9283 let navigated = editor
9284 .update(&mut cx, |editor, cx| {
9285 editor.navigate_to_hover_links(
9286 Some(kind),
9287 definitions
9288 .into_iter()
9289 .filter(|location| {
9290 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9291 })
9292 .map(HoverLink::Text)
9293 .collect::<Vec<_>>(),
9294 split,
9295 cx,
9296 )
9297 })?
9298 .await?;
9299 anyhow::Ok(navigated)
9300 })
9301 }
9302
9303 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9304 let selection = self.selections.newest_anchor();
9305 let head = selection.head();
9306 let tail = selection.tail();
9307
9308 let Some((buffer, start_position)) =
9309 self.buffer.read(cx).text_anchor_for_position(head, cx)
9310 else {
9311 return;
9312 };
9313
9314 let end_position = if head != tail {
9315 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
9316 return;
9317 };
9318 Some(pos)
9319 } else {
9320 None
9321 };
9322
9323 let url_finder = cx.spawn(|editor, mut cx| async move {
9324 let url = if let Some(end_pos) = end_position {
9325 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
9326 } else {
9327 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
9328 };
9329
9330 if let Some(url) = url {
9331 editor.update(&mut cx, |_, cx| {
9332 cx.open_url(&url);
9333 })
9334 } else {
9335 Ok(())
9336 }
9337 });
9338
9339 url_finder.detach();
9340 }
9341
9342 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9343 let Some(workspace) = self.workspace() else {
9344 return;
9345 };
9346
9347 let position = self.selections.newest_anchor().head();
9348
9349 let Some((buffer, buffer_position)) =
9350 self.buffer.read(cx).text_anchor_for_position(position, cx)
9351 else {
9352 return;
9353 };
9354
9355 let project = self.project.clone();
9356
9357 cx.spawn(|_, mut cx| async move {
9358 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9359
9360 if let Some((_, path)) = result {
9361 workspace
9362 .update(&mut cx, |workspace, cx| {
9363 workspace.open_resolved_path(path, cx)
9364 })?
9365 .await?;
9366 }
9367 anyhow::Ok(())
9368 })
9369 .detach();
9370 }
9371
9372 pub(crate) fn navigate_to_hover_links(
9373 &mut self,
9374 kind: Option<GotoDefinitionKind>,
9375 mut definitions: Vec<HoverLink>,
9376 split: bool,
9377 cx: &mut ViewContext<Editor>,
9378 ) -> Task<Result<Navigated>> {
9379 // If there is one definition, just open it directly
9380 if definitions.len() == 1 {
9381 let definition = definitions.pop().unwrap();
9382
9383 enum TargetTaskResult {
9384 Location(Option<Location>),
9385 AlreadyNavigated,
9386 }
9387
9388 let target_task = match definition {
9389 HoverLink::Text(link) => {
9390 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9391 }
9392 HoverLink::InlayHint(lsp_location, server_id) => {
9393 let computation = self.compute_target_location(lsp_location, server_id, cx);
9394 cx.background_executor().spawn(async move {
9395 let location = computation.await?;
9396 Ok(TargetTaskResult::Location(location))
9397 })
9398 }
9399 HoverLink::Url(url) => {
9400 cx.open_url(&url);
9401 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9402 }
9403 HoverLink::File(path) => {
9404 if let Some(workspace) = self.workspace() {
9405 cx.spawn(|_, mut cx| async move {
9406 workspace
9407 .update(&mut cx, |workspace, cx| {
9408 workspace.open_resolved_path(path, cx)
9409 })?
9410 .await
9411 .map(|_| TargetTaskResult::AlreadyNavigated)
9412 })
9413 } else {
9414 Task::ready(Ok(TargetTaskResult::Location(None)))
9415 }
9416 }
9417 };
9418 cx.spawn(|editor, mut cx| async move {
9419 let target = match target_task.await.context("target resolution task")? {
9420 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9421 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9422 TargetTaskResult::Location(Some(target)) => target,
9423 };
9424
9425 editor.update(&mut cx, |editor, cx| {
9426 let Some(workspace) = editor.workspace() else {
9427 return Navigated::No;
9428 };
9429 let pane = workspace.read(cx).active_pane().clone();
9430
9431 let range = target.range.to_offset(target.buffer.read(cx));
9432 let range = editor.range_for_match(&range);
9433
9434 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9435 let buffer = target.buffer.read(cx);
9436 let range = check_multiline_range(buffer, range);
9437 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9438 s.select_ranges([range]);
9439 });
9440 } else {
9441 cx.window_context().defer(move |cx| {
9442 let target_editor: View<Self> =
9443 workspace.update(cx, |workspace, cx| {
9444 let pane = if split {
9445 workspace.adjacent_pane(cx)
9446 } else {
9447 workspace.active_pane().clone()
9448 };
9449
9450 workspace.open_project_item(
9451 pane,
9452 target.buffer.clone(),
9453 true,
9454 true,
9455 cx,
9456 )
9457 });
9458 target_editor.update(cx, |target_editor, cx| {
9459 // When selecting a definition in a different buffer, disable the nav history
9460 // to avoid creating a history entry at the previous cursor location.
9461 pane.update(cx, |pane, _| pane.disable_history());
9462 let buffer = target.buffer.read(cx);
9463 let range = check_multiline_range(buffer, range);
9464 target_editor.change_selections(
9465 Some(Autoscroll::focused()),
9466 cx,
9467 |s| {
9468 s.select_ranges([range]);
9469 },
9470 );
9471 pane.update(cx, |pane, _| pane.enable_history());
9472 });
9473 });
9474 }
9475 Navigated::Yes
9476 })
9477 })
9478 } else if !definitions.is_empty() {
9479 cx.spawn(|editor, mut cx| async move {
9480 let (title, location_tasks, workspace) = editor
9481 .update(&mut cx, |editor, cx| {
9482 let tab_kind = match kind {
9483 Some(GotoDefinitionKind::Implementation) => "Implementations",
9484 _ => "Definitions",
9485 };
9486 let title = definitions
9487 .iter()
9488 .find_map(|definition| match definition {
9489 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9490 let buffer = origin.buffer.read(cx);
9491 format!(
9492 "{} for {}",
9493 tab_kind,
9494 buffer
9495 .text_for_range(origin.range.clone())
9496 .collect::<String>()
9497 )
9498 }),
9499 HoverLink::InlayHint(_, _) => None,
9500 HoverLink::Url(_) => None,
9501 HoverLink::File(_) => None,
9502 })
9503 .unwrap_or(tab_kind.to_string());
9504 let location_tasks = definitions
9505 .into_iter()
9506 .map(|definition| match definition {
9507 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
9508 HoverLink::InlayHint(lsp_location, server_id) => {
9509 editor.compute_target_location(lsp_location, server_id, cx)
9510 }
9511 HoverLink::Url(_) => Task::ready(Ok(None)),
9512 HoverLink::File(_) => Task::ready(Ok(None)),
9513 })
9514 .collect::<Vec<_>>();
9515 (title, location_tasks, editor.workspace().clone())
9516 })
9517 .context("location tasks preparation")?;
9518
9519 let locations = future::join_all(location_tasks)
9520 .await
9521 .into_iter()
9522 .filter_map(|location| location.transpose())
9523 .collect::<Result<_>>()
9524 .context("location tasks")?;
9525
9526 let Some(workspace) = workspace else {
9527 return Ok(Navigated::No);
9528 };
9529 let opened = workspace
9530 .update(&mut cx, |workspace, cx| {
9531 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9532 })
9533 .ok();
9534
9535 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9536 })
9537 } else {
9538 Task::ready(Ok(Navigated::No))
9539 }
9540 }
9541
9542 fn compute_target_location(
9543 &self,
9544 lsp_location: lsp::Location,
9545 server_id: LanguageServerId,
9546 cx: &mut ViewContext<Self>,
9547 ) -> Task<anyhow::Result<Option<Location>>> {
9548 let Some(project) = self.project.clone() else {
9549 return Task::ready(Ok(None));
9550 };
9551
9552 cx.spawn(move |editor, mut cx| async move {
9553 let location_task = editor.update(&mut cx, |_, cx| {
9554 project.update(cx, |project, cx| {
9555 let language_server_name = project
9556 .language_server_statuses(cx)
9557 .find(|(id, _)| server_id == *id)
9558 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
9559 language_server_name.map(|language_server_name| {
9560 project.open_local_buffer_via_lsp(
9561 lsp_location.uri.clone(),
9562 server_id,
9563 language_server_name,
9564 cx,
9565 )
9566 })
9567 })
9568 })?;
9569 let location = match location_task {
9570 Some(task) => Some({
9571 let target_buffer_handle = task.await.context("open local buffer")?;
9572 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9573 let target_start = target_buffer
9574 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9575 let target_end = target_buffer
9576 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9577 target_buffer.anchor_after(target_start)
9578 ..target_buffer.anchor_before(target_end)
9579 })?;
9580 Location {
9581 buffer: target_buffer_handle,
9582 range,
9583 }
9584 }),
9585 None => None,
9586 };
9587 Ok(location)
9588 })
9589 }
9590
9591 pub fn find_all_references(
9592 &mut self,
9593 _: &FindAllReferences,
9594 cx: &mut ViewContext<Self>,
9595 ) -> Option<Task<Result<Navigated>>> {
9596 let selection = self.selections.newest::<usize>(cx);
9597 let multi_buffer = self.buffer.read(cx);
9598 let head = selection.head();
9599
9600 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9601 let head_anchor = multi_buffer_snapshot.anchor_at(
9602 head,
9603 if head < selection.tail() {
9604 Bias::Right
9605 } else {
9606 Bias::Left
9607 },
9608 );
9609
9610 match self
9611 .find_all_references_task_sources
9612 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9613 {
9614 Ok(_) => {
9615 log::info!(
9616 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9617 );
9618 return None;
9619 }
9620 Err(i) => {
9621 self.find_all_references_task_sources.insert(i, head_anchor);
9622 }
9623 }
9624
9625 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9626 let workspace = self.workspace()?;
9627 let project = workspace.read(cx).project().clone();
9628 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9629 Some(cx.spawn(|editor, mut cx| async move {
9630 let _cleanup = defer({
9631 let mut cx = cx.clone();
9632 move || {
9633 let _ = editor.update(&mut cx, |editor, _| {
9634 if let Ok(i) =
9635 editor
9636 .find_all_references_task_sources
9637 .binary_search_by(|anchor| {
9638 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9639 })
9640 {
9641 editor.find_all_references_task_sources.remove(i);
9642 }
9643 });
9644 }
9645 });
9646
9647 let locations = references.await?;
9648 if locations.is_empty() {
9649 return anyhow::Ok(Navigated::No);
9650 }
9651
9652 workspace.update(&mut cx, |workspace, cx| {
9653 let title = locations
9654 .first()
9655 .as_ref()
9656 .map(|location| {
9657 let buffer = location.buffer.read(cx);
9658 format!(
9659 "References to `{}`",
9660 buffer
9661 .text_for_range(location.range.clone())
9662 .collect::<String>()
9663 )
9664 })
9665 .unwrap();
9666 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9667 Navigated::Yes
9668 })
9669 }))
9670 }
9671
9672 /// Opens a multibuffer with the given project locations in it
9673 pub fn open_locations_in_multibuffer(
9674 workspace: &mut Workspace,
9675 mut locations: Vec<Location>,
9676 title: String,
9677 split: bool,
9678 cx: &mut ViewContext<Workspace>,
9679 ) {
9680 // If there are multiple definitions, open them in a multibuffer
9681 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9682 let mut locations = locations.into_iter().peekable();
9683 let mut ranges_to_highlight = Vec::new();
9684 let capability = workspace.project().read(cx).capability();
9685
9686 let excerpt_buffer = cx.new_model(|cx| {
9687 let mut multibuffer = MultiBuffer::new(capability);
9688 while let Some(location) = locations.next() {
9689 let buffer = location.buffer.read(cx);
9690 let mut ranges_for_buffer = Vec::new();
9691 let range = location.range.to_offset(buffer);
9692 ranges_for_buffer.push(range.clone());
9693
9694 while let Some(next_location) = locations.peek() {
9695 if next_location.buffer == location.buffer {
9696 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9697 locations.next();
9698 } else {
9699 break;
9700 }
9701 }
9702
9703 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9704 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9705 location.buffer.clone(),
9706 ranges_for_buffer,
9707 DEFAULT_MULTIBUFFER_CONTEXT,
9708 cx,
9709 ))
9710 }
9711
9712 multibuffer.with_title(title)
9713 });
9714
9715 let editor = cx.new_view(|cx| {
9716 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9717 });
9718 editor.update(cx, |editor, cx| {
9719 if let Some(first_range) = ranges_to_highlight.first() {
9720 editor.change_selections(None, cx, |selections| {
9721 selections.clear_disjoint();
9722 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9723 });
9724 }
9725 editor.highlight_background::<Self>(
9726 &ranges_to_highlight,
9727 |theme| theme.editor_highlighted_line_background,
9728 cx,
9729 );
9730 editor.register_buffers_with_language_servers(cx);
9731 });
9732
9733 let item = Box::new(editor);
9734 let item_id = item.item_id();
9735
9736 if split {
9737 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9738 } else {
9739 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9740 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9741 pane.close_current_preview_item(cx)
9742 } else {
9743 None
9744 }
9745 });
9746 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9747 }
9748 workspace.active_pane().update(cx, |pane, cx| {
9749 pane.set_preview_item_id(Some(item_id), cx);
9750 });
9751 }
9752
9753 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9754 use language::ToOffset as _;
9755
9756 let provider = self.semantics_provider.clone()?;
9757 let selection = self.selections.newest_anchor().clone();
9758 let (cursor_buffer, cursor_buffer_position) = self
9759 .buffer
9760 .read(cx)
9761 .text_anchor_for_position(selection.head(), cx)?;
9762 let (tail_buffer, cursor_buffer_position_end) = self
9763 .buffer
9764 .read(cx)
9765 .text_anchor_for_position(selection.tail(), cx)?;
9766 if tail_buffer != cursor_buffer {
9767 return None;
9768 }
9769
9770 let snapshot = cursor_buffer.read(cx).snapshot();
9771 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9772 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9773 let prepare_rename = provider
9774 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
9775 .unwrap_or_else(|| Task::ready(Ok(None)));
9776 drop(snapshot);
9777
9778 Some(cx.spawn(|this, mut cx| async move {
9779 let rename_range = if let Some(range) = prepare_rename.await? {
9780 Some(range)
9781 } else {
9782 this.update(&mut cx, |this, cx| {
9783 let buffer = this.buffer.read(cx).snapshot(cx);
9784 let mut buffer_highlights = this
9785 .document_highlights_for_position(selection.head(), &buffer)
9786 .filter(|highlight| {
9787 highlight.start.excerpt_id == selection.head().excerpt_id
9788 && highlight.end.excerpt_id == selection.head().excerpt_id
9789 });
9790 buffer_highlights
9791 .next()
9792 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9793 })?
9794 };
9795 if let Some(rename_range) = rename_range {
9796 this.update(&mut cx, |this, cx| {
9797 let snapshot = cursor_buffer.read(cx).snapshot();
9798 let rename_buffer_range = rename_range.to_offset(&snapshot);
9799 let cursor_offset_in_rename_range =
9800 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9801 let cursor_offset_in_rename_range_end =
9802 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9803
9804 this.take_rename(false, cx);
9805 let buffer = this.buffer.read(cx).read(cx);
9806 let cursor_offset = selection.head().to_offset(&buffer);
9807 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9808 let rename_end = rename_start + rename_buffer_range.len();
9809 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9810 let mut old_highlight_id = None;
9811 let old_name: Arc<str> = buffer
9812 .chunks(rename_start..rename_end, true)
9813 .map(|chunk| {
9814 if old_highlight_id.is_none() {
9815 old_highlight_id = chunk.syntax_highlight_id;
9816 }
9817 chunk.text
9818 })
9819 .collect::<String>()
9820 .into();
9821
9822 drop(buffer);
9823
9824 // Position the selection in the rename editor so that it matches the current selection.
9825 this.show_local_selections = false;
9826 let rename_editor = cx.new_view(|cx| {
9827 let mut editor = Editor::single_line(cx);
9828 editor.buffer.update(cx, |buffer, cx| {
9829 buffer.edit([(0..0, old_name.clone())], None, cx)
9830 });
9831 let rename_selection_range = match cursor_offset_in_rename_range
9832 .cmp(&cursor_offset_in_rename_range_end)
9833 {
9834 Ordering::Equal => {
9835 editor.select_all(&SelectAll, cx);
9836 return editor;
9837 }
9838 Ordering::Less => {
9839 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9840 }
9841 Ordering::Greater => {
9842 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9843 }
9844 };
9845 if rename_selection_range.end > old_name.len() {
9846 editor.select_all(&SelectAll, cx);
9847 } else {
9848 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9849 s.select_ranges([rename_selection_range]);
9850 });
9851 }
9852 editor
9853 });
9854 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
9855 if e == &EditorEvent::Focused {
9856 cx.emit(EditorEvent::FocusedIn)
9857 }
9858 })
9859 .detach();
9860
9861 let write_highlights =
9862 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
9863 let read_highlights =
9864 this.clear_background_highlights::<DocumentHighlightRead>(cx);
9865 let ranges = write_highlights
9866 .iter()
9867 .flat_map(|(_, ranges)| ranges.iter())
9868 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
9869 .cloned()
9870 .collect();
9871
9872 this.highlight_text::<Rename>(
9873 ranges,
9874 HighlightStyle {
9875 fade_out: Some(0.6),
9876 ..Default::default()
9877 },
9878 cx,
9879 );
9880 let rename_focus_handle = rename_editor.focus_handle(cx);
9881 cx.focus(&rename_focus_handle);
9882 let block_id = this.insert_blocks(
9883 [BlockProperties {
9884 style: BlockStyle::Flex,
9885 placement: BlockPlacement::Below(range.start),
9886 height: 1,
9887 render: Arc::new({
9888 let rename_editor = rename_editor.clone();
9889 move |cx: &mut BlockContext| {
9890 let mut text_style = cx.editor_style.text.clone();
9891 if let Some(highlight_style) = old_highlight_id
9892 .and_then(|h| h.style(&cx.editor_style.syntax))
9893 {
9894 text_style = text_style.highlight(highlight_style);
9895 }
9896 div()
9897 .block_mouse_down()
9898 .pl(cx.anchor_x)
9899 .child(EditorElement::new(
9900 &rename_editor,
9901 EditorStyle {
9902 background: cx.theme().system().transparent,
9903 local_player: cx.editor_style.local_player,
9904 text: text_style,
9905 scrollbar_width: cx.editor_style.scrollbar_width,
9906 syntax: cx.editor_style.syntax.clone(),
9907 status: cx.editor_style.status.clone(),
9908 inlay_hints_style: HighlightStyle {
9909 font_weight: Some(FontWeight::BOLD),
9910 ..make_inlay_hints_style(cx)
9911 },
9912 inline_completion_styles: make_suggestion_styles(
9913 cx,
9914 ),
9915 ..EditorStyle::default()
9916 },
9917 ))
9918 .into_any_element()
9919 }
9920 }),
9921 priority: 0,
9922 }],
9923 Some(Autoscroll::fit()),
9924 cx,
9925 )[0];
9926 this.pending_rename = Some(RenameState {
9927 range,
9928 old_name,
9929 editor: rename_editor,
9930 block_id,
9931 });
9932 })?;
9933 }
9934
9935 Ok(())
9936 }))
9937 }
9938
9939 pub fn confirm_rename(
9940 &mut self,
9941 _: &ConfirmRename,
9942 cx: &mut ViewContext<Self>,
9943 ) -> Option<Task<Result<()>>> {
9944 let rename = self.take_rename(false, cx)?;
9945 let workspace = self.workspace()?.downgrade();
9946 let (buffer, start) = self
9947 .buffer
9948 .read(cx)
9949 .text_anchor_for_position(rename.range.start, cx)?;
9950 let (end_buffer, _) = self
9951 .buffer
9952 .read(cx)
9953 .text_anchor_for_position(rename.range.end, cx)?;
9954 if buffer != end_buffer {
9955 return None;
9956 }
9957
9958 let old_name = rename.old_name;
9959 let new_name = rename.editor.read(cx).text(cx);
9960
9961 let rename = self.semantics_provider.as_ref()?.perform_rename(
9962 &buffer,
9963 start,
9964 new_name.clone(),
9965 cx,
9966 )?;
9967
9968 Some(cx.spawn(|editor, mut cx| async move {
9969 let project_transaction = rename.await?;
9970 Self::open_project_transaction(
9971 &editor,
9972 workspace,
9973 project_transaction,
9974 format!("Rename: {} → {}", old_name, new_name),
9975 cx.clone(),
9976 )
9977 .await?;
9978
9979 editor.update(&mut cx, |editor, cx| {
9980 editor.refresh_document_highlights(cx);
9981 })?;
9982 Ok(())
9983 }))
9984 }
9985
9986 fn take_rename(
9987 &mut self,
9988 moving_cursor: bool,
9989 cx: &mut ViewContext<Self>,
9990 ) -> Option<RenameState> {
9991 let rename = self.pending_rename.take()?;
9992 if rename.editor.focus_handle(cx).is_focused(cx) {
9993 cx.focus(&self.focus_handle);
9994 }
9995
9996 self.remove_blocks(
9997 [rename.block_id].into_iter().collect(),
9998 Some(Autoscroll::fit()),
9999 cx,
10000 );
10001 self.clear_highlights::<Rename>(cx);
10002 self.show_local_selections = true;
10003
10004 if moving_cursor {
10005 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10006 editor.selections.newest::<usize>(cx).head()
10007 });
10008
10009 // Update the selection to match the position of the selection inside
10010 // the rename editor.
10011 let snapshot = self.buffer.read(cx).read(cx);
10012 let rename_range = rename.range.to_offset(&snapshot);
10013 let cursor_in_editor = snapshot
10014 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10015 .min(rename_range.end);
10016 drop(snapshot);
10017
10018 self.change_selections(None, cx, |s| {
10019 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10020 });
10021 } else {
10022 self.refresh_document_highlights(cx);
10023 }
10024
10025 Some(rename)
10026 }
10027
10028 pub fn pending_rename(&self) -> Option<&RenameState> {
10029 self.pending_rename.as_ref()
10030 }
10031
10032 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10033 let project = match &self.project {
10034 Some(project) => project.clone(),
10035 None => return None,
10036 };
10037
10038 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10039 }
10040
10041 fn format_selections(
10042 &mut self,
10043 _: &FormatSelections,
10044 cx: &mut ViewContext<Self>,
10045 ) -> Option<Task<Result<()>>> {
10046 let project = match &self.project {
10047 Some(project) => project.clone(),
10048 None => return None,
10049 };
10050
10051 let selections = self
10052 .selections
10053 .all_adjusted(cx)
10054 .into_iter()
10055 .filter(|s| !s.is_empty())
10056 .collect_vec();
10057
10058 Some(self.perform_format(
10059 project,
10060 FormatTrigger::Manual,
10061 FormatTarget::Ranges(selections),
10062 cx,
10063 ))
10064 }
10065
10066 fn perform_format(
10067 &mut self,
10068 project: Model<Project>,
10069 trigger: FormatTrigger,
10070 target: FormatTarget,
10071 cx: &mut ViewContext<Self>,
10072 ) -> Task<Result<()>> {
10073 let buffer = self.buffer().clone();
10074 let mut buffers = buffer.read(cx).all_buffers();
10075 if trigger == FormatTrigger::Save {
10076 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10077 }
10078
10079 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10080 let format = project.update(cx, |project, cx| {
10081 project.format(buffers, true, trigger, target, cx)
10082 });
10083
10084 cx.spawn(|_, mut cx| async move {
10085 let transaction = futures::select_biased! {
10086 () = timeout => {
10087 log::warn!("timed out waiting for formatting");
10088 None
10089 }
10090 transaction = format.log_err().fuse() => transaction,
10091 };
10092
10093 buffer
10094 .update(&mut cx, |buffer, cx| {
10095 if let Some(transaction) = transaction {
10096 if !buffer.is_singleton() {
10097 buffer.push_transaction(&transaction.0, cx);
10098 }
10099 }
10100
10101 cx.notify();
10102 })
10103 .ok();
10104
10105 Ok(())
10106 })
10107 }
10108
10109 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10110 if let Some(project) = self.project.clone() {
10111 self.buffer.update(cx, |multi_buffer, cx| {
10112 project.update(cx, |project, cx| {
10113 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10114 });
10115 })
10116 }
10117 }
10118
10119 fn cancel_language_server_work(
10120 &mut self,
10121 _: &actions::CancelLanguageServerWork,
10122 cx: &mut ViewContext<Self>,
10123 ) {
10124 if let Some(project) = self.project.clone() {
10125 self.buffer.update(cx, |multi_buffer, cx| {
10126 project.update(cx, |project, cx| {
10127 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10128 });
10129 })
10130 }
10131 }
10132
10133 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10134 cx.show_character_palette();
10135 }
10136
10137 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10138 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10139 let buffer = self.buffer.read(cx).snapshot(cx);
10140 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10141 let is_valid = buffer
10142 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10143 .any(|entry| {
10144 entry.diagnostic.is_primary
10145 && !entry.range.is_empty()
10146 && entry.range.start == primary_range_start
10147 && entry.diagnostic.message == active_diagnostics.primary_message
10148 });
10149
10150 if is_valid != active_diagnostics.is_valid {
10151 active_diagnostics.is_valid = is_valid;
10152 let mut new_styles = HashMap::default();
10153 for (block_id, diagnostic) in &active_diagnostics.blocks {
10154 new_styles.insert(
10155 *block_id,
10156 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10157 );
10158 }
10159 self.display_map.update(cx, |display_map, _cx| {
10160 display_map.replace_blocks(new_styles)
10161 });
10162 }
10163 }
10164 }
10165
10166 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10167 self.dismiss_diagnostics(cx);
10168 let snapshot = self.snapshot(cx);
10169 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10170 let buffer = self.buffer.read(cx).snapshot(cx);
10171
10172 let mut primary_range = None;
10173 let mut primary_message = None;
10174 let mut group_end = Point::zero();
10175 let diagnostic_group = buffer
10176 .diagnostic_group::<MultiBufferPoint>(group_id)
10177 .filter_map(|entry| {
10178 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10179 && (entry.range.start.row == entry.range.end.row
10180 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10181 {
10182 return None;
10183 }
10184 if entry.range.end > group_end {
10185 group_end = entry.range.end;
10186 }
10187 if entry.diagnostic.is_primary {
10188 primary_range = Some(entry.range.clone());
10189 primary_message = Some(entry.diagnostic.message.clone());
10190 }
10191 Some(entry)
10192 })
10193 .collect::<Vec<_>>();
10194 let primary_range = primary_range?;
10195 let primary_message = primary_message?;
10196 let primary_range =
10197 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10198
10199 let blocks = display_map
10200 .insert_blocks(
10201 diagnostic_group.iter().map(|entry| {
10202 let diagnostic = entry.diagnostic.clone();
10203 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10204 BlockProperties {
10205 style: BlockStyle::Fixed,
10206 placement: BlockPlacement::Below(
10207 buffer.anchor_after(entry.range.start),
10208 ),
10209 height: message_height,
10210 render: diagnostic_block_renderer(diagnostic, None, true, true),
10211 priority: 0,
10212 }
10213 }),
10214 cx,
10215 )
10216 .into_iter()
10217 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10218 .collect();
10219
10220 Some(ActiveDiagnosticGroup {
10221 primary_range,
10222 primary_message,
10223 group_id,
10224 blocks,
10225 is_valid: true,
10226 })
10227 });
10228 self.active_diagnostics.is_some()
10229 }
10230
10231 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10232 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10233 self.display_map.update(cx, |display_map, cx| {
10234 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10235 });
10236 cx.notify();
10237 }
10238 }
10239
10240 pub fn set_selections_from_remote(
10241 &mut self,
10242 selections: Vec<Selection<Anchor>>,
10243 pending_selection: Option<Selection<Anchor>>,
10244 cx: &mut ViewContext<Self>,
10245 ) {
10246 let old_cursor_position = self.selections.newest_anchor().head();
10247 self.selections.change_with(cx, |s| {
10248 s.select_anchors(selections);
10249 if let Some(pending_selection) = pending_selection {
10250 s.set_pending(pending_selection, SelectMode::Character);
10251 } else {
10252 s.clear_pending();
10253 }
10254 });
10255 self.selections_did_change(false, &old_cursor_position, true, cx);
10256 }
10257
10258 fn push_to_selection_history(&mut self) {
10259 self.selection_history.push(SelectionHistoryEntry {
10260 selections: self.selections.disjoint_anchors(),
10261 select_next_state: self.select_next_state.clone(),
10262 select_prev_state: self.select_prev_state.clone(),
10263 add_selections_state: self.add_selections_state.clone(),
10264 });
10265 }
10266
10267 pub fn transact(
10268 &mut self,
10269 cx: &mut ViewContext<Self>,
10270 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10271 ) -> Option<TransactionId> {
10272 self.start_transaction_at(Instant::now(), cx);
10273 update(self, cx);
10274 self.end_transaction_at(Instant::now(), cx)
10275 }
10276
10277 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10278 self.end_selection(cx);
10279 if let Some(tx_id) = self
10280 .buffer
10281 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10282 {
10283 self.selection_history
10284 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10285 cx.emit(EditorEvent::TransactionBegun {
10286 transaction_id: tx_id,
10287 })
10288 }
10289 }
10290
10291 fn end_transaction_at(
10292 &mut self,
10293 now: Instant,
10294 cx: &mut ViewContext<Self>,
10295 ) -> Option<TransactionId> {
10296 if let Some(transaction_id) = self
10297 .buffer
10298 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10299 {
10300 if let Some((_, end_selections)) =
10301 self.selection_history.transaction_mut(transaction_id)
10302 {
10303 *end_selections = Some(self.selections.disjoint_anchors());
10304 } else {
10305 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10306 }
10307
10308 cx.emit(EditorEvent::Edited { transaction_id });
10309 Some(transaction_id)
10310 } else {
10311 None
10312 }
10313 }
10314
10315 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10316 if self.is_singleton(cx) {
10317 let selection = self.selections.newest::<Point>(cx);
10318
10319 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10320 let range = if selection.is_empty() {
10321 let point = selection.head().to_display_point(&display_map);
10322 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10323 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10324 .to_point(&display_map);
10325 start..end
10326 } else {
10327 selection.range()
10328 };
10329 if display_map.folds_in_range(range).next().is_some() {
10330 self.unfold_lines(&Default::default(), cx)
10331 } else {
10332 self.fold(&Default::default(), cx)
10333 }
10334 } else {
10335 let (display_snapshot, selections) = self.selections.all_adjusted_display(cx);
10336 let mut toggled_buffers = HashSet::default();
10337 for selection in selections {
10338 if let Some(buffer_id) = display_snapshot
10339 .display_point_to_anchor(selection.head(), Bias::Right)
10340 .buffer_id
10341 {
10342 if toggled_buffers.insert(buffer_id) {
10343 if self.buffer_folded(buffer_id, cx) {
10344 self.unfold_buffer(buffer_id, cx);
10345 } else {
10346 self.fold_buffer(buffer_id, cx);
10347 }
10348 }
10349 }
10350 if let Some(buffer_id) = display_snapshot
10351 .display_point_to_anchor(selection.tail(), Bias::Left)
10352 .buffer_id
10353 {
10354 if toggled_buffers.insert(buffer_id) {
10355 if self.buffer_folded(buffer_id, cx) {
10356 self.unfold_buffer(buffer_id, cx);
10357 } else {
10358 self.fold_buffer(buffer_id, cx);
10359 }
10360 }
10361 }
10362 }
10363 }
10364 }
10365
10366 pub fn toggle_fold_recursive(
10367 &mut self,
10368 _: &actions::ToggleFoldRecursive,
10369 cx: &mut ViewContext<Self>,
10370 ) {
10371 let selection = self.selections.newest::<Point>(cx);
10372
10373 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10374 let range = if selection.is_empty() {
10375 let point = selection.head().to_display_point(&display_map);
10376 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10377 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10378 .to_point(&display_map);
10379 start..end
10380 } else {
10381 selection.range()
10382 };
10383 if display_map.folds_in_range(range).next().is_some() {
10384 self.unfold_recursive(&Default::default(), cx)
10385 } else {
10386 self.fold_recursive(&Default::default(), cx)
10387 }
10388 }
10389
10390 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10391 if self.is_singleton(cx) {
10392 let mut to_fold = Vec::new();
10393 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10394 let selections = self.selections.all_adjusted(cx);
10395
10396 for selection in selections {
10397 let range = selection.range().sorted();
10398 let buffer_start_row = range.start.row;
10399
10400 if range.start.row != range.end.row {
10401 let mut found = false;
10402 let mut row = range.start.row;
10403 while row <= range.end.row {
10404 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10405 {
10406 found = true;
10407 row = crease.range().end.row + 1;
10408 to_fold.push(crease);
10409 } else {
10410 row += 1
10411 }
10412 }
10413 if found {
10414 continue;
10415 }
10416 }
10417
10418 for row in (0..=range.start.row).rev() {
10419 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10420 if crease.range().end.row >= buffer_start_row {
10421 to_fold.push(crease);
10422 if row <= range.start.row {
10423 break;
10424 }
10425 }
10426 }
10427 }
10428 }
10429
10430 self.fold_creases(to_fold, true, cx);
10431 } else {
10432 let (display_snapshot, selections) = self.selections.all_adjusted_display(cx);
10433 let mut folded_buffers = HashSet::default();
10434 for selection in selections {
10435 if let Some(buffer_id) = display_snapshot
10436 .display_point_to_anchor(selection.head(), Bias::Right)
10437 .buffer_id
10438 {
10439 if folded_buffers.insert(buffer_id) {
10440 self.fold_buffer(buffer_id, cx);
10441 }
10442 }
10443 if let Some(buffer_id) = display_snapshot
10444 .display_point_to_anchor(selection.tail(), Bias::Left)
10445 .buffer_id
10446 {
10447 if folded_buffers.insert(buffer_id) {
10448 self.fold_buffer(buffer_id, cx);
10449 }
10450 }
10451 }
10452 }
10453 }
10454
10455 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10456 if !self.buffer.read(cx).is_singleton() {
10457 return;
10458 }
10459
10460 let fold_at_level = fold_at.level;
10461 let snapshot = self.buffer.read(cx).snapshot(cx);
10462 let mut to_fold = Vec::new();
10463 let mut stack = vec![(0, snapshot.max_row().0, 1)];
10464
10465 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10466 while start_row < end_row {
10467 match self
10468 .snapshot(cx)
10469 .crease_for_buffer_row(MultiBufferRow(start_row))
10470 {
10471 Some(crease) => {
10472 let nested_start_row = crease.range().start.row + 1;
10473 let nested_end_row = crease.range().end.row;
10474
10475 if current_level < fold_at_level {
10476 stack.push((nested_start_row, nested_end_row, current_level + 1));
10477 } else if current_level == fold_at_level {
10478 to_fold.push(crease);
10479 }
10480
10481 start_row = nested_end_row + 1;
10482 }
10483 None => start_row += 1,
10484 }
10485 }
10486 }
10487
10488 self.fold_creases(to_fold, true, cx);
10489 }
10490
10491 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10492 if self.buffer.read(cx).is_singleton() {
10493 let mut fold_ranges = Vec::new();
10494 let snapshot = self.buffer.read(cx).snapshot(cx);
10495
10496 for row in 0..snapshot.max_row().0 {
10497 if let Some(foldable_range) =
10498 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10499 {
10500 fold_ranges.push(foldable_range);
10501 }
10502 }
10503
10504 self.fold_creases(fold_ranges, true, cx);
10505 } else {
10506 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10507 editor
10508 .update(&mut cx, |editor, cx| {
10509 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10510 editor.fold_buffer(buffer_id, cx);
10511 }
10512 })
10513 .ok();
10514 });
10515 }
10516 }
10517
10518 pub fn fold_function_bodies(
10519 &mut self,
10520 _: &actions::FoldFunctionBodies,
10521 cx: &mut ViewContext<Self>,
10522 ) {
10523 let snapshot = self.buffer.read(cx).snapshot(cx);
10524 let Some((_, _, buffer)) = snapshot.as_singleton() else {
10525 return;
10526 };
10527 let creases = buffer
10528 .function_body_fold_ranges(0..buffer.len())
10529 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10530 .collect();
10531
10532 self.fold_creases(creases, true, cx);
10533 }
10534
10535 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10536 let mut to_fold = Vec::new();
10537 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10538 let selections = self.selections.all_adjusted(cx);
10539
10540 for selection in selections {
10541 let range = selection.range().sorted();
10542 let buffer_start_row = range.start.row;
10543
10544 if range.start.row != range.end.row {
10545 let mut found = false;
10546 for row in range.start.row..=range.end.row {
10547 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10548 found = true;
10549 to_fold.push(crease);
10550 }
10551 }
10552 if found {
10553 continue;
10554 }
10555 }
10556
10557 for row in (0..=range.start.row).rev() {
10558 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10559 if crease.range().end.row >= buffer_start_row {
10560 to_fold.push(crease);
10561 } else {
10562 break;
10563 }
10564 }
10565 }
10566 }
10567
10568 self.fold_creases(to_fold, true, cx);
10569 }
10570
10571 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10572 let buffer_row = fold_at.buffer_row;
10573 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10574
10575 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10576 let autoscroll = self
10577 .selections
10578 .all::<Point>(cx)
10579 .iter()
10580 .any(|selection| crease.range().overlaps(&selection.range()));
10581
10582 self.fold_creases(vec![crease], autoscroll, cx);
10583 }
10584 }
10585
10586 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10587 if self.is_singleton(cx) {
10588 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10589 let buffer = &display_map.buffer_snapshot;
10590 let selections = self.selections.all::<Point>(cx);
10591 let ranges = selections
10592 .iter()
10593 .map(|s| {
10594 let range = s.display_range(&display_map).sorted();
10595 let mut start = range.start.to_point(&display_map);
10596 let mut end = range.end.to_point(&display_map);
10597 start.column = 0;
10598 end.column = buffer.line_len(MultiBufferRow(end.row));
10599 start..end
10600 })
10601 .collect::<Vec<_>>();
10602
10603 self.unfold_ranges(&ranges, true, true, cx);
10604 } else {
10605 let (display_snapshot, selections) = self.selections.all_adjusted_display(cx);
10606 let mut unfolded_buffers = HashSet::default();
10607 for selection in selections {
10608 if let Some(buffer_id) = display_snapshot
10609 .display_point_to_anchor(selection.head(), Bias::Right)
10610 .buffer_id
10611 {
10612 if unfolded_buffers.insert(buffer_id) {
10613 self.unfold_buffer(buffer_id, cx);
10614 }
10615 }
10616 if let Some(buffer_id) = display_snapshot
10617 .display_point_to_anchor(selection.tail(), Bias::Left)
10618 .buffer_id
10619 {
10620 if unfolded_buffers.insert(buffer_id) {
10621 self.unfold_buffer(buffer_id, cx);
10622 }
10623 }
10624 }
10625 }
10626 }
10627
10628 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10629 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10630 let selections = self.selections.all::<Point>(cx);
10631 let ranges = selections
10632 .iter()
10633 .map(|s| {
10634 let mut range = s.display_range(&display_map).sorted();
10635 *range.start.column_mut() = 0;
10636 *range.end.column_mut() = display_map.line_len(range.end.row());
10637 let start = range.start.to_point(&display_map);
10638 let end = range.end.to_point(&display_map);
10639 start..end
10640 })
10641 .collect::<Vec<_>>();
10642
10643 self.unfold_ranges(&ranges, true, true, cx);
10644 }
10645
10646 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10647 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10648
10649 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10650 ..Point::new(
10651 unfold_at.buffer_row.0,
10652 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10653 );
10654
10655 let autoscroll = self
10656 .selections
10657 .all::<Point>(cx)
10658 .iter()
10659 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10660
10661 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10662 }
10663
10664 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10665 if self.buffer.read(cx).is_singleton() {
10666 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10667 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10668 } else {
10669 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10670 editor
10671 .update(&mut cx, |editor, cx| {
10672 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10673 editor.unfold_buffer(buffer_id, cx);
10674 }
10675 })
10676 .ok();
10677 });
10678 }
10679 }
10680
10681 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10682 let selections = self.selections.all::<Point>(cx);
10683 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10684 let line_mode = self.selections.line_mode;
10685 let ranges = selections
10686 .into_iter()
10687 .map(|s| {
10688 if line_mode {
10689 let start = Point::new(s.start.row, 0);
10690 let end = Point::new(
10691 s.end.row,
10692 display_map
10693 .buffer_snapshot
10694 .line_len(MultiBufferRow(s.end.row)),
10695 );
10696 Crease::simple(start..end, display_map.fold_placeholder.clone())
10697 } else {
10698 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10699 }
10700 })
10701 .collect::<Vec<_>>();
10702 self.fold_creases(ranges, true, cx);
10703 }
10704
10705 pub fn fold_creases<T: ToOffset + Clone>(
10706 &mut self,
10707 creases: Vec<Crease<T>>,
10708 auto_scroll: bool,
10709 cx: &mut ViewContext<Self>,
10710 ) {
10711 if creases.is_empty() {
10712 return;
10713 }
10714
10715 let mut buffers_affected = HashSet::default();
10716 let multi_buffer = self.buffer().read(cx);
10717 for crease in &creases {
10718 if let Some((_, buffer, _)) =
10719 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10720 {
10721 buffers_affected.insert(buffer.read(cx).remote_id());
10722 };
10723 }
10724
10725 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10726
10727 if auto_scroll {
10728 self.request_autoscroll(Autoscroll::fit(), cx);
10729 }
10730
10731 for buffer_id in buffers_affected {
10732 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10733 }
10734
10735 cx.notify();
10736
10737 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10738 // Clear diagnostics block when folding a range that contains it.
10739 let snapshot = self.snapshot(cx);
10740 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10741 drop(snapshot);
10742 self.active_diagnostics = Some(active_diagnostics);
10743 self.dismiss_diagnostics(cx);
10744 } else {
10745 self.active_diagnostics = Some(active_diagnostics);
10746 }
10747 }
10748
10749 self.scrollbar_marker_state.dirty = true;
10750 }
10751
10752 /// Removes any folds whose ranges intersect any of the given ranges.
10753 pub fn unfold_ranges<T: ToOffset + Clone>(
10754 &mut self,
10755 ranges: &[Range<T>],
10756 inclusive: bool,
10757 auto_scroll: bool,
10758 cx: &mut ViewContext<Self>,
10759 ) {
10760 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10761 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10762 });
10763 }
10764
10765 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10766 if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10767 return;
10768 }
10769 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10770 return;
10771 };
10772 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10773 self.display_map
10774 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10775 cx.emit(EditorEvent::BufferFoldToggled {
10776 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
10777 folded: true,
10778 });
10779 cx.notify();
10780 }
10781
10782 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10783 if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
10784 return;
10785 }
10786 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10787 return;
10788 };
10789 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10790 self.display_map.update(cx, |display_map, cx| {
10791 display_map.unfold_buffer(buffer_id, cx);
10792 });
10793 cx.emit(EditorEvent::BufferFoldToggled {
10794 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
10795 folded: false,
10796 });
10797 cx.notify();
10798 }
10799
10800 pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
10801 self.display_map.read(cx).buffer_folded(buffer)
10802 }
10803
10804 /// Removes any folds with the given ranges.
10805 pub fn remove_folds_with_type<T: ToOffset + Clone>(
10806 &mut self,
10807 ranges: &[Range<T>],
10808 type_id: TypeId,
10809 auto_scroll: bool,
10810 cx: &mut ViewContext<Self>,
10811 ) {
10812 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10813 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
10814 });
10815 }
10816
10817 fn remove_folds_with<T: ToOffset + Clone>(
10818 &mut self,
10819 ranges: &[Range<T>],
10820 auto_scroll: bool,
10821 cx: &mut ViewContext<Self>,
10822 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
10823 ) {
10824 if ranges.is_empty() {
10825 return;
10826 }
10827
10828 let mut buffers_affected = HashSet::default();
10829 let multi_buffer = self.buffer().read(cx);
10830 for range in ranges {
10831 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10832 buffers_affected.insert(buffer.read(cx).remote_id());
10833 };
10834 }
10835
10836 self.display_map.update(cx, update);
10837
10838 if auto_scroll {
10839 self.request_autoscroll(Autoscroll::fit(), cx);
10840 }
10841
10842 for buffer_id in buffers_affected {
10843 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10844 }
10845
10846 cx.notify();
10847 self.scrollbar_marker_state.dirty = true;
10848 self.active_indent_guides_state.dirty = true;
10849 }
10850
10851 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10852 self.display_map.read(cx).fold_placeholder.clone()
10853 }
10854
10855 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10856 if hovered != self.gutter_hovered {
10857 self.gutter_hovered = hovered;
10858 cx.notify();
10859 }
10860 }
10861
10862 pub fn insert_blocks(
10863 &mut self,
10864 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10865 autoscroll: Option<Autoscroll>,
10866 cx: &mut ViewContext<Self>,
10867 ) -> Vec<CustomBlockId> {
10868 let blocks = self
10869 .display_map
10870 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10871 if let Some(autoscroll) = autoscroll {
10872 self.request_autoscroll(autoscroll, cx);
10873 }
10874 cx.notify();
10875 blocks
10876 }
10877
10878 pub fn resize_blocks(
10879 &mut self,
10880 heights: HashMap<CustomBlockId, u32>,
10881 autoscroll: Option<Autoscroll>,
10882 cx: &mut ViewContext<Self>,
10883 ) {
10884 self.display_map
10885 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10886 if let Some(autoscroll) = autoscroll {
10887 self.request_autoscroll(autoscroll, cx);
10888 }
10889 cx.notify();
10890 }
10891
10892 pub fn replace_blocks(
10893 &mut self,
10894 renderers: HashMap<CustomBlockId, RenderBlock>,
10895 autoscroll: Option<Autoscroll>,
10896 cx: &mut ViewContext<Self>,
10897 ) {
10898 self.display_map
10899 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10900 if let Some(autoscroll) = autoscroll {
10901 self.request_autoscroll(autoscroll, cx);
10902 }
10903 cx.notify();
10904 }
10905
10906 pub fn remove_blocks(
10907 &mut self,
10908 block_ids: HashSet<CustomBlockId>,
10909 autoscroll: Option<Autoscroll>,
10910 cx: &mut ViewContext<Self>,
10911 ) {
10912 self.display_map.update(cx, |display_map, cx| {
10913 display_map.remove_blocks(block_ids, cx)
10914 });
10915 if let Some(autoscroll) = autoscroll {
10916 self.request_autoscroll(autoscroll, cx);
10917 }
10918 cx.notify();
10919 }
10920
10921 pub fn row_for_block(
10922 &self,
10923 block_id: CustomBlockId,
10924 cx: &mut ViewContext<Self>,
10925 ) -> Option<DisplayRow> {
10926 self.display_map
10927 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10928 }
10929
10930 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10931 self.focused_block = Some(focused_block);
10932 }
10933
10934 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10935 self.focused_block.take()
10936 }
10937
10938 pub fn insert_creases(
10939 &mut self,
10940 creases: impl IntoIterator<Item = Crease<Anchor>>,
10941 cx: &mut ViewContext<Self>,
10942 ) -> Vec<CreaseId> {
10943 self.display_map
10944 .update(cx, |map, cx| map.insert_creases(creases, cx))
10945 }
10946
10947 pub fn remove_creases(
10948 &mut self,
10949 ids: impl IntoIterator<Item = CreaseId>,
10950 cx: &mut ViewContext<Self>,
10951 ) {
10952 self.display_map
10953 .update(cx, |map, cx| map.remove_creases(ids, cx));
10954 }
10955
10956 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10957 self.display_map
10958 .update(cx, |map, cx| map.snapshot(cx))
10959 .longest_row()
10960 }
10961
10962 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10963 self.display_map
10964 .update(cx, |map, cx| map.snapshot(cx))
10965 .max_point()
10966 }
10967
10968 pub fn text(&self, cx: &AppContext) -> String {
10969 self.buffer.read(cx).read(cx).text()
10970 }
10971
10972 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10973 let text = self.text(cx);
10974 let text = text.trim();
10975
10976 if text.is_empty() {
10977 return None;
10978 }
10979
10980 Some(text.to_string())
10981 }
10982
10983 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10984 self.transact(cx, |this, cx| {
10985 this.buffer
10986 .read(cx)
10987 .as_singleton()
10988 .expect("you can only call set_text on editors for singleton buffers")
10989 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10990 });
10991 }
10992
10993 pub fn display_text(&self, cx: &mut AppContext) -> String {
10994 self.display_map
10995 .update(cx, |map, cx| map.snapshot(cx))
10996 .text()
10997 }
10998
10999 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11000 let mut wrap_guides = smallvec::smallvec![];
11001
11002 if self.show_wrap_guides == Some(false) {
11003 return wrap_guides;
11004 }
11005
11006 let settings = self.buffer.read(cx).settings_at(0, cx);
11007 if settings.show_wrap_guides {
11008 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11009 wrap_guides.push((soft_wrap as usize, true));
11010 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11011 wrap_guides.push((soft_wrap as usize, true));
11012 }
11013 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11014 }
11015
11016 wrap_guides
11017 }
11018
11019 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11020 let settings = self.buffer.read(cx).settings_at(0, cx);
11021 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11022 match mode {
11023 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11024 SoftWrap::None
11025 }
11026 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11027 language_settings::SoftWrap::PreferredLineLength => {
11028 SoftWrap::Column(settings.preferred_line_length)
11029 }
11030 language_settings::SoftWrap::Bounded => {
11031 SoftWrap::Bounded(settings.preferred_line_length)
11032 }
11033 }
11034 }
11035
11036 pub fn set_soft_wrap_mode(
11037 &mut self,
11038 mode: language_settings::SoftWrap,
11039 cx: &mut ViewContext<Self>,
11040 ) {
11041 self.soft_wrap_mode_override = Some(mode);
11042 cx.notify();
11043 }
11044
11045 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11046 self.text_style_refinement = Some(style);
11047 }
11048
11049 /// called by the Element so we know what style we were most recently rendered with.
11050 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11051 let rem_size = cx.rem_size();
11052 self.display_map.update(cx, |map, cx| {
11053 map.set_font(
11054 style.text.font(),
11055 style.text.font_size.to_pixels(rem_size),
11056 cx,
11057 )
11058 });
11059 self.style = Some(style);
11060 }
11061
11062 pub fn style(&self) -> Option<&EditorStyle> {
11063 self.style.as_ref()
11064 }
11065
11066 // Called by the element. This method is not designed to be called outside of the editor
11067 // element's layout code because it does not notify when rewrapping is computed synchronously.
11068 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11069 self.display_map
11070 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11071 }
11072
11073 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11074 if self.soft_wrap_mode_override.is_some() {
11075 self.soft_wrap_mode_override.take();
11076 } else {
11077 let soft_wrap = match self.soft_wrap_mode(cx) {
11078 SoftWrap::GitDiff => return,
11079 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11080 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11081 language_settings::SoftWrap::None
11082 }
11083 };
11084 self.soft_wrap_mode_override = Some(soft_wrap);
11085 }
11086 cx.notify();
11087 }
11088
11089 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11090 let Some(workspace) = self.workspace() else {
11091 return;
11092 };
11093 let fs = workspace.read(cx).app_state().fs.clone();
11094 let current_show = TabBarSettings::get_global(cx).show;
11095 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11096 setting.show = Some(!current_show);
11097 });
11098 }
11099
11100 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11101 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11102 self.buffer
11103 .read(cx)
11104 .settings_at(0, cx)
11105 .indent_guides
11106 .enabled
11107 });
11108 self.show_indent_guides = Some(!currently_enabled);
11109 cx.notify();
11110 }
11111
11112 fn should_show_indent_guides(&self) -> Option<bool> {
11113 self.show_indent_guides
11114 }
11115
11116 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11117 let mut editor_settings = EditorSettings::get_global(cx).clone();
11118 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11119 EditorSettings::override_global(editor_settings, cx);
11120 }
11121
11122 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11123 self.use_relative_line_numbers
11124 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11125 }
11126
11127 pub fn toggle_relative_line_numbers(
11128 &mut self,
11129 _: &ToggleRelativeLineNumbers,
11130 cx: &mut ViewContext<Self>,
11131 ) {
11132 let is_relative = self.should_use_relative_line_numbers(cx);
11133 self.set_relative_line_number(Some(!is_relative), cx)
11134 }
11135
11136 pub fn set_relative_line_number(
11137 &mut self,
11138 is_relative: Option<bool>,
11139 cx: &mut ViewContext<Self>,
11140 ) {
11141 self.use_relative_line_numbers = is_relative;
11142 cx.notify();
11143 }
11144
11145 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11146 self.show_gutter = show_gutter;
11147 cx.notify();
11148 }
11149
11150 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11151 self.show_line_numbers = Some(show_line_numbers);
11152 cx.notify();
11153 }
11154
11155 pub fn set_show_git_diff_gutter(
11156 &mut self,
11157 show_git_diff_gutter: bool,
11158 cx: &mut ViewContext<Self>,
11159 ) {
11160 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11161 cx.notify();
11162 }
11163
11164 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11165 self.show_code_actions = Some(show_code_actions);
11166 cx.notify();
11167 }
11168
11169 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11170 self.show_runnables = Some(show_runnables);
11171 cx.notify();
11172 }
11173
11174 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11175 if self.display_map.read(cx).masked != masked {
11176 self.display_map.update(cx, |map, _| map.masked = masked);
11177 }
11178 cx.notify()
11179 }
11180
11181 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11182 self.show_wrap_guides = Some(show_wrap_guides);
11183 cx.notify();
11184 }
11185
11186 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11187 self.show_indent_guides = Some(show_indent_guides);
11188 cx.notify();
11189 }
11190
11191 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11192 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11193 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11194 if let Some(dir) = file.abs_path(cx).parent() {
11195 return Some(dir.to_owned());
11196 }
11197 }
11198
11199 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11200 return Some(project_path.path.to_path_buf());
11201 }
11202 }
11203
11204 None
11205 }
11206
11207 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11208 self.active_excerpt(cx)?
11209 .1
11210 .read(cx)
11211 .file()
11212 .and_then(|f| f.as_local())
11213 }
11214
11215 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11216 if let Some(target) = self.target_file(cx) {
11217 cx.reveal_path(&target.abs_path(cx));
11218 }
11219 }
11220
11221 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11222 if let Some(file) = self.target_file(cx) {
11223 if let Some(path) = file.abs_path(cx).to_str() {
11224 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11225 }
11226 }
11227 }
11228
11229 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11230 if let Some(file) = self.target_file(cx) {
11231 if let Some(path) = file.path().to_str() {
11232 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11233 }
11234 }
11235 }
11236
11237 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11238 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11239
11240 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11241 self.start_git_blame(true, cx);
11242 }
11243
11244 cx.notify();
11245 }
11246
11247 pub fn toggle_git_blame_inline(
11248 &mut self,
11249 _: &ToggleGitBlameInline,
11250 cx: &mut ViewContext<Self>,
11251 ) {
11252 self.toggle_git_blame_inline_internal(true, cx);
11253 cx.notify();
11254 }
11255
11256 pub fn git_blame_inline_enabled(&self) -> bool {
11257 self.git_blame_inline_enabled
11258 }
11259
11260 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11261 self.show_selection_menu = self
11262 .show_selection_menu
11263 .map(|show_selections_menu| !show_selections_menu)
11264 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11265
11266 cx.notify();
11267 }
11268
11269 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11270 self.show_selection_menu
11271 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11272 }
11273
11274 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11275 if let Some(project) = self.project.as_ref() {
11276 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11277 return;
11278 };
11279
11280 if buffer.read(cx).file().is_none() {
11281 return;
11282 }
11283
11284 let focused = self.focus_handle(cx).contains_focused(cx);
11285
11286 let project = project.clone();
11287 let blame =
11288 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11289 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11290 self.blame = Some(blame);
11291 }
11292 }
11293
11294 fn toggle_git_blame_inline_internal(
11295 &mut self,
11296 user_triggered: bool,
11297 cx: &mut ViewContext<Self>,
11298 ) {
11299 if self.git_blame_inline_enabled {
11300 self.git_blame_inline_enabled = false;
11301 self.show_git_blame_inline = false;
11302 self.show_git_blame_inline_delay_task.take();
11303 } else {
11304 self.git_blame_inline_enabled = true;
11305 self.start_git_blame_inline(user_triggered, cx);
11306 }
11307
11308 cx.notify();
11309 }
11310
11311 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11312 self.start_git_blame(user_triggered, cx);
11313
11314 if ProjectSettings::get_global(cx)
11315 .git
11316 .inline_blame_delay()
11317 .is_some()
11318 {
11319 self.start_inline_blame_timer(cx);
11320 } else {
11321 self.show_git_blame_inline = true
11322 }
11323 }
11324
11325 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11326 self.blame.as_ref()
11327 }
11328
11329 pub fn show_git_blame_gutter(&self) -> bool {
11330 self.show_git_blame_gutter
11331 }
11332
11333 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11334 self.show_git_blame_gutter && self.has_blame_entries(cx)
11335 }
11336
11337 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11338 self.show_git_blame_inline
11339 && self.focus_handle.is_focused(cx)
11340 && !self.newest_selection_head_on_empty_line(cx)
11341 && self.has_blame_entries(cx)
11342 }
11343
11344 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11345 self.blame()
11346 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11347 }
11348
11349 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11350 let cursor_anchor = self.selections.newest_anchor().head();
11351
11352 let snapshot = self.buffer.read(cx).snapshot(cx);
11353 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11354
11355 snapshot.line_len(buffer_row) == 0
11356 }
11357
11358 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11359 let buffer_and_selection = maybe!({
11360 let selection = self.selections.newest::<Point>(cx);
11361 let selection_range = selection.range();
11362
11363 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11364 (buffer, selection_range.start.row..selection_range.end.row)
11365 } else {
11366 let buffer_ranges = self
11367 .buffer()
11368 .read(cx)
11369 .range_to_buffer_ranges(selection_range, cx);
11370
11371 let (buffer, range, _) = if selection.reversed {
11372 buffer_ranges.first()
11373 } else {
11374 buffer_ranges.last()
11375 }?;
11376
11377 let snapshot = buffer.read(cx).snapshot();
11378 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11379 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11380 (buffer.clone(), selection)
11381 };
11382
11383 Some((buffer, selection))
11384 });
11385
11386 let Some((buffer, selection)) = buffer_and_selection else {
11387 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11388 };
11389
11390 let Some(project) = self.project.as_ref() else {
11391 return Task::ready(Err(anyhow!("editor does not have project")));
11392 };
11393
11394 project.update(cx, |project, cx| {
11395 project.get_permalink_to_line(&buffer, selection, cx)
11396 })
11397 }
11398
11399 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11400 let permalink_task = self.get_permalink_to_line(cx);
11401 let workspace = self.workspace();
11402
11403 cx.spawn(|_, mut cx| async move {
11404 match permalink_task.await {
11405 Ok(permalink) => {
11406 cx.update(|cx| {
11407 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11408 })
11409 .ok();
11410 }
11411 Err(err) => {
11412 let message = format!("Failed to copy permalink: {err}");
11413
11414 Err::<(), anyhow::Error>(err).log_err();
11415
11416 if let Some(workspace) = workspace {
11417 workspace
11418 .update(&mut cx, |workspace, cx| {
11419 struct CopyPermalinkToLine;
11420
11421 workspace.show_toast(
11422 Toast::new(
11423 NotificationId::unique::<CopyPermalinkToLine>(),
11424 message,
11425 ),
11426 cx,
11427 )
11428 })
11429 .ok();
11430 }
11431 }
11432 }
11433 })
11434 .detach();
11435 }
11436
11437 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11438 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11439 if let Some(file) = self.target_file(cx) {
11440 if let Some(path) = file.path().to_str() {
11441 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11442 }
11443 }
11444 }
11445
11446 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11447 let permalink_task = self.get_permalink_to_line(cx);
11448 let workspace = self.workspace();
11449
11450 cx.spawn(|_, mut cx| async move {
11451 match permalink_task.await {
11452 Ok(permalink) => {
11453 cx.update(|cx| {
11454 cx.open_url(permalink.as_ref());
11455 })
11456 .ok();
11457 }
11458 Err(err) => {
11459 let message = format!("Failed to open permalink: {err}");
11460
11461 Err::<(), anyhow::Error>(err).log_err();
11462
11463 if let Some(workspace) = workspace {
11464 workspace
11465 .update(&mut cx, |workspace, cx| {
11466 struct OpenPermalinkToLine;
11467
11468 workspace.show_toast(
11469 Toast::new(
11470 NotificationId::unique::<OpenPermalinkToLine>(),
11471 message,
11472 ),
11473 cx,
11474 )
11475 })
11476 .ok();
11477 }
11478 }
11479 }
11480 })
11481 .detach();
11482 }
11483
11484 pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11485 self.insert_uuid(UuidVersion::V4, cx);
11486 }
11487
11488 pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11489 self.insert_uuid(UuidVersion::V7, cx);
11490 }
11491
11492 fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11493 self.transact(cx, |this, cx| {
11494 let edits = this
11495 .selections
11496 .all::<Point>(cx)
11497 .into_iter()
11498 .map(|selection| {
11499 let uuid = match version {
11500 UuidVersion::V4 => uuid::Uuid::new_v4(),
11501 UuidVersion::V7 => uuid::Uuid::now_v7(),
11502 };
11503
11504 (selection.range(), uuid.to_string())
11505 });
11506 this.edit(edits, cx);
11507 this.refresh_inline_completion(true, false, cx);
11508 });
11509 }
11510
11511 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11512 /// last highlight added will be used.
11513 ///
11514 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11515 pub fn highlight_rows<T: 'static>(
11516 &mut self,
11517 range: Range<Anchor>,
11518 color: Hsla,
11519 should_autoscroll: bool,
11520 cx: &mut ViewContext<Self>,
11521 ) {
11522 let snapshot = self.buffer().read(cx).snapshot(cx);
11523 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11524 let ix = row_highlights.binary_search_by(|highlight| {
11525 Ordering::Equal
11526 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11527 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11528 });
11529
11530 if let Err(mut ix) = ix {
11531 let index = post_inc(&mut self.highlight_order);
11532
11533 // If this range intersects with the preceding highlight, then merge it with
11534 // the preceding highlight. Otherwise insert a new highlight.
11535 let mut merged = false;
11536 if ix > 0 {
11537 let prev_highlight = &mut row_highlights[ix - 1];
11538 if prev_highlight
11539 .range
11540 .end
11541 .cmp(&range.start, &snapshot)
11542 .is_ge()
11543 {
11544 ix -= 1;
11545 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11546 prev_highlight.range.end = range.end;
11547 }
11548 merged = true;
11549 prev_highlight.index = index;
11550 prev_highlight.color = color;
11551 prev_highlight.should_autoscroll = should_autoscroll;
11552 }
11553 }
11554
11555 if !merged {
11556 row_highlights.insert(
11557 ix,
11558 RowHighlight {
11559 range: range.clone(),
11560 index,
11561 color,
11562 should_autoscroll,
11563 },
11564 );
11565 }
11566
11567 // If any of the following highlights intersect with this one, merge them.
11568 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11569 let highlight = &row_highlights[ix];
11570 if next_highlight
11571 .range
11572 .start
11573 .cmp(&highlight.range.end, &snapshot)
11574 .is_le()
11575 {
11576 if next_highlight
11577 .range
11578 .end
11579 .cmp(&highlight.range.end, &snapshot)
11580 .is_gt()
11581 {
11582 row_highlights[ix].range.end = next_highlight.range.end;
11583 }
11584 row_highlights.remove(ix + 1);
11585 } else {
11586 break;
11587 }
11588 }
11589 }
11590 }
11591
11592 /// Remove any highlighted row ranges of the given type that intersect the
11593 /// given ranges.
11594 pub fn remove_highlighted_rows<T: 'static>(
11595 &mut self,
11596 ranges_to_remove: Vec<Range<Anchor>>,
11597 cx: &mut ViewContext<Self>,
11598 ) {
11599 let snapshot = self.buffer().read(cx).snapshot(cx);
11600 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11601 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11602 row_highlights.retain(|highlight| {
11603 while let Some(range_to_remove) = ranges_to_remove.peek() {
11604 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11605 Ordering::Less | Ordering::Equal => {
11606 ranges_to_remove.next();
11607 }
11608 Ordering::Greater => {
11609 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11610 Ordering::Less | Ordering::Equal => {
11611 return false;
11612 }
11613 Ordering::Greater => break,
11614 }
11615 }
11616 }
11617 }
11618
11619 true
11620 })
11621 }
11622
11623 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11624 pub fn clear_row_highlights<T: 'static>(&mut self) {
11625 self.highlighted_rows.remove(&TypeId::of::<T>());
11626 }
11627
11628 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11629 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11630 self.highlighted_rows
11631 .get(&TypeId::of::<T>())
11632 .map_or(&[] as &[_], |vec| vec.as_slice())
11633 .iter()
11634 .map(|highlight| (highlight.range.clone(), highlight.color))
11635 }
11636
11637 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11638 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11639 /// Allows to ignore certain kinds of highlights.
11640 pub fn highlighted_display_rows(
11641 &mut self,
11642 cx: &mut WindowContext,
11643 ) -> BTreeMap<DisplayRow, Hsla> {
11644 let snapshot = self.snapshot(cx);
11645 let mut used_highlight_orders = HashMap::default();
11646 self.highlighted_rows
11647 .iter()
11648 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11649 .fold(
11650 BTreeMap::<DisplayRow, Hsla>::new(),
11651 |mut unique_rows, highlight| {
11652 let start = highlight.range.start.to_display_point(&snapshot);
11653 let end = highlight.range.end.to_display_point(&snapshot);
11654 let start_row = start.row().0;
11655 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11656 && end.column() == 0
11657 {
11658 end.row().0.saturating_sub(1)
11659 } else {
11660 end.row().0
11661 };
11662 for row in start_row..=end_row {
11663 let used_index =
11664 used_highlight_orders.entry(row).or_insert(highlight.index);
11665 if highlight.index >= *used_index {
11666 *used_index = highlight.index;
11667 unique_rows.insert(DisplayRow(row), highlight.color);
11668 }
11669 }
11670 unique_rows
11671 },
11672 )
11673 }
11674
11675 pub fn highlighted_display_row_for_autoscroll(
11676 &self,
11677 snapshot: &DisplaySnapshot,
11678 ) -> Option<DisplayRow> {
11679 self.highlighted_rows
11680 .values()
11681 .flat_map(|highlighted_rows| highlighted_rows.iter())
11682 .filter_map(|highlight| {
11683 if highlight.should_autoscroll {
11684 Some(highlight.range.start.to_display_point(snapshot).row())
11685 } else {
11686 None
11687 }
11688 })
11689 .min()
11690 }
11691
11692 pub fn set_search_within_ranges(
11693 &mut self,
11694 ranges: &[Range<Anchor>],
11695 cx: &mut ViewContext<Self>,
11696 ) {
11697 self.highlight_background::<SearchWithinRange>(
11698 ranges,
11699 |colors| colors.editor_document_highlight_read_background,
11700 cx,
11701 )
11702 }
11703
11704 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11705 self.breadcrumb_header = Some(new_header);
11706 }
11707
11708 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11709 self.clear_background_highlights::<SearchWithinRange>(cx);
11710 }
11711
11712 pub fn highlight_background<T: 'static>(
11713 &mut self,
11714 ranges: &[Range<Anchor>],
11715 color_fetcher: fn(&ThemeColors) -> Hsla,
11716 cx: &mut ViewContext<Self>,
11717 ) {
11718 self.background_highlights
11719 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11720 self.scrollbar_marker_state.dirty = true;
11721 cx.notify();
11722 }
11723
11724 pub fn clear_background_highlights<T: 'static>(
11725 &mut self,
11726 cx: &mut ViewContext<Self>,
11727 ) -> Option<BackgroundHighlight> {
11728 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11729 if !text_highlights.1.is_empty() {
11730 self.scrollbar_marker_state.dirty = true;
11731 cx.notify();
11732 }
11733 Some(text_highlights)
11734 }
11735
11736 pub fn highlight_gutter<T: 'static>(
11737 &mut self,
11738 ranges: &[Range<Anchor>],
11739 color_fetcher: fn(&AppContext) -> Hsla,
11740 cx: &mut ViewContext<Self>,
11741 ) {
11742 self.gutter_highlights
11743 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11744 cx.notify();
11745 }
11746
11747 pub fn clear_gutter_highlights<T: 'static>(
11748 &mut self,
11749 cx: &mut ViewContext<Self>,
11750 ) -> Option<GutterHighlight> {
11751 cx.notify();
11752 self.gutter_highlights.remove(&TypeId::of::<T>())
11753 }
11754
11755 #[cfg(feature = "test-support")]
11756 pub fn all_text_background_highlights(
11757 &mut self,
11758 cx: &mut ViewContext<Self>,
11759 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11760 let snapshot = self.snapshot(cx);
11761 let buffer = &snapshot.buffer_snapshot;
11762 let start = buffer.anchor_before(0);
11763 let end = buffer.anchor_after(buffer.len());
11764 let theme = cx.theme().colors();
11765 self.background_highlights_in_range(start..end, &snapshot, theme)
11766 }
11767
11768 #[cfg(feature = "test-support")]
11769 pub fn search_background_highlights(
11770 &mut self,
11771 cx: &mut ViewContext<Self>,
11772 ) -> Vec<Range<Point>> {
11773 let snapshot = self.buffer().read(cx).snapshot(cx);
11774
11775 let highlights = self
11776 .background_highlights
11777 .get(&TypeId::of::<items::BufferSearchHighlights>());
11778
11779 if let Some((_color, ranges)) = highlights {
11780 ranges
11781 .iter()
11782 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11783 .collect_vec()
11784 } else {
11785 vec![]
11786 }
11787 }
11788
11789 fn document_highlights_for_position<'a>(
11790 &'a self,
11791 position: Anchor,
11792 buffer: &'a MultiBufferSnapshot,
11793 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11794 let read_highlights = self
11795 .background_highlights
11796 .get(&TypeId::of::<DocumentHighlightRead>())
11797 .map(|h| &h.1);
11798 let write_highlights = self
11799 .background_highlights
11800 .get(&TypeId::of::<DocumentHighlightWrite>())
11801 .map(|h| &h.1);
11802 let left_position = position.bias_left(buffer);
11803 let right_position = position.bias_right(buffer);
11804 read_highlights
11805 .into_iter()
11806 .chain(write_highlights)
11807 .flat_map(move |ranges| {
11808 let start_ix = match ranges.binary_search_by(|probe| {
11809 let cmp = probe.end.cmp(&left_position, buffer);
11810 if cmp.is_ge() {
11811 Ordering::Greater
11812 } else {
11813 Ordering::Less
11814 }
11815 }) {
11816 Ok(i) | Err(i) => i,
11817 };
11818
11819 ranges[start_ix..]
11820 .iter()
11821 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11822 })
11823 }
11824
11825 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11826 self.background_highlights
11827 .get(&TypeId::of::<T>())
11828 .map_or(false, |(_, highlights)| !highlights.is_empty())
11829 }
11830
11831 pub fn background_highlights_in_range(
11832 &self,
11833 search_range: Range<Anchor>,
11834 display_snapshot: &DisplaySnapshot,
11835 theme: &ThemeColors,
11836 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11837 let mut results = Vec::new();
11838 for (color_fetcher, ranges) in self.background_highlights.values() {
11839 let color = color_fetcher(theme);
11840 let start_ix = match ranges.binary_search_by(|probe| {
11841 let cmp = probe
11842 .end
11843 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11844 if cmp.is_gt() {
11845 Ordering::Greater
11846 } else {
11847 Ordering::Less
11848 }
11849 }) {
11850 Ok(i) | Err(i) => i,
11851 };
11852 for range in &ranges[start_ix..] {
11853 if range
11854 .start
11855 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11856 .is_ge()
11857 {
11858 break;
11859 }
11860
11861 let start = range.start.to_display_point(display_snapshot);
11862 let end = range.end.to_display_point(display_snapshot);
11863 results.push((start..end, color))
11864 }
11865 }
11866 results
11867 }
11868
11869 pub fn background_highlight_row_ranges<T: 'static>(
11870 &self,
11871 search_range: Range<Anchor>,
11872 display_snapshot: &DisplaySnapshot,
11873 count: usize,
11874 ) -> Vec<RangeInclusive<DisplayPoint>> {
11875 let mut results = Vec::new();
11876 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11877 return vec![];
11878 };
11879
11880 let start_ix = match ranges.binary_search_by(|probe| {
11881 let cmp = probe
11882 .end
11883 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11884 if cmp.is_gt() {
11885 Ordering::Greater
11886 } else {
11887 Ordering::Less
11888 }
11889 }) {
11890 Ok(i) | Err(i) => i,
11891 };
11892 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11893 if let (Some(start_display), Some(end_display)) = (start, end) {
11894 results.push(
11895 start_display.to_display_point(display_snapshot)
11896 ..=end_display.to_display_point(display_snapshot),
11897 );
11898 }
11899 };
11900 let mut start_row: Option<Point> = None;
11901 let mut end_row: Option<Point> = None;
11902 if ranges.len() > count {
11903 return Vec::new();
11904 }
11905 for range in &ranges[start_ix..] {
11906 if range
11907 .start
11908 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11909 .is_ge()
11910 {
11911 break;
11912 }
11913 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11914 if let Some(current_row) = &end_row {
11915 if end.row == current_row.row {
11916 continue;
11917 }
11918 }
11919 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11920 if start_row.is_none() {
11921 assert_eq!(end_row, None);
11922 start_row = Some(start);
11923 end_row = Some(end);
11924 continue;
11925 }
11926 if let Some(current_end) = end_row.as_mut() {
11927 if start.row > current_end.row + 1 {
11928 push_region(start_row, end_row);
11929 start_row = Some(start);
11930 end_row = Some(end);
11931 } else {
11932 // Merge two hunks.
11933 *current_end = end;
11934 }
11935 } else {
11936 unreachable!();
11937 }
11938 }
11939 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11940 push_region(start_row, end_row);
11941 results
11942 }
11943
11944 pub fn gutter_highlights_in_range(
11945 &self,
11946 search_range: Range<Anchor>,
11947 display_snapshot: &DisplaySnapshot,
11948 cx: &AppContext,
11949 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11950 let mut results = Vec::new();
11951 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11952 let color = color_fetcher(cx);
11953 let start_ix = match ranges.binary_search_by(|probe| {
11954 let cmp = probe
11955 .end
11956 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11957 if cmp.is_gt() {
11958 Ordering::Greater
11959 } else {
11960 Ordering::Less
11961 }
11962 }) {
11963 Ok(i) | Err(i) => i,
11964 };
11965 for range in &ranges[start_ix..] {
11966 if range
11967 .start
11968 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11969 .is_ge()
11970 {
11971 break;
11972 }
11973
11974 let start = range.start.to_display_point(display_snapshot);
11975 let end = range.end.to_display_point(display_snapshot);
11976 results.push((start..end, color))
11977 }
11978 }
11979 results
11980 }
11981
11982 /// Get the text ranges corresponding to the redaction query
11983 pub fn redacted_ranges(
11984 &self,
11985 search_range: Range<Anchor>,
11986 display_snapshot: &DisplaySnapshot,
11987 cx: &WindowContext,
11988 ) -> Vec<Range<DisplayPoint>> {
11989 display_snapshot
11990 .buffer_snapshot
11991 .redacted_ranges(search_range, |file| {
11992 if let Some(file) = file {
11993 file.is_private()
11994 && EditorSettings::get(
11995 Some(SettingsLocation {
11996 worktree_id: file.worktree_id(cx),
11997 path: file.path().as_ref(),
11998 }),
11999 cx,
12000 )
12001 .redact_private_values
12002 } else {
12003 false
12004 }
12005 })
12006 .map(|range| {
12007 range.start.to_display_point(display_snapshot)
12008 ..range.end.to_display_point(display_snapshot)
12009 })
12010 .collect()
12011 }
12012
12013 pub fn highlight_text<T: 'static>(
12014 &mut self,
12015 ranges: Vec<Range<Anchor>>,
12016 style: HighlightStyle,
12017 cx: &mut ViewContext<Self>,
12018 ) {
12019 self.display_map.update(cx, |map, _| {
12020 map.highlight_text(TypeId::of::<T>(), ranges, style)
12021 });
12022 cx.notify();
12023 }
12024
12025 pub(crate) fn highlight_inlays<T: 'static>(
12026 &mut self,
12027 highlights: Vec<InlayHighlight>,
12028 style: HighlightStyle,
12029 cx: &mut ViewContext<Self>,
12030 ) {
12031 self.display_map.update(cx, |map, _| {
12032 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12033 });
12034 cx.notify();
12035 }
12036
12037 pub fn text_highlights<'a, T: 'static>(
12038 &'a self,
12039 cx: &'a AppContext,
12040 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12041 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12042 }
12043
12044 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12045 let cleared = self
12046 .display_map
12047 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12048 if cleared {
12049 cx.notify();
12050 }
12051 }
12052
12053 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12054 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12055 && self.focus_handle.is_focused(cx)
12056 }
12057
12058 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12059 self.show_cursor_when_unfocused = is_enabled;
12060 cx.notify();
12061 }
12062
12063 pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12064 self.project
12065 .as_ref()
12066 .map(|project| project.read(cx).lsp_store())
12067 }
12068
12069 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12070 cx.notify();
12071 }
12072
12073 fn on_buffer_event(
12074 &mut self,
12075 multibuffer: Model<MultiBuffer>,
12076 event: &multi_buffer::Event,
12077 cx: &mut ViewContext<Self>,
12078 ) {
12079 match event {
12080 multi_buffer::Event::Edited {
12081 singleton_buffer_edited,
12082 edited_buffer: buffer_edited,
12083 } => {
12084 self.scrollbar_marker_state.dirty = true;
12085 self.active_indent_guides_state.dirty = true;
12086 self.refresh_active_diagnostics(cx);
12087 self.refresh_code_actions(cx);
12088 if self.has_active_inline_completion() {
12089 self.update_visible_inline_completion(cx);
12090 }
12091 if let Some(buffer) = buffer_edited {
12092 let buffer_id = buffer.read(cx).remote_id();
12093 if !self.registered_buffers.contains_key(&buffer_id) {
12094 if let Some(lsp_store) = self.lsp_store(cx) {
12095 lsp_store.update(cx, |lsp_store, cx| {
12096 self.registered_buffers.insert(
12097 buffer_id,
12098 lsp_store.register_buffer_with_language_servers(&buffer, cx),
12099 );
12100 })
12101 }
12102 }
12103 }
12104 cx.emit(EditorEvent::BufferEdited);
12105 cx.emit(SearchEvent::MatchesInvalidated);
12106 if *singleton_buffer_edited {
12107 if let Some(project) = &self.project {
12108 let project = project.read(cx);
12109 #[allow(clippy::mutable_key_type)]
12110 let languages_affected = multibuffer
12111 .read(cx)
12112 .all_buffers()
12113 .into_iter()
12114 .filter_map(|buffer| {
12115 let buffer = buffer.read(cx);
12116 let language = buffer.language()?;
12117 if project.is_local()
12118 && project
12119 .language_servers_for_local_buffer(buffer, cx)
12120 .count()
12121 == 0
12122 {
12123 None
12124 } else {
12125 Some(language)
12126 }
12127 })
12128 .cloned()
12129 .collect::<HashSet<_>>();
12130 if !languages_affected.is_empty() {
12131 self.refresh_inlay_hints(
12132 InlayHintRefreshReason::BufferEdited(languages_affected),
12133 cx,
12134 );
12135 }
12136 }
12137 }
12138
12139 let Some(project) = &self.project else { return };
12140 let (telemetry, is_via_ssh) = {
12141 let project = project.read(cx);
12142 let telemetry = project.client().telemetry().clone();
12143 let is_via_ssh = project.is_via_ssh();
12144 (telemetry, is_via_ssh)
12145 };
12146 refresh_linked_ranges(self, cx);
12147 telemetry.log_edit_event("editor", is_via_ssh);
12148 }
12149 multi_buffer::Event::ExcerptsAdded {
12150 buffer,
12151 predecessor,
12152 excerpts,
12153 } => {
12154 self.tasks_update_task = Some(self.refresh_runnables(cx));
12155 let buffer_id = buffer.read(cx).remote_id();
12156 if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12157 if let Some(project) = &self.project {
12158 get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12159 }
12160 }
12161 cx.emit(EditorEvent::ExcerptsAdded {
12162 buffer: buffer.clone(),
12163 predecessor: *predecessor,
12164 excerpts: excerpts.clone(),
12165 });
12166 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12167 }
12168 multi_buffer::Event::ExcerptsRemoved { ids } => {
12169 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12170 let buffer = self.buffer.read(cx);
12171 self.registered_buffers
12172 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12173 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12174 }
12175 multi_buffer::Event::ExcerptsEdited { ids } => {
12176 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12177 }
12178 multi_buffer::Event::ExcerptsExpanded { ids } => {
12179 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12180 }
12181 multi_buffer::Event::Reparsed(buffer_id) => {
12182 self.tasks_update_task = Some(self.refresh_runnables(cx));
12183
12184 cx.emit(EditorEvent::Reparsed(*buffer_id));
12185 }
12186 multi_buffer::Event::LanguageChanged(buffer_id) => {
12187 linked_editing_ranges::refresh_linked_ranges(self, cx);
12188 cx.emit(EditorEvent::Reparsed(*buffer_id));
12189 cx.notify();
12190 }
12191 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12192 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12193 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12194 cx.emit(EditorEvent::TitleChanged)
12195 }
12196 // multi_buffer::Event::DiffBaseChanged => {
12197 // self.scrollbar_marker_state.dirty = true;
12198 // cx.emit(EditorEvent::DiffBaseChanged);
12199 // cx.notify();
12200 // }
12201 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12202 multi_buffer::Event::DiagnosticsUpdated => {
12203 self.refresh_active_diagnostics(cx);
12204 self.scrollbar_marker_state.dirty = true;
12205 cx.notify();
12206 }
12207 _ => {}
12208 };
12209 }
12210
12211 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12212 cx.notify();
12213 }
12214
12215 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12216 self.tasks_update_task = Some(self.refresh_runnables(cx));
12217 self.refresh_inline_completion(true, false, cx);
12218 self.refresh_inlay_hints(
12219 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12220 self.selections.newest_anchor().head(),
12221 &self.buffer.read(cx).snapshot(cx),
12222 cx,
12223 )),
12224 cx,
12225 );
12226
12227 let old_cursor_shape = self.cursor_shape;
12228
12229 {
12230 let editor_settings = EditorSettings::get_global(cx);
12231 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12232 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12233 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12234 }
12235
12236 if old_cursor_shape != self.cursor_shape {
12237 cx.emit(EditorEvent::CursorShapeChanged);
12238 }
12239
12240 let project_settings = ProjectSettings::get_global(cx);
12241 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12242
12243 if self.mode == EditorMode::Full {
12244 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12245 if self.git_blame_inline_enabled != inline_blame_enabled {
12246 self.toggle_git_blame_inline_internal(false, cx);
12247 }
12248 }
12249
12250 cx.notify();
12251 }
12252
12253 pub fn set_searchable(&mut self, searchable: bool) {
12254 self.searchable = searchable;
12255 }
12256
12257 pub fn searchable(&self) -> bool {
12258 self.searchable
12259 }
12260
12261 fn open_proposed_changes_editor(
12262 &mut self,
12263 _: &OpenProposedChangesEditor,
12264 cx: &mut ViewContext<Self>,
12265 ) {
12266 let Some(workspace) = self.workspace() else {
12267 cx.propagate();
12268 return;
12269 };
12270
12271 let selections = self.selections.all::<usize>(cx);
12272 let buffer = self.buffer.read(cx);
12273 let mut new_selections_by_buffer = HashMap::default();
12274 for selection in selections {
12275 for (buffer, range, _) in
12276 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12277 {
12278 let mut range = range.to_point(buffer.read(cx));
12279 range.start.column = 0;
12280 range.end.column = buffer.read(cx).line_len(range.end.row);
12281 new_selections_by_buffer
12282 .entry(buffer)
12283 .or_insert(Vec::new())
12284 .push(range)
12285 }
12286 }
12287
12288 let proposed_changes_buffers = new_selections_by_buffer
12289 .into_iter()
12290 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12291 .collect::<Vec<_>>();
12292 let proposed_changes_editor = cx.new_view(|cx| {
12293 ProposedChangesEditor::new(
12294 "Proposed changes",
12295 proposed_changes_buffers,
12296 self.project.clone(),
12297 cx,
12298 )
12299 });
12300
12301 cx.window_context().defer(move |cx| {
12302 workspace.update(cx, |workspace, cx| {
12303 workspace.active_pane().update(cx, |pane, cx| {
12304 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12305 });
12306 });
12307 });
12308 }
12309
12310 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12311 self.open_excerpts_common(None, true, cx)
12312 }
12313
12314 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12315 self.open_excerpts_common(None, false, cx)
12316 }
12317
12318 fn open_excerpts_common(
12319 &mut self,
12320 jump_data: Option<JumpData>,
12321 split: bool,
12322 cx: &mut ViewContext<Self>,
12323 ) {
12324 let Some(workspace) = self.workspace() else {
12325 cx.propagate();
12326 return;
12327 };
12328
12329 if self.buffer.read(cx).is_singleton() {
12330 cx.propagate();
12331 return;
12332 }
12333
12334 let mut new_selections_by_buffer = HashMap::default();
12335 match &jump_data {
12336 Some(jump_data) => {
12337 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12338 if let Some(buffer) = multi_buffer_snapshot
12339 .buffer_id_for_excerpt(jump_data.excerpt_id)
12340 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12341 {
12342 let buffer_snapshot = buffer.read(cx).snapshot();
12343 let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12344 language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12345 } else {
12346 buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12347 };
12348 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12349 new_selections_by_buffer.insert(
12350 buffer,
12351 (
12352 vec![jump_to_offset..jump_to_offset],
12353 Some(jump_data.line_offset_from_top),
12354 ),
12355 );
12356 }
12357 }
12358 None => {
12359 let selections = self.selections.all::<usize>(cx);
12360 let buffer = self.buffer.read(cx);
12361 for selection in selections {
12362 for (mut buffer_handle, mut range, _) in
12363 buffer.range_to_buffer_ranges(selection.range(), cx)
12364 {
12365 // When editing branch buffers, jump to the corresponding location
12366 // in their base buffer.
12367 let buffer = buffer_handle.read(cx);
12368 if let Some(base_buffer) = buffer.base_buffer() {
12369 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12370 buffer_handle = base_buffer;
12371 }
12372
12373 if selection.reversed {
12374 mem::swap(&mut range.start, &mut range.end);
12375 }
12376 new_selections_by_buffer
12377 .entry(buffer_handle)
12378 .or_insert((Vec::new(), None))
12379 .0
12380 .push(range)
12381 }
12382 }
12383 }
12384 }
12385
12386 if new_selections_by_buffer.is_empty() {
12387 return;
12388 }
12389
12390 // We defer the pane interaction because we ourselves are a workspace item
12391 // and activating a new item causes the pane to call a method on us reentrantly,
12392 // which panics if we're on the stack.
12393 cx.window_context().defer(move |cx| {
12394 workspace.update(cx, |workspace, cx| {
12395 let pane = if split {
12396 workspace.adjacent_pane(cx)
12397 } else {
12398 workspace.active_pane().clone()
12399 };
12400
12401 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12402 let editor = buffer
12403 .read(cx)
12404 .file()
12405 .is_none()
12406 .then(|| {
12407 // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
12408 // so `workspace.open_project_item` will never find them, always opening a new editor.
12409 // Instead, we try to activate the existing editor in the pane first.
12410 let (editor, pane_item_index) =
12411 pane.read(cx).items().enumerate().find_map(|(i, item)| {
12412 let editor = item.downcast::<Editor>()?;
12413 let singleton_buffer =
12414 editor.read(cx).buffer().read(cx).as_singleton()?;
12415 if singleton_buffer == buffer {
12416 Some((editor, i))
12417 } else {
12418 None
12419 }
12420 })?;
12421 pane.update(cx, |pane, cx| {
12422 pane.activate_item(pane_item_index, true, true, cx)
12423 });
12424 Some(editor)
12425 })
12426 .flatten()
12427 .unwrap_or_else(|| {
12428 workspace.open_project_item::<Self>(
12429 pane.clone(),
12430 buffer,
12431 true,
12432 true,
12433 cx,
12434 )
12435 });
12436
12437 editor.update(cx, |editor, cx| {
12438 let autoscroll = match scroll_offset {
12439 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12440 None => Autoscroll::newest(),
12441 };
12442 let nav_history = editor.nav_history.take();
12443 editor.change_selections(Some(autoscroll), cx, |s| {
12444 s.select_ranges(ranges);
12445 });
12446 editor.nav_history = nav_history;
12447 });
12448 }
12449 })
12450 });
12451 }
12452
12453 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12454 let snapshot = self.buffer.read(cx).read(cx);
12455 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12456 Some(
12457 ranges
12458 .iter()
12459 .map(move |range| {
12460 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12461 })
12462 .collect(),
12463 )
12464 }
12465
12466 fn selection_replacement_ranges(
12467 &self,
12468 range: Range<OffsetUtf16>,
12469 cx: &mut AppContext,
12470 ) -> Vec<Range<OffsetUtf16>> {
12471 let selections = self.selections.all::<OffsetUtf16>(cx);
12472 let newest_selection = selections
12473 .iter()
12474 .max_by_key(|selection| selection.id)
12475 .unwrap();
12476 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12477 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12478 let snapshot = self.buffer.read(cx).read(cx);
12479 selections
12480 .into_iter()
12481 .map(|mut selection| {
12482 selection.start.0 =
12483 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12484 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12485 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12486 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12487 })
12488 .collect()
12489 }
12490
12491 fn report_editor_event(
12492 &self,
12493 operation: &'static str,
12494 file_extension: Option<String>,
12495 cx: &AppContext,
12496 ) {
12497 if cfg!(any(test, feature = "test-support")) {
12498 return;
12499 }
12500
12501 let Some(project) = &self.project else { return };
12502
12503 // If None, we are in a file without an extension
12504 let file = self
12505 .buffer
12506 .read(cx)
12507 .as_singleton()
12508 .and_then(|b| b.read(cx).file());
12509 let file_extension = file_extension.or(file
12510 .as_ref()
12511 .and_then(|file| Path::new(file.file_name(cx)).extension())
12512 .and_then(|e| e.to_str())
12513 .map(|a| a.to_string()));
12514
12515 let vim_mode = cx
12516 .global::<SettingsStore>()
12517 .raw_user_settings()
12518 .get("vim_mode")
12519 == Some(&serde_json::Value::Bool(true));
12520
12521 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12522 == language::language_settings::InlineCompletionProvider::Copilot;
12523 let copilot_enabled_for_language = self
12524 .buffer
12525 .read(cx)
12526 .settings_at(0, cx)
12527 .show_inline_completions;
12528
12529 let project = project.read(cx);
12530 let telemetry = project.client().telemetry().clone();
12531 telemetry.report_editor_event(
12532 file_extension,
12533 vim_mode,
12534 operation,
12535 copilot_enabled,
12536 copilot_enabled_for_language,
12537 project.is_via_ssh(),
12538 )
12539 }
12540
12541 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12542 /// with each line being an array of {text, highlight} objects.
12543 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12544 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12545 return;
12546 };
12547
12548 #[derive(Serialize)]
12549 struct Chunk<'a> {
12550 text: String,
12551 highlight: Option<&'a str>,
12552 }
12553
12554 let snapshot = buffer.read(cx).snapshot();
12555 let range = self
12556 .selected_text_range(false, cx)
12557 .and_then(|selection| {
12558 if selection.range.is_empty() {
12559 None
12560 } else {
12561 Some(selection.range)
12562 }
12563 })
12564 .unwrap_or_else(|| 0..snapshot.len());
12565
12566 let chunks = snapshot.chunks(range, true);
12567 let mut lines = Vec::new();
12568 let mut line: VecDeque<Chunk> = VecDeque::new();
12569
12570 let Some(style) = self.style.as_ref() else {
12571 return;
12572 };
12573
12574 for chunk in chunks {
12575 let highlight = chunk
12576 .syntax_highlight_id
12577 .and_then(|id| id.name(&style.syntax));
12578 let mut chunk_lines = chunk.text.split('\n').peekable();
12579 while let Some(text) = chunk_lines.next() {
12580 let mut merged_with_last_token = false;
12581 if let Some(last_token) = line.back_mut() {
12582 if last_token.highlight == highlight {
12583 last_token.text.push_str(text);
12584 merged_with_last_token = true;
12585 }
12586 }
12587
12588 if !merged_with_last_token {
12589 line.push_back(Chunk {
12590 text: text.into(),
12591 highlight,
12592 });
12593 }
12594
12595 if chunk_lines.peek().is_some() {
12596 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12597 line.pop_front();
12598 }
12599 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12600 line.pop_back();
12601 }
12602
12603 lines.push(mem::take(&mut line));
12604 }
12605 }
12606 }
12607
12608 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12609 return;
12610 };
12611 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12612 }
12613
12614 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12615 self.request_autoscroll(Autoscroll::newest(), cx);
12616 let position = self.selections.newest_display(cx).start;
12617 mouse_context_menu::deploy_context_menu(self, None, position, cx);
12618 }
12619
12620 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12621 &self.inlay_hint_cache
12622 }
12623
12624 pub fn replay_insert_event(
12625 &mut self,
12626 text: &str,
12627 relative_utf16_range: Option<Range<isize>>,
12628 cx: &mut ViewContext<Self>,
12629 ) {
12630 if !self.input_enabled {
12631 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12632 return;
12633 }
12634 if let Some(relative_utf16_range) = relative_utf16_range {
12635 let selections = self.selections.all::<OffsetUtf16>(cx);
12636 self.change_selections(None, cx, |s| {
12637 let new_ranges = selections.into_iter().map(|range| {
12638 let start = OffsetUtf16(
12639 range
12640 .head()
12641 .0
12642 .saturating_add_signed(relative_utf16_range.start),
12643 );
12644 let end = OffsetUtf16(
12645 range
12646 .head()
12647 .0
12648 .saturating_add_signed(relative_utf16_range.end),
12649 );
12650 start..end
12651 });
12652 s.select_ranges(new_ranges);
12653 });
12654 }
12655
12656 self.handle_input(text, cx);
12657 }
12658
12659 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12660 let Some(provider) = self.semantics_provider.as_ref() else {
12661 return false;
12662 };
12663
12664 let mut supports = false;
12665 self.buffer().read(cx).for_each_buffer(|buffer| {
12666 supports |= provider.supports_inlay_hints(buffer, cx);
12667 });
12668 supports
12669 }
12670
12671 pub fn focus(&self, cx: &mut WindowContext) {
12672 cx.focus(&self.focus_handle)
12673 }
12674
12675 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12676 self.focus_handle.is_focused(cx)
12677 }
12678
12679 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12680 cx.emit(EditorEvent::Focused);
12681
12682 if let Some(descendant) = self
12683 .last_focused_descendant
12684 .take()
12685 .and_then(|descendant| descendant.upgrade())
12686 {
12687 cx.focus(&descendant);
12688 } else {
12689 if let Some(blame) = self.blame.as_ref() {
12690 blame.update(cx, GitBlame::focus)
12691 }
12692
12693 self.blink_manager.update(cx, BlinkManager::enable);
12694 self.show_cursor_names(cx);
12695 self.buffer.update(cx, |buffer, cx| {
12696 buffer.finalize_last_transaction(cx);
12697 if self.leader_peer_id.is_none() {
12698 buffer.set_active_selections(
12699 &self.selections.disjoint_anchors(),
12700 self.selections.line_mode,
12701 self.cursor_shape,
12702 cx,
12703 );
12704 }
12705 });
12706 }
12707 }
12708
12709 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12710 cx.emit(EditorEvent::FocusedIn)
12711 }
12712
12713 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12714 if event.blurred != self.focus_handle {
12715 self.last_focused_descendant = Some(event.blurred);
12716 }
12717 }
12718
12719 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12720 self.blink_manager.update(cx, BlinkManager::disable);
12721 self.buffer
12722 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12723
12724 if let Some(blame) = self.blame.as_ref() {
12725 blame.update(cx, GitBlame::blur)
12726 }
12727 if !self.hover_state.focused(cx) {
12728 hide_hover(self, cx);
12729 }
12730
12731 self.hide_context_menu(cx);
12732 cx.emit(EditorEvent::Blurred);
12733 cx.notify();
12734 }
12735
12736 pub fn register_action<A: Action>(
12737 &mut self,
12738 listener: impl Fn(&A, &mut WindowContext) + 'static,
12739 ) -> Subscription {
12740 let id = self.next_editor_action_id.post_inc();
12741 let listener = Arc::new(listener);
12742 self.editor_actions.borrow_mut().insert(
12743 id,
12744 Box::new(move |cx| {
12745 let cx = cx.window_context();
12746 let listener = listener.clone();
12747 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12748 let action = action.downcast_ref().unwrap();
12749 if phase == DispatchPhase::Bubble {
12750 listener(action, cx)
12751 }
12752 })
12753 }),
12754 );
12755
12756 let editor_actions = self.editor_actions.clone();
12757 Subscription::new(move || {
12758 editor_actions.borrow_mut().remove(&id);
12759 })
12760 }
12761
12762 pub fn file_header_size(&self) -> u32 {
12763 FILE_HEADER_HEIGHT
12764 }
12765
12766 pub fn revert(
12767 &mut self,
12768 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12769 cx: &mut ViewContext<Self>,
12770 ) {
12771 self.buffer().update(cx, |multi_buffer, cx| {
12772 for (buffer_id, changes) in revert_changes {
12773 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12774 buffer.update(cx, |buffer, cx| {
12775 buffer.edit(
12776 changes.into_iter().map(|(range, text)| {
12777 (range, text.to_string().map(Arc::<str>::from))
12778 }),
12779 None,
12780 cx,
12781 );
12782 });
12783 }
12784 }
12785 });
12786 self.change_selections(None, cx, |selections| selections.refresh());
12787 }
12788
12789 pub fn to_pixel_point(
12790 &mut self,
12791 source: multi_buffer::Anchor,
12792 editor_snapshot: &EditorSnapshot,
12793 cx: &mut ViewContext<Self>,
12794 ) -> Option<gpui::Point<Pixels>> {
12795 let source_point = source.to_display_point(editor_snapshot);
12796 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12797 }
12798
12799 pub fn display_to_pixel_point(
12800 &self,
12801 source: DisplayPoint,
12802 editor_snapshot: &EditorSnapshot,
12803 cx: &WindowContext,
12804 ) -> Option<gpui::Point<Pixels>> {
12805 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12806 let text_layout_details = self.text_layout_details(cx);
12807 let scroll_top = text_layout_details
12808 .scroll_anchor
12809 .scroll_position(editor_snapshot)
12810 .y;
12811
12812 if source.row().as_f32() < scroll_top.floor() {
12813 return None;
12814 }
12815 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12816 let source_y = line_height * (source.row().as_f32() - scroll_top);
12817 Some(gpui::Point::new(source_x, source_y))
12818 }
12819
12820 pub fn has_active_completions_menu(&self) -> bool {
12821 self.context_menu.read().as_ref().map_or(false, |menu| {
12822 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
12823 })
12824 }
12825
12826 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12827 self.addons
12828 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12829 }
12830
12831 pub fn unregister_addon<T: Addon>(&mut self) {
12832 self.addons.remove(&std::any::TypeId::of::<T>());
12833 }
12834
12835 pub fn addon<T: Addon>(&self) -> Option<&T> {
12836 let type_id = std::any::TypeId::of::<T>();
12837 self.addons
12838 .get(&type_id)
12839 .and_then(|item| item.to_any().downcast_ref::<T>())
12840 }
12841
12842 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
12843 let text_layout_details = self.text_layout_details(cx);
12844 let style = &text_layout_details.editor_style;
12845 let font_id = cx.text_system().resolve_font(&style.text.font());
12846 let font_size = style.text.font_size.to_pixels(cx.rem_size());
12847 let line_height = style.text.line_height_in_pixels(cx.rem_size());
12848
12849 let em_width = cx
12850 .text_system()
12851 .typographic_bounds(font_id, font_size, 'm')
12852 .unwrap()
12853 .size
12854 .width;
12855
12856 gpui::Point::new(em_width, line_height)
12857 }
12858}
12859
12860fn get_unstaged_changes_for_buffers(
12861 project: &Model<Project>,
12862 buffers: impl IntoIterator<Item = Model<Buffer>>,
12863 cx: &mut ViewContext<Editor>,
12864) {
12865 let mut tasks = Vec::new();
12866 project.update(cx, |project, cx| {
12867 for buffer in buffers {
12868 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
12869 }
12870 });
12871 cx.spawn(|this, mut cx| async move {
12872 let change_sets = futures::future::join_all(tasks).await;
12873 this.update(&mut cx, |this, cx| {
12874 for change_set in change_sets {
12875 if let Some(change_set) = change_set.log_err() {
12876 this.diff_map.add_change_set(change_set, cx);
12877 }
12878 }
12879 })
12880 .ok();
12881 })
12882 .detach();
12883}
12884
12885fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
12886 let tab_size = tab_size.get() as usize;
12887 let mut width = offset;
12888
12889 for ch in text.chars() {
12890 width += if ch == '\t' {
12891 tab_size - (width % tab_size)
12892 } else {
12893 1
12894 };
12895 }
12896
12897 width - offset
12898}
12899
12900#[cfg(test)]
12901mod tests {
12902 use super::*;
12903
12904 #[test]
12905 fn test_string_size_with_expanded_tabs() {
12906 let nz = |val| NonZeroU32::new(val).unwrap();
12907 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
12908 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
12909 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
12910 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
12911 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
12912 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
12913 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
12914 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
12915 }
12916}
12917
12918/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
12919struct WordBreakingTokenizer<'a> {
12920 input: &'a str,
12921}
12922
12923impl<'a> WordBreakingTokenizer<'a> {
12924 fn new(input: &'a str) -> Self {
12925 Self { input }
12926 }
12927}
12928
12929fn is_char_ideographic(ch: char) -> bool {
12930 use unicode_script::Script::*;
12931 use unicode_script::UnicodeScript;
12932 matches!(ch.script(), Han | Tangut | Yi)
12933}
12934
12935fn is_grapheme_ideographic(text: &str) -> bool {
12936 text.chars().any(is_char_ideographic)
12937}
12938
12939fn is_grapheme_whitespace(text: &str) -> bool {
12940 text.chars().any(|x| x.is_whitespace())
12941}
12942
12943fn should_stay_with_preceding_ideograph(text: &str) -> bool {
12944 text.chars().next().map_or(false, |ch| {
12945 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
12946 })
12947}
12948
12949#[derive(PartialEq, Eq, Debug, Clone, Copy)]
12950struct WordBreakToken<'a> {
12951 token: &'a str,
12952 grapheme_len: usize,
12953 is_whitespace: bool,
12954}
12955
12956impl<'a> Iterator for WordBreakingTokenizer<'a> {
12957 /// Yields a span, the count of graphemes in the token, and whether it was
12958 /// whitespace. Note that it also breaks at word boundaries.
12959 type Item = WordBreakToken<'a>;
12960
12961 fn next(&mut self) -> Option<Self::Item> {
12962 use unicode_segmentation::UnicodeSegmentation;
12963 if self.input.is_empty() {
12964 return None;
12965 }
12966
12967 let mut iter = self.input.graphemes(true).peekable();
12968 let mut offset = 0;
12969 let mut graphemes = 0;
12970 if let Some(first_grapheme) = iter.next() {
12971 let is_whitespace = is_grapheme_whitespace(first_grapheme);
12972 offset += first_grapheme.len();
12973 graphemes += 1;
12974 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
12975 if let Some(grapheme) = iter.peek().copied() {
12976 if should_stay_with_preceding_ideograph(grapheme) {
12977 offset += grapheme.len();
12978 graphemes += 1;
12979 }
12980 }
12981 } else {
12982 let mut words = self.input[offset..].split_word_bound_indices().peekable();
12983 let mut next_word_bound = words.peek().copied();
12984 if next_word_bound.map_or(false, |(i, _)| i == 0) {
12985 next_word_bound = words.next();
12986 }
12987 while let Some(grapheme) = iter.peek().copied() {
12988 if next_word_bound.map_or(false, |(i, _)| i == offset) {
12989 break;
12990 };
12991 if is_grapheme_whitespace(grapheme) != is_whitespace {
12992 break;
12993 };
12994 offset += grapheme.len();
12995 graphemes += 1;
12996 iter.next();
12997 }
12998 }
12999 let token = &self.input[..offset];
13000 self.input = &self.input[offset..];
13001 if is_whitespace {
13002 Some(WordBreakToken {
13003 token: " ",
13004 grapheme_len: 1,
13005 is_whitespace: true,
13006 })
13007 } else {
13008 Some(WordBreakToken {
13009 token,
13010 grapheme_len: graphemes,
13011 is_whitespace: false,
13012 })
13013 }
13014 } else {
13015 None
13016 }
13017 }
13018}
13019
13020#[test]
13021fn test_word_breaking_tokenizer() {
13022 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13023 ("", &[]),
13024 (" ", &[(" ", 1, true)]),
13025 ("Ʒ", &[("Ʒ", 1, false)]),
13026 ("Ǽ", &[("Ǽ", 1, false)]),
13027 ("⋑", &[("⋑", 1, false)]),
13028 ("⋑⋑", &[("⋑⋑", 2, false)]),
13029 (
13030 "原理,进而",
13031 &[
13032 ("原", 1, false),
13033 ("理,", 2, false),
13034 ("进", 1, false),
13035 ("而", 1, false),
13036 ],
13037 ),
13038 (
13039 "hello world",
13040 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13041 ),
13042 (
13043 "hello, world",
13044 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13045 ),
13046 (
13047 " hello world",
13048 &[
13049 (" ", 1, true),
13050 ("hello", 5, false),
13051 (" ", 1, true),
13052 ("world", 5, false),
13053 ],
13054 ),
13055 (
13056 "这是什么 \n 钢笔",
13057 &[
13058 ("这", 1, false),
13059 ("是", 1, false),
13060 ("什", 1, false),
13061 ("么", 1, false),
13062 (" ", 1, true),
13063 ("钢", 1, false),
13064 ("笔", 1, false),
13065 ],
13066 ),
13067 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13068 ];
13069
13070 for (input, result) in tests {
13071 assert_eq!(
13072 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13073 result
13074 .iter()
13075 .copied()
13076 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13077 token,
13078 grapheme_len,
13079 is_whitespace,
13080 })
13081 .collect::<Vec<_>>()
13082 );
13083 }
13084}
13085
13086fn wrap_with_prefix(
13087 line_prefix: String,
13088 unwrapped_text: String,
13089 wrap_column: usize,
13090 tab_size: NonZeroU32,
13091) -> String {
13092 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13093 let mut wrapped_text = String::new();
13094 let mut current_line = line_prefix.clone();
13095
13096 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13097 let mut current_line_len = line_prefix_len;
13098 for WordBreakToken {
13099 token,
13100 grapheme_len,
13101 is_whitespace,
13102 } in tokenizer
13103 {
13104 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13105 wrapped_text.push_str(current_line.trim_end());
13106 wrapped_text.push('\n');
13107 current_line.truncate(line_prefix.len());
13108 current_line_len = line_prefix_len;
13109 if !is_whitespace {
13110 current_line.push_str(token);
13111 current_line_len += grapheme_len;
13112 }
13113 } else if !is_whitespace {
13114 current_line.push_str(token);
13115 current_line_len += grapheme_len;
13116 } else if current_line_len != line_prefix_len {
13117 current_line.push(' ');
13118 current_line_len += 1;
13119 }
13120 }
13121
13122 if !current_line.is_empty() {
13123 wrapped_text.push_str(¤t_line);
13124 }
13125 wrapped_text
13126}
13127
13128#[test]
13129fn test_wrap_with_prefix() {
13130 assert_eq!(
13131 wrap_with_prefix(
13132 "# ".to_string(),
13133 "abcdefg".to_string(),
13134 4,
13135 NonZeroU32::new(4).unwrap()
13136 ),
13137 "# abcdefg"
13138 );
13139 assert_eq!(
13140 wrap_with_prefix(
13141 "".to_string(),
13142 "\thello world".to_string(),
13143 8,
13144 NonZeroU32::new(4).unwrap()
13145 ),
13146 "hello\nworld"
13147 );
13148 assert_eq!(
13149 wrap_with_prefix(
13150 "// ".to_string(),
13151 "xx \nyy zz aa bb cc".to_string(),
13152 12,
13153 NonZeroU32::new(4).unwrap()
13154 ),
13155 "// xx yy zz\n// aa bb cc"
13156 );
13157 assert_eq!(
13158 wrap_with_prefix(
13159 String::new(),
13160 "这是什么 \n 钢笔".to_string(),
13161 3,
13162 NonZeroU32::new(4).unwrap()
13163 ),
13164 "这是什\n么 钢\n笔"
13165 );
13166}
13167
13168fn hunks_for_selections(
13169 snapshot: &EditorSnapshot,
13170 selections: &[Selection<Point>],
13171) -> Vec<MultiBufferDiffHunk> {
13172 hunks_for_ranges(
13173 selections.iter().map(|selection| selection.range()),
13174 snapshot,
13175 )
13176}
13177
13178pub fn hunks_for_ranges(
13179 ranges: impl Iterator<Item = Range<Point>>,
13180 snapshot: &EditorSnapshot,
13181) -> Vec<MultiBufferDiffHunk> {
13182 let mut hunks = Vec::new();
13183 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13184 HashMap::default();
13185 for query_range in ranges {
13186 let query_rows =
13187 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13188 for hunk in snapshot.diff_map.diff_hunks_in_range(
13189 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13190 &snapshot.buffer_snapshot,
13191 ) {
13192 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13193 // when the caret is just above or just below the deleted hunk.
13194 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13195 let related_to_selection = if allow_adjacent {
13196 hunk.row_range.overlaps(&query_rows)
13197 || hunk.row_range.start == query_rows.end
13198 || hunk.row_range.end == query_rows.start
13199 } else {
13200 hunk.row_range.overlaps(&query_rows)
13201 };
13202 if related_to_selection {
13203 if !processed_buffer_rows
13204 .entry(hunk.buffer_id)
13205 .or_default()
13206 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13207 {
13208 continue;
13209 }
13210 hunks.push(hunk);
13211 }
13212 }
13213 }
13214
13215 hunks
13216}
13217
13218pub trait CollaborationHub {
13219 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13220 fn user_participant_indices<'a>(
13221 &self,
13222 cx: &'a AppContext,
13223 ) -> &'a HashMap<u64, ParticipantIndex>;
13224 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13225}
13226
13227impl CollaborationHub for Model<Project> {
13228 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13229 self.read(cx).collaborators()
13230 }
13231
13232 fn user_participant_indices<'a>(
13233 &self,
13234 cx: &'a AppContext,
13235 ) -> &'a HashMap<u64, ParticipantIndex> {
13236 self.read(cx).user_store().read(cx).participant_indices()
13237 }
13238
13239 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13240 let this = self.read(cx);
13241 let user_ids = this.collaborators().values().map(|c| c.user_id);
13242 this.user_store().read_with(cx, |user_store, cx| {
13243 user_store.participant_names(user_ids, cx)
13244 })
13245 }
13246}
13247
13248pub trait SemanticsProvider {
13249 fn hover(
13250 &self,
13251 buffer: &Model<Buffer>,
13252 position: text::Anchor,
13253 cx: &mut AppContext,
13254 ) -> Option<Task<Vec<project::Hover>>>;
13255
13256 fn inlay_hints(
13257 &self,
13258 buffer_handle: Model<Buffer>,
13259 range: Range<text::Anchor>,
13260 cx: &mut AppContext,
13261 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13262
13263 fn resolve_inlay_hint(
13264 &self,
13265 hint: InlayHint,
13266 buffer_handle: Model<Buffer>,
13267 server_id: LanguageServerId,
13268 cx: &mut AppContext,
13269 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13270
13271 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13272
13273 fn document_highlights(
13274 &self,
13275 buffer: &Model<Buffer>,
13276 position: text::Anchor,
13277 cx: &mut AppContext,
13278 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13279
13280 fn definitions(
13281 &self,
13282 buffer: &Model<Buffer>,
13283 position: text::Anchor,
13284 kind: GotoDefinitionKind,
13285 cx: &mut AppContext,
13286 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13287
13288 fn range_for_rename(
13289 &self,
13290 buffer: &Model<Buffer>,
13291 position: text::Anchor,
13292 cx: &mut AppContext,
13293 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13294
13295 fn perform_rename(
13296 &self,
13297 buffer: &Model<Buffer>,
13298 position: text::Anchor,
13299 new_name: String,
13300 cx: &mut AppContext,
13301 ) -> Option<Task<Result<ProjectTransaction>>>;
13302}
13303
13304pub trait CompletionProvider {
13305 fn completions(
13306 &self,
13307 buffer: &Model<Buffer>,
13308 buffer_position: text::Anchor,
13309 trigger: CompletionContext,
13310 cx: &mut ViewContext<Editor>,
13311 ) -> Task<Result<Vec<Completion>>>;
13312
13313 fn resolve_completions(
13314 &self,
13315 buffer: Model<Buffer>,
13316 completion_indices: Vec<usize>,
13317 completions: Arc<RwLock<Box<[Completion]>>>,
13318 cx: &mut ViewContext<Editor>,
13319 ) -> Task<Result<bool>>;
13320
13321 fn apply_additional_edits_for_completion(
13322 &self,
13323 buffer: Model<Buffer>,
13324 completion: Completion,
13325 push_to_history: bool,
13326 cx: &mut ViewContext<Editor>,
13327 ) -> Task<Result<Option<language::Transaction>>>;
13328
13329 fn is_completion_trigger(
13330 &self,
13331 buffer: &Model<Buffer>,
13332 position: language::Anchor,
13333 text: &str,
13334 trigger_in_words: bool,
13335 cx: &mut ViewContext<Editor>,
13336 ) -> bool;
13337
13338 fn sort_completions(&self) -> bool {
13339 true
13340 }
13341}
13342
13343pub trait CodeActionProvider {
13344 fn code_actions(
13345 &self,
13346 buffer: &Model<Buffer>,
13347 range: Range<text::Anchor>,
13348 cx: &mut WindowContext,
13349 ) -> Task<Result<Vec<CodeAction>>>;
13350
13351 fn apply_code_action(
13352 &self,
13353 buffer_handle: Model<Buffer>,
13354 action: CodeAction,
13355 excerpt_id: ExcerptId,
13356 push_to_history: bool,
13357 cx: &mut WindowContext,
13358 ) -> Task<Result<ProjectTransaction>>;
13359}
13360
13361impl CodeActionProvider for Model<Project> {
13362 fn code_actions(
13363 &self,
13364 buffer: &Model<Buffer>,
13365 range: Range<text::Anchor>,
13366 cx: &mut WindowContext,
13367 ) -> Task<Result<Vec<CodeAction>>> {
13368 self.update(cx, |project, cx| {
13369 project.code_actions(buffer, range, None, cx)
13370 })
13371 }
13372
13373 fn apply_code_action(
13374 &self,
13375 buffer_handle: Model<Buffer>,
13376 action: CodeAction,
13377 _excerpt_id: ExcerptId,
13378 push_to_history: bool,
13379 cx: &mut WindowContext,
13380 ) -> Task<Result<ProjectTransaction>> {
13381 self.update(cx, |project, cx| {
13382 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13383 })
13384 }
13385}
13386
13387fn snippet_completions(
13388 project: &Project,
13389 buffer: &Model<Buffer>,
13390 buffer_position: text::Anchor,
13391 cx: &mut AppContext,
13392) -> Task<Result<Vec<Completion>>> {
13393 let language = buffer.read(cx).language_at(buffer_position);
13394 let language_name = language.as_ref().map(|language| language.lsp_id());
13395 let snippet_store = project.snippets().read(cx);
13396 let snippets = snippet_store.snippets_for(language_name, cx);
13397
13398 if snippets.is_empty() {
13399 return Task::ready(Ok(vec![]));
13400 }
13401 let snapshot = buffer.read(cx).text_snapshot();
13402 let chars: String = snapshot
13403 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13404 .collect();
13405
13406 let scope = language.map(|language| language.default_scope());
13407 let executor = cx.background_executor().clone();
13408
13409 cx.background_executor().spawn(async move {
13410 let classifier = CharClassifier::new(scope).for_completion(true);
13411 let mut last_word = chars
13412 .chars()
13413 .take_while(|c| classifier.is_word(*c))
13414 .collect::<String>();
13415 last_word = last_word.chars().rev().collect();
13416
13417 if last_word.is_empty() {
13418 return Ok(vec![]);
13419 }
13420
13421 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13422 let to_lsp = |point: &text::Anchor| {
13423 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13424 point_to_lsp(end)
13425 };
13426 let lsp_end = to_lsp(&buffer_position);
13427
13428 let candidates = snippets
13429 .iter()
13430 .enumerate()
13431 .flat_map(|(ix, snippet)| {
13432 snippet
13433 .prefix
13434 .iter()
13435 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13436 })
13437 .collect::<Vec<StringMatchCandidate>>();
13438
13439 let mut matches = fuzzy::match_strings(
13440 &candidates,
13441 &last_word,
13442 last_word.chars().any(|c| c.is_uppercase()),
13443 100,
13444 &Default::default(),
13445 executor,
13446 )
13447 .await;
13448
13449 // Remove all candidates where the query's start does not match the start of any word in the candidate
13450 if let Some(query_start) = last_word.chars().next() {
13451 matches.retain(|string_match| {
13452 split_words(&string_match.string).any(|word| {
13453 // Check that the first codepoint of the word as lowercase matches the first
13454 // codepoint of the query as lowercase
13455 word.chars()
13456 .flat_map(|codepoint| codepoint.to_lowercase())
13457 .zip(query_start.to_lowercase())
13458 .all(|(word_cp, query_cp)| word_cp == query_cp)
13459 })
13460 });
13461 }
13462
13463 let matched_strings = matches
13464 .into_iter()
13465 .map(|m| m.string)
13466 .collect::<HashSet<_>>();
13467
13468 let result: Vec<Completion> = snippets
13469 .into_iter()
13470 .filter_map(|snippet| {
13471 let matching_prefix = snippet
13472 .prefix
13473 .iter()
13474 .find(|prefix| matched_strings.contains(*prefix))?;
13475 let start = as_offset - last_word.len();
13476 let start = snapshot.anchor_before(start);
13477 let range = start..buffer_position;
13478 let lsp_start = to_lsp(&start);
13479 let lsp_range = lsp::Range {
13480 start: lsp_start,
13481 end: lsp_end,
13482 };
13483 Some(Completion {
13484 old_range: range,
13485 new_text: snippet.body.clone(),
13486 label: CodeLabel {
13487 text: matching_prefix.clone(),
13488 runs: vec![],
13489 filter_range: 0..matching_prefix.len(),
13490 },
13491 server_id: LanguageServerId(usize::MAX),
13492 documentation: snippet.description.clone().map(Documentation::SingleLine),
13493 lsp_completion: lsp::CompletionItem {
13494 label: snippet.prefix.first().unwrap().clone(),
13495 kind: Some(CompletionItemKind::SNIPPET),
13496 label_details: snippet.description.as_ref().map(|description| {
13497 lsp::CompletionItemLabelDetails {
13498 detail: Some(description.clone()),
13499 description: None,
13500 }
13501 }),
13502 insert_text_format: Some(InsertTextFormat::SNIPPET),
13503 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13504 lsp::InsertReplaceEdit {
13505 new_text: snippet.body.clone(),
13506 insert: lsp_range,
13507 replace: lsp_range,
13508 },
13509 )),
13510 filter_text: Some(snippet.body.clone()),
13511 sort_text: Some(char::MAX.to_string()),
13512 ..Default::default()
13513 },
13514 confirm: None,
13515 })
13516 })
13517 .collect();
13518
13519 Ok(result)
13520 })
13521}
13522
13523impl CompletionProvider for Model<Project> {
13524 fn completions(
13525 &self,
13526 buffer: &Model<Buffer>,
13527 buffer_position: text::Anchor,
13528 options: CompletionContext,
13529 cx: &mut ViewContext<Editor>,
13530 ) -> Task<Result<Vec<Completion>>> {
13531 self.update(cx, |project, cx| {
13532 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13533 let project_completions = project.completions(buffer, buffer_position, options, cx);
13534 cx.background_executor().spawn(async move {
13535 let mut completions = project_completions.await?;
13536 let snippets_completions = snippets.await?;
13537 completions.extend(snippets_completions);
13538 Ok(completions)
13539 })
13540 })
13541 }
13542
13543 fn resolve_completions(
13544 &self,
13545 buffer: Model<Buffer>,
13546 completion_indices: Vec<usize>,
13547 completions: Arc<RwLock<Box<[Completion]>>>,
13548 cx: &mut ViewContext<Editor>,
13549 ) -> Task<Result<bool>> {
13550 self.update(cx, |project, cx| {
13551 project.resolve_completions(buffer, completion_indices, completions, cx)
13552 })
13553 }
13554
13555 fn apply_additional_edits_for_completion(
13556 &self,
13557 buffer: Model<Buffer>,
13558 completion: Completion,
13559 push_to_history: bool,
13560 cx: &mut ViewContext<Editor>,
13561 ) -> Task<Result<Option<language::Transaction>>> {
13562 self.update(cx, |project, cx| {
13563 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13564 })
13565 }
13566
13567 fn is_completion_trigger(
13568 &self,
13569 buffer: &Model<Buffer>,
13570 position: language::Anchor,
13571 text: &str,
13572 trigger_in_words: bool,
13573 cx: &mut ViewContext<Editor>,
13574 ) -> bool {
13575 let mut chars = text.chars();
13576 let char = if let Some(char) = chars.next() {
13577 char
13578 } else {
13579 return false;
13580 };
13581 if chars.next().is_some() {
13582 return false;
13583 }
13584
13585 let buffer = buffer.read(cx);
13586 let snapshot = buffer.snapshot();
13587 if !snapshot.settings_at(position, cx).show_completions_on_input {
13588 return false;
13589 }
13590 let classifier = snapshot.char_classifier_at(position).for_completion(true);
13591 if trigger_in_words && classifier.is_word(char) {
13592 return true;
13593 }
13594
13595 buffer.completion_triggers().contains(text)
13596 }
13597}
13598
13599impl SemanticsProvider for Model<Project> {
13600 fn hover(
13601 &self,
13602 buffer: &Model<Buffer>,
13603 position: text::Anchor,
13604 cx: &mut AppContext,
13605 ) -> Option<Task<Vec<project::Hover>>> {
13606 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13607 }
13608
13609 fn document_highlights(
13610 &self,
13611 buffer: &Model<Buffer>,
13612 position: text::Anchor,
13613 cx: &mut AppContext,
13614 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13615 Some(self.update(cx, |project, cx| {
13616 project.document_highlights(buffer, position, cx)
13617 }))
13618 }
13619
13620 fn definitions(
13621 &self,
13622 buffer: &Model<Buffer>,
13623 position: text::Anchor,
13624 kind: GotoDefinitionKind,
13625 cx: &mut AppContext,
13626 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13627 Some(self.update(cx, |project, cx| match kind {
13628 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13629 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13630 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13631 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13632 }))
13633 }
13634
13635 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13636 // TODO: make this work for remote projects
13637 self.read(cx)
13638 .language_servers_for_local_buffer(buffer.read(cx), cx)
13639 .any(
13640 |(_, server)| match server.capabilities().inlay_hint_provider {
13641 Some(lsp::OneOf::Left(enabled)) => enabled,
13642 Some(lsp::OneOf::Right(_)) => true,
13643 None => false,
13644 },
13645 )
13646 }
13647
13648 fn inlay_hints(
13649 &self,
13650 buffer_handle: Model<Buffer>,
13651 range: Range<text::Anchor>,
13652 cx: &mut AppContext,
13653 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13654 Some(self.update(cx, |project, cx| {
13655 project.inlay_hints(buffer_handle, range, cx)
13656 }))
13657 }
13658
13659 fn resolve_inlay_hint(
13660 &self,
13661 hint: InlayHint,
13662 buffer_handle: Model<Buffer>,
13663 server_id: LanguageServerId,
13664 cx: &mut AppContext,
13665 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13666 Some(self.update(cx, |project, cx| {
13667 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13668 }))
13669 }
13670
13671 fn range_for_rename(
13672 &self,
13673 buffer: &Model<Buffer>,
13674 position: text::Anchor,
13675 cx: &mut AppContext,
13676 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13677 Some(self.update(cx, |project, cx| {
13678 project.prepare_rename(buffer.clone(), position, cx)
13679 }))
13680 }
13681
13682 fn perform_rename(
13683 &self,
13684 buffer: &Model<Buffer>,
13685 position: text::Anchor,
13686 new_name: String,
13687 cx: &mut AppContext,
13688 ) -> Option<Task<Result<ProjectTransaction>>> {
13689 Some(self.update(cx, |project, cx| {
13690 project.perform_rename(buffer.clone(), position, new_name, cx)
13691 }))
13692 }
13693}
13694
13695fn inlay_hint_settings(
13696 location: Anchor,
13697 snapshot: &MultiBufferSnapshot,
13698 cx: &mut ViewContext<'_, Editor>,
13699) -> InlayHintSettings {
13700 let file = snapshot.file_at(location);
13701 let language = snapshot.language_at(location).map(|l| l.name());
13702 language_settings(language, file, cx).inlay_hints
13703}
13704
13705fn consume_contiguous_rows(
13706 contiguous_row_selections: &mut Vec<Selection<Point>>,
13707 selection: &Selection<Point>,
13708 display_map: &DisplaySnapshot,
13709 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13710) -> (MultiBufferRow, MultiBufferRow) {
13711 contiguous_row_selections.push(selection.clone());
13712 let start_row = MultiBufferRow(selection.start.row);
13713 let mut end_row = ending_row(selection, display_map);
13714
13715 while let Some(next_selection) = selections.peek() {
13716 if next_selection.start.row <= end_row.0 {
13717 end_row = ending_row(next_selection, display_map);
13718 contiguous_row_selections.push(selections.next().unwrap().clone());
13719 } else {
13720 break;
13721 }
13722 }
13723 (start_row, end_row)
13724}
13725
13726fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13727 if next_selection.end.column > 0 || next_selection.is_empty() {
13728 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13729 } else {
13730 MultiBufferRow(next_selection.end.row)
13731 }
13732}
13733
13734impl EditorSnapshot {
13735 pub fn remote_selections_in_range<'a>(
13736 &'a self,
13737 range: &'a Range<Anchor>,
13738 collaboration_hub: &dyn CollaborationHub,
13739 cx: &'a AppContext,
13740 ) -> impl 'a + Iterator<Item = RemoteSelection> {
13741 let participant_names = collaboration_hub.user_names(cx);
13742 let participant_indices = collaboration_hub.user_participant_indices(cx);
13743 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13744 let collaborators_by_replica_id = collaborators_by_peer_id
13745 .iter()
13746 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13747 .collect::<HashMap<_, _>>();
13748 self.buffer_snapshot
13749 .selections_in_range(range, false)
13750 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13751 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13752 let participant_index = participant_indices.get(&collaborator.user_id).copied();
13753 let user_name = participant_names.get(&collaborator.user_id).cloned();
13754 Some(RemoteSelection {
13755 replica_id,
13756 selection,
13757 cursor_shape,
13758 line_mode,
13759 participant_index,
13760 peer_id: collaborator.peer_id,
13761 user_name,
13762 })
13763 })
13764 }
13765
13766 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13767 self.display_snapshot.buffer_snapshot.language_at(position)
13768 }
13769
13770 pub fn is_focused(&self) -> bool {
13771 self.is_focused
13772 }
13773
13774 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13775 self.placeholder_text.as_ref()
13776 }
13777
13778 pub fn scroll_position(&self) -> gpui::Point<f32> {
13779 self.scroll_anchor.scroll_position(&self.display_snapshot)
13780 }
13781
13782 fn gutter_dimensions(
13783 &self,
13784 font_id: FontId,
13785 font_size: Pixels,
13786 em_width: Pixels,
13787 em_advance: Pixels,
13788 max_line_number_width: Pixels,
13789 cx: &AppContext,
13790 ) -> GutterDimensions {
13791 if !self.show_gutter {
13792 return GutterDimensions::default();
13793 }
13794 let descent = cx.text_system().descent(font_id, font_size);
13795
13796 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13797 matches!(
13798 ProjectSettings::get_global(cx).git.git_gutter,
13799 Some(GitGutterSetting::TrackedFiles)
13800 )
13801 });
13802 let gutter_settings = EditorSettings::get_global(cx).gutter;
13803 let show_line_numbers = self
13804 .show_line_numbers
13805 .unwrap_or(gutter_settings.line_numbers);
13806 let line_gutter_width = if show_line_numbers {
13807 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13808 let min_width_for_number_on_gutter = em_advance * 4.0;
13809 max_line_number_width.max(min_width_for_number_on_gutter)
13810 } else {
13811 0.0.into()
13812 };
13813
13814 let show_code_actions = self
13815 .show_code_actions
13816 .unwrap_or(gutter_settings.code_actions);
13817
13818 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13819
13820 let git_blame_entries_width =
13821 self.git_blame_gutter_max_author_length
13822 .map(|max_author_length| {
13823 // Length of the author name, but also space for the commit hash,
13824 // the spacing and the timestamp.
13825 let max_char_count = max_author_length
13826 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13827 + 7 // length of commit sha
13828 + 14 // length of max relative timestamp ("60 minutes ago")
13829 + 4; // gaps and margins
13830
13831 em_advance * max_char_count
13832 });
13833
13834 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13835 left_padding += if show_code_actions || show_runnables {
13836 em_width * 3.0
13837 } else if show_git_gutter && show_line_numbers {
13838 em_width * 2.0
13839 } else if show_git_gutter || show_line_numbers {
13840 em_width
13841 } else {
13842 px(0.)
13843 };
13844
13845 let right_padding = if gutter_settings.folds && show_line_numbers {
13846 em_width * 4.0
13847 } else if gutter_settings.folds {
13848 em_width * 3.0
13849 } else if show_line_numbers {
13850 em_width
13851 } else {
13852 px(0.)
13853 };
13854
13855 GutterDimensions {
13856 left_padding,
13857 right_padding,
13858 width: line_gutter_width + left_padding + right_padding,
13859 margin: -descent,
13860 git_blame_entries_width,
13861 }
13862 }
13863
13864 pub fn render_crease_toggle(
13865 &self,
13866 buffer_row: MultiBufferRow,
13867 row_contains_cursor: bool,
13868 editor: View<Editor>,
13869 cx: &mut WindowContext,
13870 ) -> Option<AnyElement> {
13871 let folded = self.is_line_folded(buffer_row);
13872 let mut is_foldable = false;
13873
13874 if let Some(crease) = self
13875 .crease_snapshot
13876 .query_row(buffer_row, &self.buffer_snapshot)
13877 {
13878 is_foldable = true;
13879 match crease {
13880 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
13881 if let Some(render_toggle) = render_toggle {
13882 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13883 if folded {
13884 editor.update(cx, |editor, cx| {
13885 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13886 });
13887 } else {
13888 editor.update(cx, |editor, cx| {
13889 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13890 });
13891 }
13892 });
13893 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
13894 }
13895 }
13896 }
13897 }
13898
13899 is_foldable |= self.starts_indent(buffer_row);
13900
13901 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
13902 Some(
13903 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
13904 .toggle_state(folded)
13905 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13906 if folded {
13907 this.unfold_at(&UnfoldAt { buffer_row }, cx);
13908 } else {
13909 this.fold_at(&FoldAt { buffer_row }, cx);
13910 }
13911 }))
13912 .into_any_element(),
13913 )
13914 } else {
13915 None
13916 }
13917 }
13918
13919 pub fn render_crease_trailer(
13920 &self,
13921 buffer_row: MultiBufferRow,
13922 cx: &mut WindowContext,
13923 ) -> Option<AnyElement> {
13924 let folded = self.is_line_folded(buffer_row);
13925 if let Crease::Inline { render_trailer, .. } = self
13926 .crease_snapshot
13927 .query_row(buffer_row, &self.buffer_snapshot)?
13928 {
13929 let render_trailer = render_trailer.as_ref()?;
13930 Some(render_trailer(buffer_row, folded, cx))
13931 } else {
13932 None
13933 }
13934 }
13935}
13936
13937impl Deref for EditorSnapshot {
13938 type Target = DisplaySnapshot;
13939
13940 fn deref(&self) -> &Self::Target {
13941 &self.display_snapshot
13942 }
13943}
13944
13945#[derive(Clone, Debug, PartialEq, Eq)]
13946pub enum EditorEvent {
13947 InputIgnored {
13948 text: Arc<str>,
13949 },
13950 InputHandled {
13951 utf16_range_to_replace: Option<Range<isize>>,
13952 text: Arc<str>,
13953 },
13954 ExcerptsAdded {
13955 buffer: Model<Buffer>,
13956 predecessor: ExcerptId,
13957 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13958 },
13959 ExcerptsRemoved {
13960 ids: Vec<ExcerptId>,
13961 },
13962 BufferFoldToggled {
13963 ids: Vec<ExcerptId>,
13964 folded: bool,
13965 },
13966 ExcerptsEdited {
13967 ids: Vec<ExcerptId>,
13968 },
13969 ExcerptsExpanded {
13970 ids: Vec<ExcerptId>,
13971 },
13972 BufferEdited,
13973 Edited {
13974 transaction_id: clock::Lamport,
13975 },
13976 Reparsed(BufferId),
13977 Focused,
13978 FocusedIn,
13979 Blurred,
13980 DirtyChanged,
13981 Saved,
13982 TitleChanged,
13983 DiffBaseChanged,
13984 SelectionsChanged {
13985 local: bool,
13986 },
13987 ScrollPositionChanged {
13988 local: bool,
13989 autoscroll: bool,
13990 },
13991 Closed,
13992 TransactionUndone {
13993 transaction_id: clock::Lamport,
13994 },
13995 TransactionBegun {
13996 transaction_id: clock::Lamport,
13997 },
13998 Reloaded,
13999 CursorShapeChanged,
14000}
14001
14002impl EventEmitter<EditorEvent> for Editor {}
14003
14004impl FocusableView for Editor {
14005 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14006 self.focus_handle.clone()
14007 }
14008}
14009
14010impl Render for Editor {
14011 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14012 let settings = ThemeSettings::get_global(cx);
14013
14014 let mut text_style = match self.mode {
14015 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14016 color: cx.theme().colors().editor_foreground,
14017 font_family: settings.ui_font.family.clone(),
14018 font_features: settings.ui_font.features.clone(),
14019 font_fallbacks: settings.ui_font.fallbacks.clone(),
14020 font_size: rems(0.875).into(),
14021 font_weight: settings.ui_font.weight,
14022 line_height: relative(settings.buffer_line_height.value()),
14023 ..Default::default()
14024 },
14025 EditorMode::Full => TextStyle {
14026 color: cx.theme().colors().editor_foreground,
14027 font_family: settings.buffer_font.family.clone(),
14028 font_features: settings.buffer_font.features.clone(),
14029 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14030 font_size: settings.buffer_font_size(cx).into(),
14031 font_weight: settings.buffer_font.weight,
14032 line_height: relative(settings.buffer_line_height.value()),
14033 ..Default::default()
14034 },
14035 };
14036 if let Some(text_style_refinement) = &self.text_style_refinement {
14037 text_style.refine(text_style_refinement)
14038 }
14039
14040 let background = match self.mode {
14041 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14042 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14043 EditorMode::Full => cx.theme().colors().editor_background,
14044 };
14045
14046 EditorElement::new(
14047 cx.view(),
14048 EditorStyle {
14049 background,
14050 local_player: cx.theme().players().local(),
14051 text: text_style,
14052 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14053 syntax: cx.theme().syntax().clone(),
14054 status: cx.theme().status().clone(),
14055 inlay_hints_style: make_inlay_hints_style(cx),
14056 inline_completion_styles: make_suggestion_styles(cx),
14057 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14058 },
14059 )
14060 }
14061}
14062
14063impl ViewInputHandler for Editor {
14064 fn text_for_range(
14065 &mut self,
14066 range_utf16: Range<usize>,
14067 adjusted_range: &mut Option<Range<usize>>,
14068 cx: &mut ViewContext<Self>,
14069 ) -> Option<String> {
14070 let snapshot = self.buffer.read(cx).read(cx);
14071 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14072 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14073 if (start.0..end.0) != range_utf16 {
14074 adjusted_range.replace(start.0..end.0);
14075 }
14076 Some(snapshot.text_for_range(start..end).collect())
14077 }
14078
14079 fn selected_text_range(
14080 &mut self,
14081 ignore_disabled_input: bool,
14082 cx: &mut ViewContext<Self>,
14083 ) -> Option<UTF16Selection> {
14084 // Prevent the IME menu from appearing when holding down an alphabetic key
14085 // while input is disabled.
14086 if !ignore_disabled_input && !self.input_enabled {
14087 return None;
14088 }
14089
14090 let selection = self.selections.newest::<OffsetUtf16>(cx);
14091 let range = selection.range();
14092
14093 Some(UTF16Selection {
14094 range: range.start.0..range.end.0,
14095 reversed: selection.reversed,
14096 })
14097 }
14098
14099 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14100 let snapshot = self.buffer.read(cx).read(cx);
14101 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14102 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14103 }
14104
14105 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14106 self.clear_highlights::<InputComposition>(cx);
14107 self.ime_transaction.take();
14108 }
14109
14110 fn replace_text_in_range(
14111 &mut self,
14112 range_utf16: Option<Range<usize>>,
14113 text: &str,
14114 cx: &mut ViewContext<Self>,
14115 ) {
14116 if !self.input_enabled {
14117 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14118 return;
14119 }
14120
14121 self.transact(cx, |this, cx| {
14122 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14123 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14124 Some(this.selection_replacement_ranges(range_utf16, cx))
14125 } else {
14126 this.marked_text_ranges(cx)
14127 };
14128
14129 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14130 let newest_selection_id = this.selections.newest_anchor().id;
14131 this.selections
14132 .all::<OffsetUtf16>(cx)
14133 .iter()
14134 .zip(ranges_to_replace.iter())
14135 .find_map(|(selection, range)| {
14136 if selection.id == newest_selection_id {
14137 Some(
14138 (range.start.0 as isize - selection.head().0 as isize)
14139 ..(range.end.0 as isize - selection.head().0 as isize),
14140 )
14141 } else {
14142 None
14143 }
14144 })
14145 });
14146
14147 cx.emit(EditorEvent::InputHandled {
14148 utf16_range_to_replace: range_to_replace,
14149 text: text.into(),
14150 });
14151
14152 if let Some(new_selected_ranges) = new_selected_ranges {
14153 this.change_selections(None, cx, |selections| {
14154 selections.select_ranges(new_selected_ranges)
14155 });
14156 this.backspace(&Default::default(), cx);
14157 }
14158
14159 this.handle_input(text, cx);
14160 });
14161
14162 if let Some(transaction) = self.ime_transaction {
14163 self.buffer.update(cx, |buffer, cx| {
14164 buffer.group_until_transaction(transaction, cx);
14165 });
14166 }
14167
14168 self.unmark_text(cx);
14169 }
14170
14171 fn replace_and_mark_text_in_range(
14172 &mut self,
14173 range_utf16: Option<Range<usize>>,
14174 text: &str,
14175 new_selected_range_utf16: Option<Range<usize>>,
14176 cx: &mut ViewContext<Self>,
14177 ) {
14178 if !self.input_enabled {
14179 return;
14180 }
14181
14182 let transaction = self.transact(cx, |this, cx| {
14183 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14184 let snapshot = this.buffer.read(cx).read(cx);
14185 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14186 for marked_range in &mut marked_ranges {
14187 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14188 marked_range.start.0 += relative_range_utf16.start;
14189 marked_range.start =
14190 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14191 marked_range.end =
14192 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14193 }
14194 }
14195 Some(marked_ranges)
14196 } else if let Some(range_utf16) = range_utf16 {
14197 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14198 Some(this.selection_replacement_ranges(range_utf16, cx))
14199 } else {
14200 None
14201 };
14202
14203 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14204 let newest_selection_id = this.selections.newest_anchor().id;
14205 this.selections
14206 .all::<OffsetUtf16>(cx)
14207 .iter()
14208 .zip(ranges_to_replace.iter())
14209 .find_map(|(selection, range)| {
14210 if selection.id == newest_selection_id {
14211 Some(
14212 (range.start.0 as isize - selection.head().0 as isize)
14213 ..(range.end.0 as isize - selection.head().0 as isize),
14214 )
14215 } else {
14216 None
14217 }
14218 })
14219 });
14220
14221 cx.emit(EditorEvent::InputHandled {
14222 utf16_range_to_replace: range_to_replace,
14223 text: text.into(),
14224 });
14225
14226 if let Some(ranges) = ranges_to_replace {
14227 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14228 }
14229
14230 let marked_ranges = {
14231 let snapshot = this.buffer.read(cx).read(cx);
14232 this.selections
14233 .disjoint_anchors()
14234 .iter()
14235 .map(|selection| {
14236 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14237 })
14238 .collect::<Vec<_>>()
14239 };
14240
14241 if text.is_empty() {
14242 this.unmark_text(cx);
14243 } else {
14244 this.highlight_text::<InputComposition>(
14245 marked_ranges.clone(),
14246 HighlightStyle {
14247 underline: Some(UnderlineStyle {
14248 thickness: px(1.),
14249 color: None,
14250 wavy: false,
14251 }),
14252 ..Default::default()
14253 },
14254 cx,
14255 );
14256 }
14257
14258 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14259 let use_autoclose = this.use_autoclose;
14260 let use_auto_surround = this.use_auto_surround;
14261 this.set_use_autoclose(false);
14262 this.set_use_auto_surround(false);
14263 this.handle_input(text, cx);
14264 this.set_use_autoclose(use_autoclose);
14265 this.set_use_auto_surround(use_auto_surround);
14266
14267 if let Some(new_selected_range) = new_selected_range_utf16 {
14268 let snapshot = this.buffer.read(cx).read(cx);
14269 let new_selected_ranges = marked_ranges
14270 .into_iter()
14271 .map(|marked_range| {
14272 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14273 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14274 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14275 snapshot.clip_offset_utf16(new_start, Bias::Left)
14276 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14277 })
14278 .collect::<Vec<_>>();
14279
14280 drop(snapshot);
14281 this.change_selections(None, cx, |selections| {
14282 selections.select_ranges(new_selected_ranges)
14283 });
14284 }
14285 });
14286
14287 self.ime_transaction = self.ime_transaction.or(transaction);
14288 if let Some(transaction) = self.ime_transaction {
14289 self.buffer.update(cx, |buffer, cx| {
14290 buffer.group_until_transaction(transaction, cx);
14291 });
14292 }
14293
14294 if self.text_highlights::<InputComposition>(cx).is_none() {
14295 self.ime_transaction.take();
14296 }
14297 }
14298
14299 fn bounds_for_range(
14300 &mut self,
14301 range_utf16: Range<usize>,
14302 element_bounds: gpui::Bounds<Pixels>,
14303 cx: &mut ViewContext<Self>,
14304 ) -> Option<gpui::Bounds<Pixels>> {
14305 let text_layout_details = self.text_layout_details(cx);
14306 let gpui::Point {
14307 x: em_width,
14308 y: line_height,
14309 } = self.character_size(cx);
14310
14311 let snapshot = self.snapshot(cx);
14312 let scroll_position = snapshot.scroll_position();
14313 let scroll_left = scroll_position.x * em_width;
14314
14315 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14316 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14317 + self.gutter_dimensions.width
14318 + self.gutter_dimensions.margin;
14319 let y = line_height * (start.row().as_f32() - scroll_position.y);
14320
14321 Some(Bounds {
14322 origin: element_bounds.origin + point(x, y),
14323 size: size(em_width, line_height),
14324 })
14325 }
14326}
14327
14328trait SelectionExt {
14329 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14330 fn spanned_rows(
14331 &self,
14332 include_end_if_at_line_start: bool,
14333 map: &DisplaySnapshot,
14334 ) -> Range<MultiBufferRow>;
14335}
14336
14337impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14338 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14339 let start = self
14340 .start
14341 .to_point(&map.buffer_snapshot)
14342 .to_display_point(map);
14343 let end = self
14344 .end
14345 .to_point(&map.buffer_snapshot)
14346 .to_display_point(map);
14347 if self.reversed {
14348 end..start
14349 } else {
14350 start..end
14351 }
14352 }
14353
14354 fn spanned_rows(
14355 &self,
14356 include_end_if_at_line_start: bool,
14357 map: &DisplaySnapshot,
14358 ) -> Range<MultiBufferRow> {
14359 let start = self.start.to_point(&map.buffer_snapshot);
14360 let mut end = self.end.to_point(&map.buffer_snapshot);
14361 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14362 end.row -= 1;
14363 }
14364
14365 let buffer_start = map.prev_line_boundary(start).0;
14366 let buffer_end = map.next_line_boundary(end).0;
14367 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14368 }
14369}
14370
14371impl<T: InvalidationRegion> InvalidationStack<T> {
14372 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14373 where
14374 S: Clone + ToOffset,
14375 {
14376 while let Some(region) = self.last() {
14377 let all_selections_inside_invalidation_ranges =
14378 if selections.len() == region.ranges().len() {
14379 selections
14380 .iter()
14381 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14382 .all(|(selection, invalidation_range)| {
14383 let head = selection.head().to_offset(buffer);
14384 invalidation_range.start <= head && invalidation_range.end >= head
14385 })
14386 } else {
14387 false
14388 };
14389
14390 if all_selections_inside_invalidation_ranges {
14391 break;
14392 } else {
14393 self.pop();
14394 }
14395 }
14396 }
14397}
14398
14399impl<T> Default for InvalidationStack<T> {
14400 fn default() -> Self {
14401 Self(Default::default())
14402 }
14403}
14404
14405impl<T> Deref for InvalidationStack<T> {
14406 type Target = Vec<T>;
14407
14408 fn deref(&self) -> &Self::Target {
14409 &self.0
14410 }
14411}
14412
14413impl<T> DerefMut for InvalidationStack<T> {
14414 fn deref_mut(&mut self) -> &mut Self::Target {
14415 &mut self.0
14416 }
14417}
14418
14419impl InvalidationRegion for SnippetState {
14420 fn ranges(&self) -> &[Range<Anchor>] {
14421 &self.ranges[self.active_index]
14422 }
14423}
14424
14425pub fn diagnostic_block_renderer(
14426 diagnostic: Diagnostic,
14427 max_message_rows: Option<u8>,
14428 allow_closing: bool,
14429 _is_valid: bool,
14430) -> RenderBlock {
14431 let (text_without_backticks, code_ranges) =
14432 highlight_diagnostic_message(&diagnostic, max_message_rows);
14433
14434 Arc::new(move |cx: &mut BlockContext| {
14435 let group_id: SharedString = cx.block_id.to_string().into();
14436
14437 let mut text_style = cx.text_style().clone();
14438 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14439 let theme_settings = ThemeSettings::get_global(cx);
14440 text_style.font_family = theme_settings.buffer_font.family.clone();
14441 text_style.font_style = theme_settings.buffer_font.style;
14442 text_style.font_features = theme_settings.buffer_font.features.clone();
14443 text_style.font_weight = theme_settings.buffer_font.weight;
14444
14445 let multi_line_diagnostic = diagnostic.message.contains('\n');
14446
14447 let buttons = |diagnostic: &Diagnostic| {
14448 if multi_line_diagnostic {
14449 v_flex()
14450 } else {
14451 h_flex()
14452 }
14453 .when(allow_closing, |div| {
14454 div.children(diagnostic.is_primary.then(|| {
14455 IconButton::new("close-block", IconName::XCircle)
14456 .icon_color(Color::Muted)
14457 .size(ButtonSize::Compact)
14458 .style(ButtonStyle::Transparent)
14459 .visible_on_hover(group_id.clone())
14460 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14461 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14462 }))
14463 })
14464 .child(
14465 IconButton::new("copy-block", IconName::Copy)
14466 .icon_color(Color::Muted)
14467 .size(ButtonSize::Compact)
14468 .style(ButtonStyle::Transparent)
14469 .visible_on_hover(group_id.clone())
14470 .on_click({
14471 let message = diagnostic.message.clone();
14472 move |_click, cx| {
14473 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14474 }
14475 })
14476 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14477 )
14478 };
14479
14480 let icon_size = buttons(&diagnostic)
14481 .into_any_element()
14482 .layout_as_root(AvailableSpace::min_size(), cx);
14483
14484 h_flex()
14485 .id(cx.block_id)
14486 .group(group_id.clone())
14487 .relative()
14488 .size_full()
14489 .block_mouse_down()
14490 .pl(cx.gutter_dimensions.width)
14491 .w(cx.max_width - cx.gutter_dimensions.full_width())
14492 .child(
14493 div()
14494 .flex()
14495 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14496 .flex_shrink(),
14497 )
14498 .child(buttons(&diagnostic))
14499 .child(div().flex().flex_shrink_0().child(
14500 StyledText::new(text_without_backticks.clone()).with_highlights(
14501 &text_style,
14502 code_ranges.iter().map(|range| {
14503 (
14504 range.clone(),
14505 HighlightStyle {
14506 font_weight: Some(FontWeight::BOLD),
14507 ..Default::default()
14508 },
14509 )
14510 }),
14511 ),
14512 ))
14513 .into_any_element()
14514 })
14515}
14516
14517pub fn highlight_diagnostic_message(
14518 diagnostic: &Diagnostic,
14519 mut max_message_rows: Option<u8>,
14520) -> (SharedString, Vec<Range<usize>>) {
14521 let mut text_without_backticks = String::new();
14522 let mut code_ranges = Vec::new();
14523
14524 if let Some(source) = &diagnostic.source {
14525 text_without_backticks.push_str(source);
14526 code_ranges.push(0..source.len());
14527 text_without_backticks.push_str(": ");
14528 }
14529
14530 let mut prev_offset = 0;
14531 let mut in_code_block = false;
14532 let has_row_limit = max_message_rows.is_some();
14533 let mut newline_indices = diagnostic
14534 .message
14535 .match_indices('\n')
14536 .filter(|_| has_row_limit)
14537 .map(|(ix, _)| ix)
14538 .fuse()
14539 .peekable();
14540
14541 for (quote_ix, _) in diagnostic
14542 .message
14543 .match_indices('`')
14544 .chain([(diagnostic.message.len(), "")])
14545 {
14546 let mut first_newline_ix = None;
14547 let mut last_newline_ix = None;
14548 while let Some(newline_ix) = newline_indices.peek() {
14549 if *newline_ix < quote_ix {
14550 if first_newline_ix.is_none() {
14551 first_newline_ix = Some(*newline_ix);
14552 }
14553 last_newline_ix = Some(*newline_ix);
14554
14555 if let Some(rows_left) = &mut max_message_rows {
14556 if *rows_left == 0 {
14557 break;
14558 } else {
14559 *rows_left -= 1;
14560 }
14561 }
14562 let _ = newline_indices.next();
14563 } else {
14564 break;
14565 }
14566 }
14567 let prev_len = text_without_backticks.len();
14568 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14569 text_without_backticks.push_str(new_text);
14570 if in_code_block {
14571 code_ranges.push(prev_len..text_without_backticks.len());
14572 }
14573 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14574 in_code_block = !in_code_block;
14575 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14576 text_without_backticks.push_str("...");
14577 break;
14578 }
14579 }
14580
14581 (text_without_backticks.into(), code_ranges)
14582}
14583
14584fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14585 match severity {
14586 DiagnosticSeverity::ERROR => colors.error,
14587 DiagnosticSeverity::WARNING => colors.warning,
14588 DiagnosticSeverity::INFORMATION => colors.info,
14589 DiagnosticSeverity::HINT => colors.info,
14590 _ => colors.ignored,
14591 }
14592}
14593
14594pub fn styled_runs_for_code_label<'a>(
14595 label: &'a CodeLabel,
14596 syntax_theme: &'a theme::SyntaxTheme,
14597) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14598 let fade_out = HighlightStyle {
14599 fade_out: Some(0.35),
14600 ..Default::default()
14601 };
14602
14603 let mut prev_end = label.filter_range.end;
14604 label
14605 .runs
14606 .iter()
14607 .enumerate()
14608 .flat_map(move |(ix, (range, highlight_id))| {
14609 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14610 style
14611 } else {
14612 return Default::default();
14613 };
14614 let mut muted_style = style;
14615 muted_style.highlight(fade_out);
14616
14617 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14618 if range.start >= label.filter_range.end {
14619 if range.start > prev_end {
14620 runs.push((prev_end..range.start, fade_out));
14621 }
14622 runs.push((range.clone(), muted_style));
14623 } else if range.end <= label.filter_range.end {
14624 runs.push((range.clone(), style));
14625 } else {
14626 runs.push((range.start..label.filter_range.end, style));
14627 runs.push((label.filter_range.end..range.end, muted_style));
14628 }
14629 prev_end = cmp::max(prev_end, range.end);
14630
14631 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14632 runs.push((prev_end..label.text.len(), fade_out));
14633 }
14634
14635 runs
14636 })
14637}
14638
14639pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14640 let mut prev_index = 0;
14641 let mut prev_codepoint: Option<char> = None;
14642 text.char_indices()
14643 .chain([(text.len(), '\0')])
14644 .filter_map(move |(index, codepoint)| {
14645 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14646 let is_boundary = index == text.len()
14647 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14648 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14649 if is_boundary {
14650 let chunk = &text[prev_index..index];
14651 prev_index = index;
14652 Some(chunk)
14653 } else {
14654 None
14655 }
14656 })
14657}
14658
14659pub trait RangeToAnchorExt: Sized {
14660 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14661
14662 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14663 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14664 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14665 }
14666}
14667
14668impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14669 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14670 let start_offset = self.start.to_offset(snapshot);
14671 let end_offset = self.end.to_offset(snapshot);
14672 if start_offset == end_offset {
14673 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14674 } else {
14675 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14676 }
14677 }
14678}
14679
14680pub trait RowExt {
14681 fn as_f32(&self) -> f32;
14682
14683 fn next_row(&self) -> Self;
14684
14685 fn previous_row(&self) -> Self;
14686
14687 fn minus(&self, other: Self) -> u32;
14688}
14689
14690impl RowExt for DisplayRow {
14691 fn as_f32(&self) -> f32 {
14692 self.0 as f32
14693 }
14694
14695 fn next_row(&self) -> Self {
14696 Self(self.0 + 1)
14697 }
14698
14699 fn previous_row(&self) -> Self {
14700 Self(self.0.saturating_sub(1))
14701 }
14702
14703 fn minus(&self, other: Self) -> u32 {
14704 self.0 - other.0
14705 }
14706}
14707
14708impl RowExt for MultiBufferRow {
14709 fn as_f32(&self) -> f32 {
14710 self.0 as f32
14711 }
14712
14713 fn next_row(&self) -> Self {
14714 Self(self.0 + 1)
14715 }
14716
14717 fn previous_row(&self) -> Self {
14718 Self(self.0.saturating_sub(1))
14719 }
14720
14721 fn minus(&self, other: Self) -> u32 {
14722 self.0 - other.0
14723 }
14724}
14725
14726trait RowRangeExt {
14727 type Row;
14728
14729 fn len(&self) -> usize;
14730
14731 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14732}
14733
14734impl RowRangeExt for Range<MultiBufferRow> {
14735 type Row = MultiBufferRow;
14736
14737 fn len(&self) -> usize {
14738 (self.end.0 - self.start.0) as usize
14739 }
14740
14741 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14742 (self.start.0..self.end.0).map(MultiBufferRow)
14743 }
14744}
14745
14746impl RowRangeExt for Range<DisplayRow> {
14747 type Row = DisplayRow;
14748
14749 fn len(&self) -> usize {
14750 (self.end.0 - self.start.0) as usize
14751 }
14752
14753 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14754 (self.start.0..self.end.0).map(DisplayRow)
14755 }
14756}
14757
14758fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14759 if hunk.diff_base_byte_range.is_empty() {
14760 DiffHunkStatus::Added
14761 } else if hunk.row_range.is_empty() {
14762 DiffHunkStatus::Removed
14763 } else {
14764 DiffHunkStatus::Modified
14765 }
14766}
14767
14768/// If select range has more than one line, we
14769/// just point the cursor to range.start.
14770fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14771 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14772 range
14773 } else {
14774 range.start..range.start
14775 }
14776}
14777
14778pub struct KillRing(ClipboardItem);
14779impl Global for KillRing {}
14780
14781const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);