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 CompletionEntry, CompletionsMenu, ContextMenuOrigin,
77};
78use git::blame::GitBlame;
79use gpui::{
80 div, impl_actions, point, prelude::*, px, relative, size, Action, AnyElement, AppContext,
81 AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context,
82 DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent, FocusableView, FontId,
83 FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Model, ModelContext,
84 MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText,
85 Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
86 UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
87 WeakView, WindowContext,
88};
89use highlight_matching_bracket::refresh_matching_bracket_highlights;
90use hover_popover::{hide_hover, HoverState};
91pub(crate) use hunk_diff::HoveredHunk;
92use hunk_diff::{diff_hunk_to_display, DiffMap, DiffMapSnapshot};
93use indent_guides::ActiveIndentGuidesState;
94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
95pub use inline_completion::Direction;
96use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
97pub use items::MAX_TAB_TITLE_LEN;
98use itertools::Itertools;
99use language::{
100 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
101 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
102 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
103 Point, Selection, SelectionGoal, TransactionId,
104};
105use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
106use linked_editing_ranges::refresh_linked_ranges;
107use mouse_context_menu::MouseContextMenu;
108pub use proposed_changes_editor::{
109 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
110};
111use similar::{ChangeTag, TextDiff};
112use std::iter::Peekable;
113use task::{ResolvedTask, TaskTemplate, TaskVariables};
114
115use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
116pub use lsp::CompletionContext;
117use lsp::{
118 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
119 LanguageServerId, LanguageServerName,
120};
121
122use movement::TextLayoutDetails;
123pub use multi_buffer::{
124 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
125 ToPoint,
126};
127use multi_buffer::{
128 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
129};
130use project::{
131 lsp_store::{FormatTarget, FormatTrigger, OpenLspBufferHandle},
132 project_settings::{GitGutterSetting, ProjectSettings},
133 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
134 LspStore, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
135};
136use rand::prelude::*;
137use rpc::{proto::*, ErrorExt};
138use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
139use selections_collection::{
140 resolve_selections, MutableSelectionsCollection, SelectionsCollection,
141};
142use serde::{Deserialize, Serialize};
143use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
144use smallvec::SmallVec;
145use snippet::Snippet;
146use std::{
147 any::TypeId,
148 borrow::Cow,
149 cell::RefCell,
150 cmp::{self, Ordering, Reverse},
151 mem,
152 num::NonZeroU32,
153 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
154 path::{Path, PathBuf},
155 rc::Rc,
156 sync::Arc,
157 time::{Duration, Instant},
158};
159pub use sum_tree::Bias;
160use sum_tree::TreeMap;
161use text::{BufferId, OffsetUtf16, Rope};
162use theme::{
163 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
164 ThemeColors, ThemeSettings,
165};
166use ui::{
167 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
168 PopoverMenuHandle, Tooltip,
169};
170use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
171use workspace::item::{ItemHandle, PreviewTabsSettings};
172use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
173use workspace::{
174 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
175};
176use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
177
178use crate::hover_links::{find_url, find_url_from_range};
179use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
180
181pub const FILE_HEADER_HEIGHT: u32 = 2;
182pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
183pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
184pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
185const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
186const MAX_LINE_LEN: usize = 1024;
187const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
188const MAX_SELECTION_HISTORY_LEN: usize = 1024;
189pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
190#[doc(hidden)]
191pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
192
193pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
194pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
195
196pub fn render_parsed_markdown(
197 element_id: impl Into<ElementId>,
198 parsed: &language::ParsedMarkdown,
199 editor_style: &EditorStyle,
200 workspace: Option<WeakView<Workspace>>,
201 cx: &mut WindowContext,
202) -> InteractiveText {
203 let code_span_background_color = cx
204 .theme()
205 .colors()
206 .editor_document_highlight_read_background;
207
208 let highlights = gpui::combine_highlights(
209 parsed.highlights.iter().filter_map(|(range, highlight)| {
210 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
211 Some((range.clone(), highlight))
212 }),
213 parsed
214 .regions
215 .iter()
216 .zip(&parsed.region_ranges)
217 .filter_map(|(region, range)| {
218 if region.code {
219 Some((
220 range.clone(),
221 HighlightStyle {
222 background_color: Some(code_span_background_color),
223 ..Default::default()
224 },
225 ))
226 } else {
227 None
228 }
229 }),
230 );
231
232 let mut links = Vec::new();
233 let mut link_ranges = Vec::new();
234 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
235 if let Some(link) = region.link.clone() {
236 links.push(link);
237 link_ranges.push(range.clone());
238 }
239 }
240
241 InteractiveText::new(
242 element_id,
243 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
244 )
245 .on_click(link_ranges, move |clicked_range_ix, cx| {
246 match &links[clicked_range_ix] {
247 markdown::Link::Web { url } => cx.open_url(url),
248 markdown::Link::Path { path } => {
249 if let Some(workspace) = &workspace {
250 _ = workspace.update(cx, |workspace, cx| {
251 workspace.open_abs_path(path.clone(), false, cx).detach();
252 });
253 }
254 }
255 }
256 })
257}
258
259#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
260pub(crate) enum InlayId {
261 InlineCompletion(usize),
262 Hint(usize),
263}
264
265impl InlayId {
266 fn id(&self) -> usize {
267 match self {
268 Self::InlineCompletion(id) => *id,
269 Self::Hint(id) => *id,
270 }
271 }
272}
273
274enum DiffRowHighlight {}
275enum DocumentHighlightRead {}
276enum DocumentHighlightWrite {}
277enum InputComposition {}
278
279#[derive(Debug, Copy, Clone, PartialEq, Eq)]
280pub enum Navigated {
281 Yes,
282 No,
283}
284
285impl Navigated {
286 pub fn from_bool(yes: bool) -> Navigated {
287 if yes {
288 Navigated::Yes
289 } else {
290 Navigated::No
291 }
292 }
293}
294
295pub fn init_settings(cx: &mut AppContext) {
296 EditorSettings::register(cx);
297}
298
299pub fn init(cx: &mut AppContext) {
300 init_settings(cx);
301
302 workspace::register_project_item::<Editor>(cx);
303 workspace::FollowableViewRegistry::register::<Editor>(cx);
304 workspace::register_serializable_item::<Editor>(cx);
305
306 cx.observe_new_views(
307 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
308 workspace.register_action(Editor::new_file);
309 workspace.register_action(Editor::new_file_vertical);
310 workspace.register_action(Editor::new_file_horizontal);
311 },
312 )
313 .detach();
314
315 cx.on_action(move |_: &workspace::NewFile, cx| {
316 let app_state = workspace::AppState::global(cx);
317 if let Some(app_state) = app_state.upgrade() {
318 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
319 Editor::new_file(workspace, &Default::default(), cx)
320 })
321 .detach();
322 }
323 });
324 cx.on_action(move |_: &workspace::NewWindow, cx| {
325 let app_state = workspace::AppState::global(cx);
326 if let Some(app_state) = app_state.upgrade() {
327 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
328 Editor::new_file(workspace, &Default::default(), cx)
329 })
330 .detach();
331 }
332 });
333 git::project_diff::init(cx);
334}
335
336pub struct SearchWithinRange;
337
338trait InvalidationRegion {
339 fn ranges(&self) -> &[Range<Anchor>];
340}
341
342#[derive(Clone, Debug, PartialEq)]
343pub enum SelectPhase {
344 Begin {
345 position: DisplayPoint,
346 add: bool,
347 click_count: usize,
348 },
349 BeginColumnar {
350 position: DisplayPoint,
351 reset: bool,
352 goal_column: u32,
353 },
354 Extend {
355 position: DisplayPoint,
356 click_count: usize,
357 },
358 Update {
359 position: DisplayPoint,
360 goal_column: u32,
361 scroll_delta: gpui::Point<f32>,
362 },
363 End,
364}
365
366#[derive(Clone, Debug)]
367pub enum SelectMode {
368 Character,
369 Word(Range<Anchor>),
370 Line(Range<Anchor>),
371 All,
372}
373
374#[derive(Copy, Clone, PartialEq, Eq, Debug)]
375pub enum EditorMode {
376 SingleLine { auto_width: bool },
377 AutoHeight { max_lines: usize },
378 Full,
379}
380
381#[derive(Copy, Clone, Debug)]
382pub enum SoftWrap {
383 /// Prefer not to wrap at all.
384 ///
385 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
386 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
387 GitDiff,
388 /// Prefer a single line generally, unless an overly long line is encountered.
389 None,
390 /// Soft wrap lines that exceed the editor width.
391 EditorWidth,
392 /// Soft wrap lines at the preferred line length.
393 Column(u32),
394 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
395 Bounded(u32),
396}
397
398#[derive(Clone)]
399pub struct EditorStyle {
400 pub background: Hsla,
401 pub local_player: PlayerColor,
402 pub text: TextStyle,
403 pub scrollbar_width: Pixels,
404 pub syntax: Arc<SyntaxTheme>,
405 pub status: StatusColors,
406 pub inlay_hints_style: HighlightStyle,
407 pub inline_completion_styles: InlineCompletionStyles,
408 pub unnecessary_code_fade: f32,
409}
410
411impl Default for EditorStyle {
412 fn default() -> Self {
413 Self {
414 background: Hsla::default(),
415 local_player: PlayerColor::default(),
416 text: TextStyle::default(),
417 scrollbar_width: Pixels::default(),
418 syntax: Default::default(),
419 // HACK: Status colors don't have a real default.
420 // We should look into removing the status colors from the editor
421 // style and retrieve them directly from the theme.
422 status: StatusColors::dark(),
423 inlay_hints_style: HighlightStyle::default(),
424 inline_completion_styles: InlineCompletionStyles {
425 insertion: HighlightStyle::default(),
426 whitespace: HighlightStyle::default(),
427 },
428 unnecessary_code_fade: Default::default(),
429 }
430 }
431}
432
433pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
434 let show_background = language_settings::language_settings(None, None, cx)
435 .inlay_hints
436 .show_background;
437
438 HighlightStyle {
439 color: Some(cx.theme().status().hint),
440 background_color: show_background.then(|| cx.theme().status().hint_background),
441 ..HighlightStyle::default()
442 }
443}
444
445pub fn make_suggestion_styles(cx: &WindowContext) -> InlineCompletionStyles {
446 InlineCompletionStyles {
447 insertion: HighlightStyle {
448 color: Some(cx.theme().status().predictive),
449 ..HighlightStyle::default()
450 },
451 whitespace: HighlightStyle {
452 background_color: Some(cx.theme().status().created_background),
453 ..HighlightStyle::default()
454 },
455 }
456}
457
458type CompletionId = usize;
459
460#[derive(Debug, Clone)]
461struct InlineCompletionMenuHint {
462 provider_name: &'static str,
463 text: InlineCompletionText,
464}
465
466#[derive(Clone, Debug)]
467enum InlineCompletionText {
468 Move(SharedString),
469 Edit {
470 text: SharedString,
471 highlights: Vec<(Range<usize>, HighlightStyle)>,
472 },
473}
474
475enum InlineCompletion {
476 Edit(Vec<(Range<Anchor>, String)>),
477 Move(Anchor),
478}
479
480struct InlineCompletionState {
481 inlay_ids: Vec<InlayId>,
482 completion: InlineCompletion,
483 invalidation_range: Range<Anchor>,
484}
485
486enum InlineCompletionHighlight {}
487
488#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
489struct EditorActionId(usize);
490
491impl EditorActionId {
492 pub fn post_inc(&mut self) -> Self {
493 let answer = self.0;
494
495 *self = Self(answer + 1);
496
497 Self(answer)
498 }
499}
500
501// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
502// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
503
504type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
505type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
506
507#[derive(Default)]
508struct ScrollbarMarkerState {
509 scrollbar_size: Size<Pixels>,
510 dirty: bool,
511 markers: Arc<[PaintQuad]>,
512 pending_refresh: Option<Task<Result<()>>>,
513}
514
515impl ScrollbarMarkerState {
516 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
517 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
518 }
519}
520
521#[derive(Clone, Debug)]
522struct RunnableTasks {
523 templates: Vec<(TaskSourceKind, TaskTemplate)>,
524 offset: MultiBufferOffset,
525 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
526 column: u32,
527 // Values of all named captures, including those starting with '_'
528 extra_variables: HashMap<String, String>,
529 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
530 context_range: Range<BufferOffset>,
531}
532
533impl RunnableTasks {
534 fn resolve<'a>(
535 &'a self,
536 cx: &'a task::TaskContext,
537 ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
538 self.templates.iter().filter_map(|(kind, template)| {
539 template
540 .resolve_task(&kind.to_id_base(), cx)
541 .map(|task| (kind.clone(), task))
542 })
543 }
544}
545
546#[derive(Clone)]
547struct ResolvedTasks {
548 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
549 position: Anchor,
550}
551#[derive(Copy, Clone, Debug)]
552struct MultiBufferOffset(usize);
553#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
554struct BufferOffset(usize);
555
556// Addons allow storing per-editor state in other crates (e.g. Vim)
557pub trait Addon: 'static {
558 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
559
560 fn to_any(&self) -> &dyn std::any::Any;
561}
562
563#[derive(Debug, Copy, Clone, PartialEq, Eq)]
564pub enum IsVimMode {
565 Yes,
566 No,
567}
568
569/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
570///
571/// See the [module level documentation](self) for more information.
572pub struct Editor {
573 focus_handle: FocusHandle,
574 last_focused_descendant: Option<WeakFocusHandle>,
575 /// The text buffer being edited
576 buffer: Model<MultiBuffer>,
577 /// Map of how text in the buffer should be displayed.
578 /// Handles soft wraps, folds, fake inlay text insertions, etc.
579 pub display_map: Model<DisplayMap>,
580 pub selections: SelectionsCollection,
581 pub scroll_manager: ScrollManager,
582 /// When inline assist editors are linked, they all render cursors because
583 /// typing enters text into each of them, even the ones that aren't focused.
584 pub(crate) show_cursor_when_unfocused: bool,
585 columnar_selection_tail: Option<Anchor>,
586 add_selections_state: Option<AddSelectionsState>,
587 select_next_state: Option<SelectNextState>,
588 select_prev_state: Option<SelectNextState>,
589 selection_history: SelectionHistory,
590 autoclose_regions: Vec<AutocloseRegion>,
591 snippet_stack: InvalidationStack<SnippetState>,
592 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
593 ime_transaction: Option<TransactionId>,
594 active_diagnostics: Option<ActiveDiagnosticGroup>,
595 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
596
597 project: Option<Model<Project>>,
598 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
599 completion_provider: Option<Box<dyn CompletionProvider>>,
600 collaboration_hub: Option<Box<dyn CollaborationHub>>,
601 blink_manager: Model<BlinkManager>,
602 show_cursor_names: bool,
603 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
604 pub show_local_selections: bool,
605 mode: EditorMode,
606 show_breadcrumbs: bool,
607 show_gutter: bool,
608 show_line_numbers: Option<bool>,
609 use_relative_line_numbers: Option<bool>,
610 show_git_diff_gutter: Option<bool>,
611 show_code_actions: Option<bool>,
612 show_runnables: Option<bool>,
613 show_wrap_guides: Option<bool>,
614 show_indent_guides: Option<bool>,
615 placeholder_text: Option<Arc<str>>,
616 highlight_order: usize,
617 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
618 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
619 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
620 scrollbar_marker_state: ScrollbarMarkerState,
621 active_indent_guides_state: ActiveIndentGuidesState,
622 nav_history: Option<ItemNavHistory>,
623 context_menu: RefCell<Option<CodeContextMenu>>,
624 mouse_context_menu: Option<MouseContextMenu>,
625 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
626 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
627 signature_help_state: SignatureHelpState,
628 auto_signature_help: Option<bool>,
629 find_all_references_task_sources: Vec<Anchor>,
630 next_completion_id: CompletionId,
631 available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
632 code_actions_task: Option<Task<Result<()>>>,
633 document_highlights_task: Option<Task<()>>,
634 linked_editing_range_task: Option<Task<Option<()>>>,
635 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
636 pending_rename: Option<RenameState>,
637 searchable: bool,
638 cursor_shape: CursorShape,
639 current_line_highlight: Option<CurrentLineHighlight>,
640 collapse_matches: bool,
641 autoindent_mode: Option<AutoindentMode>,
642 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
643 input_enabled: bool,
644 use_modal_editing: bool,
645 read_only: bool,
646 leader_peer_id: Option<PeerId>,
647 remote_id: Option<ViewId>,
648 hover_state: HoverState,
649 gutter_hovered: bool,
650 hovered_link_state: Option<HoveredLinkState>,
651 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
652 code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
653 active_inline_completion: Option<InlineCompletionState>,
654 // enable_inline_completions is a switch that Vim can use to disable
655 // inline completions based on its mode.
656 enable_inline_completions: bool,
657 show_inline_completions_override: Option<bool>,
658 inlay_hint_cache: InlayHintCache,
659 diff_map: DiffMap,
660 next_inlay_id: usize,
661 _subscriptions: Vec<Subscription>,
662 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
663 gutter_dimensions: GutterDimensions,
664 style: Option<EditorStyle>,
665 text_style_refinement: Option<TextStyleRefinement>,
666 next_editor_action_id: EditorActionId,
667 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
668 use_autoclose: bool,
669 use_auto_surround: bool,
670 auto_replace_emoji_shortcode: bool,
671 show_git_blame_gutter: bool,
672 show_git_blame_inline: bool,
673 show_git_blame_inline_delay_task: Option<Task<()>>,
674 git_blame_inline_enabled: bool,
675 serialize_dirty_buffers: bool,
676 show_selection_menu: Option<bool>,
677 blame: Option<Model<GitBlame>>,
678 blame_subscription: Option<Subscription>,
679 custom_context_menu: Option<
680 Box<
681 dyn 'static
682 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
683 >,
684 >,
685 last_bounds: Option<Bounds<Pixels>>,
686 expect_bounds_change: Option<Bounds<Pixels>>,
687 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
688 tasks_update_task: Option<Task<()>>,
689 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
690 breadcrumb_header: Option<String>,
691 focused_block: Option<FocusedBlock>,
692 next_scroll_position: NextScrollCursorCenterTopBottom,
693 addons: HashMap<TypeId, Box<dyn Addon>>,
694 registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
695 toggle_fold_multiple_buffers: Task<()>,
696 _scroll_cursor_center_top_bottom_task: Task<()>,
697}
698
699#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
700enum NextScrollCursorCenterTopBottom {
701 #[default]
702 Center,
703 Top,
704 Bottom,
705}
706
707impl NextScrollCursorCenterTopBottom {
708 fn next(&self) -> Self {
709 match self {
710 Self::Center => Self::Top,
711 Self::Top => Self::Bottom,
712 Self::Bottom => Self::Center,
713 }
714 }
715}
716
717#[derive(Clone)]
718pub struct EditorSnapshot {
719 pub mode: EditorMode,
720 show_gutter: bool,
721 show_line_numbers: Option<bool>,
722 show_git_diff_gutter: Option<bool>,
723 show_code_actions: Option<bool>,
724 show_runnables: Option<bool>,
725 git_blame_gutter_max_author_length: Option<usize>,
726 pub display_snapshot: DisplaySnapshot,
727 pub placeholder_text: Option<Arc<str>>,
728 diff_map: DiffMapSnapshot,
729 is_focused: bool,
730 scroll_anchor: ScrollAnchor,
731 ongoing_scroll: OngoingScroll,
732 current_line_highlight: CurrentLineHighlight,
733 gutter_hovered: bool,
734}
735
736const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
737
738#[derive(Default, Debug, Clone, Copy)]
739pub struct GutterDimensions {
740 pub left_padding: Pixels,
741 pub right_padding: Pixels,
742 pub width: Pixels,
743 pub margin: Pixels,
744 pub git_blame_entries_width: Option<Pixels>,
745}
746
747impl GutterDimensions {
748 /// The full width of the space taken up by the gutter.
749 pub fn full_width(&self) -> Pixels {
750 self.margin + self.width
751 }
752
753 /// The width of the space reserved for the fold indicators,
754 /// use alongside 'justify_end' and `gutter_width` to
755 /// right align content with the line numbers
756 pub fn fold_area_width(&self) -> Pixels {
757 self.margin + self.right_padding
758 }
759}
760
761#[derive(Debug)]
762pub struct RemoteSelection {
763 pub replica_id: ReplicaId,
764 pub selection: Selection<Anchor>,
765 pub cursor_shape: CursorShape,
766 pub peer_id: PeerId,
767 pub line_mode: bool,
768 pub participant_index: Option<ParticipantIndex>,
769 pub user_name: Option<SharedString>,
770}
771
772#[derive(Clone, Debug)]
773struct SelectionHistoryEntry {
774 selections: Arc<[Selection<Anchor>]>,
775 select_next_state: Option<SelectNextState>,
776 select_prev_state: Option<SelectNextState>,
777 add_selections_state: Option<AddSelectionsState>,
778}
779
780enum SelectionHistoryMode {
781 Normal,
782 Undoing,
783 Redoing,
784}
785
786#[derive(Clone, PartialEq, Eq, Hash)]
787struct HoveredCursor {
788 replica_id: u16,
789 selection_id: usize,
790}
791
792impl Default for SelectionHistoryMode {
793 fn default() -> Self {
794 Self::Normal
795 }
796}
797
798#[derive(Default)]
799struct SelectionHistory {
800 #[allow(clippy::type_complexity)]
801 selections_by_transaction:
802 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
803 mode: SelectionHistoryMode,
804 undo_stack: VecDeque<SelectionHistoryEntry>,
805 redo_stack: VecDeque<SelectionHistoryEntry>,
806}
807
808impl SelectionHistory {
809 fn insert_transaction(
810 &mut self,
811 transaction_id: TransactionId,
812 selections: Arc<[Selection<Anchor>]>,
813 ) {
814 self.selections_by_transaction
815 .insert(transaction_id, (selections, None));
816 }
817
818 #[allow(clippy::type_complexity)]
819 fn transaction(
820 &self,
821 transaction_id: TransactionId,
822 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
823 self.selections_by_transaction.get(&transaction_id)
824 }
825
826 #[allow(clippy::type_complexity)]
827 fn transaction_mut(
828 &mut self,
829 transaction_id: TransactionId,
830 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
831 self.selections_by_transaction.get_mut(&transaction_id)
832 }
833
834 fn push(&mut self, entry: SelectionHistoryEntry) {
835 if !entry.selections.is_empty() {
836 match self.mode {
837 SelectionHistoryMode::Normal => {
838 self.push_undo(entry);
839 self.redo_stack.clear();
840 }
841 SelectionHistoryMode::Undoing => self.push_redo(entry),
842 SelectionHistoryMode::Redoing => self.push_undo(entry),
843 }
844 }
845 }
846
847 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
848 if self
849 .undo_stack
850 .back()
851 .map_or(true, |e| e.selections != entry.selections)
852 {
853 self.undo_stack.push_back(entry);
854 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
855 self.undo_stack.pop_front();
856 }
857 }
858 }
859
860 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
861 if self
862 .redo_stack
863 .back()
864 .map_or(true, |e| e.selections != entry.selections)
865 {
866 self.redo_stack.push_back(entry);
867 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
868 self.redo_stack.pop_front();
869 }
870 }
871 }
872}
873
874struct RowHighlight {
875 index: usize,
876 range: Range<Anchor>,
877 color: Hsla,
878 should_autoscroll: bool,
879}
880
881#[derive(Clone, Debug)]
882struct AddSelectionsState {
883 above: bool,
884 stack: Vec<usize>,
885}
886
887#[derive(Clone)]
888struct SelectNextState {
889 query: AhoCorasick,
890 wordwise: bool,
891 done: bool,
892}
893
894impl std::fmt::Debug for SelectNextState {
895 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
896 f.debug_struct(std::any::type_name::<Self>())
897 .field("wordwise", &self.wordwise)
898 .field("done", &self.done)
899 .finish()
900 }
901}
902
903#[derive(Debug)]
904struct AutocloseRegion {
905 selection_id: usize,
906 range: Range<Anchor>,
907 pair: BracketPair,
908}
909
910#[derive(Debug)]
911struct SnippetState {
912 ranges: Vec<Vec<Range<Anchor>>>,
913 active_index: usize,
914 choices: Vec<Option<Vec<String>>>,
915}
916
917#[doc(hidden)]
918pub struct RenameState {
919 pub range: Range<Anchor>,
920 pub old_name: Arc<str>,
921 pub editor: View<Editor>,
922 block_id: CustomBlockId,
923}
924
925struct InvalidationStack<T>(Vec<T>);
926
927struct RegisteredInlineCompletionProvider {
928 provider: Arc<dyn InlineCompletionProviderHandle>,
929 _subscription: Subscription,
930}
931
932#[derive(Debug)]
933struct ActiveDiagnosticGroup {
934 primary_range: Range<Anchor>,
935 primary_message: String,
936 group_id: usize,
937 blocks: HashMap<CustomBlockId, Diagnostic>,
938 is_valid: bool,
939}
940
941#[derive(Serialize, Deserialize, Clone, Debug)]
942pub struct ClipboardSelection {
943 pub len: usize,
944 pub is_entire_line: bool,
945 pub first_line_indent: u32,
946}
947
948#[derive(Debug)]
949pub(crate) struct NavigationData {
950 cursor_anchor: Anchor,
951 cursor_position: Point,
952 scroll_anchor: ScrollAnchor,
953 scroll_top_row: u32,
954}
955
956#[derive(Debug, Clone, Copy, PartialEq, Eq)]
957pub enum GotoDefinitionKind {
958 Symbol,
959 Declaration,
960 Type,
961 Implementation,
962}
963
964#[derive(Debug, Clone)]
965enum InlayHintRefreshReason {
966 Toggle(bool),
967 SettingsChange(InlayHintSettings),
968 NewLinesShown,
969 BufferEdited(HashSet<Arc<Language>>),
970 RefreshRequested,
971 ExcerptsRemoved(Vec<ExcerptId>),
972}
973
974impl InlayHintRefreshReason {
975 fn description(&self) -> &'static str {
976 match self {
977 Self::Toggle(_) => "toggle",
978 Self::SettingsChange(_) => "settings change",
979 Self::NewLinesShown => "new lines shown",
980 Self::BufferEdited(_) => "buffer edited",
981 Self::RefreshRequested => "refresh requested",
982 Self::ExcerptsRemoved(_) => "excerpts removed",
983 }
984 }
985}
986
987pub(crate) struct FocusedBlock {
988 id: BlockId,
989 focus_handle: WeakFocusHandle,
990}
991
992#[derive(Clone)]
993struct JumpData {
994 excerpt_id: ExcerptId,
995 position: Point,
996 anchor: text::Anchor,
997 path: Option<project::ProjectPath>,
998 line_offset_from_top: u32,
999}
1000
1001impl Editor {
1002 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1003 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1004 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1005 Self::new(
1006 EditorMode::SingleLine { auto_width: false },
1007 buffer,
1008 None,
1009 false,
1010 cx,
1011 )
1012 }
1013
1014 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1015 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1016 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1017 Self::new(EditorMode::Full, buffer, None, false, cx)
1018 }
1019
1020 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1021 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1022 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1023 Self::new(
1024 EditorMode::SingleLine { auto_width: true },
1025 buffer,
1026 None,
1027 false,
1028 cx,
1029 )
1030 }
1031
1032 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1033 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1034 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1035 Self::new(
1036 EditorMode::AutoHeight { max_lines },
1037 buffer,
1038 None,
1039 false,
1040 cx,
1041 )
1042 }
1043
1044 pub fn for_buffer(
1045 buffer: Model<Buffer>,
1046 project: Option<Model<Project>>,
1047 cx: &mut ViewContext<Self>,
1048 ) -> Self {
1049 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1050 Self::new(EditorMode::Full, buffer, project, false, cx)
1051 }
1052
1053 pub fn for_multibuffer(
1054 buffer: Model<MultiBuffer>,
1055 project: Option<Model<Project>>,
1056 show_excerpt_controls: bool,
1057 cx: &mut ViewContext<Self>,
1058 ) -> Self {
1059 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1060 }
1061
1062 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1063 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1064 let mut clone = Self::new(
1065 self.mode,
1066 self.buffer.clone(),
1067 self.project.clone(),
1068 show_excerpt_controls,
1069 cx,
1070 );
1071 self.display_map.update(cx, |display_map, cx| {
1072 let snapshot = display_map.snapshot(cx);
1073 clone.display_map.update(cx, |display_map, cx| {
1074 display_map.set_state(&snapshot, cx);
1075 });
1076 });
1077 clone.selections.clone_state(&self.selections);
1078 clone.scroll_manager.clone_state(&self.scroll_manager);
1079 clone.searchable = self.searchable;
1080 clone
1081 }
1082
1083 pub fn new(
1084 mode: EditorMode,
1085 buffer: Model<MultiBuffer>,
1086 project: Option<Model<Project>>,
1087 show_excerpt_controls: bool,
1088 cx: &mut ViewContext<Self>,
1089 ) -> Self {
1090 let style = cx.text_style();
1091 let font_size = style.font_size.to_pixels(cx.rem_size());
1092 let editor = cx.view().downgrade();
1093 let fold_placeholder = FoldPlaceholder {
1094 constrain_width: true,
1095 render: Arc::new(move |fold_id, fold_range, cx| {
1096 let editor = editor.clone();
1097 div()
1098 .id(fold_id)
1099 .bg(cx.theme().colors().ghost_element_background)
1100 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1101 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1102 .rounded_sm()
1103 .size_full()
1104 .cursor_pointer()
1105 .child("⋯")
1106 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1107 .on_click(move |_, cx| {
1108 editor
1109 .update(cx, |editor, cx| {
1110 editor.unfold_ranges(
1111 &[fold_range.start..fold_range.end],
1112 true,
1113 false,
1114 cx,
1115 );
1116 cx.stop_propagation();
1117 })
1118 .ok();
1119 })
1120 .into_any()
1121 }),
1122 merge_adjacent: true,
1123 ..Default::default()
1124 };
1125 let display_map = cx.new_model(|cx| {
1126 DisplayMap::new(
1127 buffer.clone(),
1128 style.font(),
1129 font_size,
1130 None,
1131 show_excerpt_controls,
1132 FILE_HEADER_HEIGHT,
1133 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1134 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1135 fold_placeholder,
1136 cx,
1137 )
1138 });
1139
1140 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1141
1142 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1143
1144 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1145 .then(|| language_settings::SoftWrap::None);
1146
1147 let mut project_subscriptions = Vec::new();
1148 if mode == EditorMode::Full {
1149 if let Some(project) = project.as_ref() {
1150 if buffer.read(cx).is_singleton() {
1151 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1152 cx.emit(EditorEvent::TitleChanged);
1153 }));
1154 }
1155 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1156 if let project::Event::RefreshInlayHints = event {
1157 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1158 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1159 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1160 let focus_handle = editor.focus_handle(cx);
1161 if focus_handle.is_focused(cx) {
1162 let snapshot = buffer.read(cx).snapshot();
1163 for (range, snippet) in snippet_edits {
1164 let editor_range =
1165 language::range_from_lsp(*range).to_offset(&snapshot);
1166 editor
1167 .insert_snippet(&[editor_range], snippet.clone(), cx)
1168 .ok();
1169 }
1170 }
1171 }
1172 }
1173 }));
1174 if let Some(task_inventory) = project
1175 .read(cx)
1176 .task_store()
1177 .read(cx)
1178 .task_inventory()
1179 .cloned()
1180 {
1181 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1182 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1183 }));
1184 }
1185 }
1186 }
1187
1188 let buffer_snapshot = buffer.read(cx).snapshot(cx);
1189
1190 let inlay_hint_settings =
1191 inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
1192 let focus_handle = cx.focus_handle();
1193 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1194 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1195 .detach();
1196 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1197 .detach();
1198 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1199
1200 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1201 Some(false)
1202 } else {
1203 None
1204 };
1205
1206 let mut code_action_providers = Vec::new();
1207 if let Some(project) = project.clone() {
1208 get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
1209 code_action_providers.push(Rc::new(project) as Rc<_>);
1210 }
1211
1212 let mut this = Self {
1213 focus_handle,
1214 show_cursor_when_unfocused: false,
1215 last_focused_descendant: None,
1216 buffer: buffer.clone(),
1217 display_map: display_map.clone(),
1218 selections,
1219 scroll_manager: ScrollManager::new(cx),
1220 columnar_selection_tail: None,
1221 add_selections_state: None,
1222 select_next_state: None,
1223 select_prev_state: None,
1224 selection_history: Default::default(),
1225 autoclose_regions: Default::default(),
1226 snippet_stack: Default::default(),
1227 select_larger_syntax_node_stack: Vec::new(),
1228 ime_transaction: Default::default(),
1229 active_diagnostics: None,
1230 soft_wrap_mode_override,
1231 completion_provider: project.clone().map(|project| Box::new(project) as _),
1232 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1233 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1234 project,
1235 blink_manager: blink_manager.clone(),
1236 show_local_selections: true,
1237 mode,
1238 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1239 show_gutter: mode == EditorMode::Full,
1240 show_line_numbers: None,
1241 use_relative_line_numbers: None,
1242 show_git_diff_gutter: None,
1243 show_code_actions: None,
1244 show_runnables: None,
1245 show_wrap_guides: None,
1246 show_indent_guides,
1247 placeholder_text: None,
1248 highlight_order: 0,
1249 highlighted_rows: HashMap::default(),
1250 background_highlights: Default::default(),
1251 gutter_highlights: TreeMap::default(),
1252 scrollbar_marker_state: ScrollbarMarkerState::default(),
1253 active_indent_guides_state: ActiveIndentGuidesState::default(),
1254 nav_history: None,
1255 context_menu: RefCell::new(None),
1256 mouse_context_menu: None,
1257 hunk_controls_menu_handle: PopoverMenuHandle::default(),
1258 completion_tasks: Default::default(),
1259 signature_help_state: SignatureHelpState::default(),
1260 auto_signature_help: None,
1261 find_all_references_task_sources: Vec::new(),
1262 next_completion_id: 0,
1263 next_inlay_id: 0,
1264 code_action_providers,
1265 available_code_actions: Default::default(),
1266 code_actions_task: Default::default(),
1267 document_highlights_task: Default::default(),
1268 linked_editing_range_task: Default::default(),
1269 pending_rename: Default::default(),
1270 searchable: true,
1271 cursor_shape: EditorSettings::get_global(cx)
1272 .cursor_shape
1273 .unwrap_or_default(),
1274 current_line_highlight: None,
1275 autoindent_mode: Some(AutoindentMode::EachLine),
1276 collapse_matches: false,
1277 workspace: None,
1278 input_enabled: true,
1279 use_modal_editing: mode == EditorMode::Full,
1280 read_only: false,
1281 use_autoclose: true,
1282 use_auto_surround: true,
1283 auto_replace_emoji_shortcode: false,
1284 leader_peer_id: None,
1285 remote_id: None,
1286 hover_state: Default::default(),
1287 hovered_link_state: Default::default(),
1288 inline_completion_provider: None,
1289 active_inline_completion: None,
1290 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1291 diff_map: DiffMap::default(),
1292 gutter_hovered: false,
1293 pixel_position_of_newest_cursor: None,
1294 last_bounds: None,
1295 expect_bounds_change: None,
1296 gutter_dimensions: GutterDimensions::default(),
1297 style: None,
1298 show_cursor_names: false,
1299 hovered_cursors: Default::default(),
1300 next_editor_action_id: EditorActionId::default(),
1301 editor_actions: Rc::default(),
1302 show_inline_completions_override: None,
1303 enable_inline_completions: true,
1304 custom_context_menu: None,
1305 show_git_blame_gutter: false,
1306 show_git_blame_inline: false,
1307 show_selection_menu: None,
1308 show_git_blame_inline_delay_task: None,
1309 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1310 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1311 .session
1312 .restore_unsaved_buffers,
1313 blame: None,
1314 blame_subscription: None,
1315 tasks: Default::default(),
1316 _subscriptions: vec![
1317 cx.observe(&buffer, Self::on_buffer_changed),
1318 cx.subscribe(&buffer, Self::on_buffer_event),
1319 cx.observe(&display_map, Self::on_display_map_changed),
1320 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1321 cx.observe_global::<SettingsStore>(Self::settings_changed),
1322 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1323 cx.observe_window_activation(|editor, cx| {
1324 let active = cx.is_window_active();
1325 editor.blink_manager.update(cx, |blink_manager, cx| {
1326 if active {
1327 blink_manager.enable(cx);
1328 } else {
1329 blink_manager.disable(cx);
1330 }
1331 });
1332 }),
1333 ],
1334 tasks_update_task: None,
1335 linked_edit_ranges: Default::default(),
1336 previous_search_ranges: None,
1337 breadcrumb_header: None,
1338 focused_block: None,
1339 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1340 addons: HashMap::default(),
1341 registered_buffers: HashMap::default(),
1342 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1343 toggle_fold_multiple_buffers: Task::ready(()),
1344 text_style_refinement: None,
1345 };
1346 this.tasks_update_task = Some(this.refresh_runnables(cx));
1347 this._subscriptions.extend(project_subscriptions);
1348
1349 this.end_selection(cx);
1350 this.scroll_manager.show_scrollbar(cx);
1351
1352 if mode == EditorMode::Full {
1353 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1354 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1355
1356 if this.git_blame_inline_enabled {
1357 this.git_blame_inline_enabled = true;
1358 this.start_git_blame_inline(false, cx);
1359 }
1360
1361 if let Some(buffer) = buffer.read(cx).as_singleton() {
1362 if let Some(project) = this.project.as_ref() {
1363 let lsp_store = project.read(cx).lsp_store();
1364 let handle = lsp_store.update(cx, |lsp_store, cx| {
1365 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1366 });
1367 this.registered_buffers
1368 .insert(buffer.read(cx).remote_id(), handle);
1369 }
1370 }
1371 }
1372
1373 this.report_editor_event("Editor Opened", None, cx);
1374 this
1375 }
1376
1377 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
1378 self.mouse_context_menu
1379 .as_ref()
1380 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1381 }
1382
1383 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
1384 let mut key_context = KeyContext::new_with_defaults();
1385 key_context.add("Editor");
1386 let mode = match self.mode {
1387 EditorMode::SingleLine { .. } => "single_line",
1388 EditorMode::AutoHeight { .. } => "auto_height",
1389 EditorMode::Full => "full",
1390 };
1391
1392 if EditorSettings::jupyter_enabled(cx) {
1393 key_context.add("jupyter");
1394 }
1395
1396 key_context.set("mode", mode);
1397 if self.pending_rename.is_some() {
1398 key_context.add("renaming");
1399 }
1400 match self.context_menu.borrow().as_ref() {
1401 Some(CodeContextMenu::Completions(_)) => {
1402 key_context.add("menu");
1403 key_context.add("showing_completions")
1404 }
1405 Some(CodeContextMenu::CodeActions(_)) => {
1406 key_context.add("menu");
1407 key_context.add("showing_code_actions")
1408 }
1409 None => {}
1410 }
1411
1412 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
1413 if !self.focus_handle(cx).contains_focused(cx)
1414 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
1415 {
1416 for addon in self.addons.values() {
1417 addon.extend_key_context(&mut key_context, cx)
1418 }
1419 }
1420
1421 if let Some(extension) = self
1422 .buffer
1423 .read(cx)
1424 .as_singleton()
1425 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1426 {
1427 key_context.set("extension", extension.to_string());
1428 }
1429
1430 if self.has_active_inline_completion() {
1431 key_context.add("copilot_suggestion");
1432 key_context.add("inline_completion");
1433 }
1434
1435 if !self
1436 .selections
1437 .disjoint
1438 .iter()
1439 .all(|selection| selection.start == selection.end)
1440 {
1441 key_context.add("selection");
1442 }
1443
1444 key_context
1445 }
1446
1447 pub fn new_file(
1448 workspace: &mut Workspace,
1449 _: &workspace::NewFile,
1450 cx: &mut ViewContext<Workspace>,
1451 ) {
1452 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
1453 "Failed to create buffer",
1454 cx,
1455 |e, _| match e.error_code() {
1456 ErrorCode::RemoteUpgradeRequired => Some(format!(
1457 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1458 e.error_tag("required").unwrap_or("the latest version")
1459 )),
1460 _ => None,
1461 },
1462 );
1463 }
1464
1465 pub fn new_in_workspace(
1466 workspace: &mut Workspace,
1467 cx: &mut ViewContext<Workspace>,
1468 ) -> Task<Result<View<Editor>>> {
1469 let project = workspace.project().clone();
1470 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1471
1472 cx.spawn(|workspace, mut cx| async move {
1473 let buffer = create.await?;
1474 workspace.update(&mut cx, |workspace, cx| {
1475 let editor =
1476 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
1477 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
1478 editor
1479 })
1480 })
1481 }
1482
1483 fn new_file_vertical(
1484 workspace: &mut Workspace,
1485 _: &workspace::NewFileSplitVertical,
1486 cx: &mut ViewContext<Workspace>,
1487 ) {
1488 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
1489 }
1490
1491 fn new_file_horizontal(
1492 workspace: &mut Workspace,
1493 _: &workspace::NewFileSplitHorizontal,
1494 cx: &mut ViewContext<Workspace>,
1495 ) {
1496 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
1497 }
1498
1499 fn new_file_in_direction(
1500 workspace: &mut Workspace,
1501 direction: SplitDirection,
1502 cx: &mut ViewContext<Workspace>,
1503 ) {
1504 let project = workspace.project().clone();
1505 let create = project.update(cx, |project, cx| project.create_buffer(cx));
1506
1507 cx.spawn(|workspace, mut cx| async move {
1508 let buffer = create.await?;
1509 workspace.update(&mut cx, move |workspace, cx| {
1510 workspace.split_item(
1511 direction,
1512 Box::new(
1513 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
1514 ),
1515 cx,
1516 )
1517 })?;
1518 anyhow::Ok(())
1519 })
1520 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
1521 ErrorCode::RemoteUpgradeRequired => Some(format!(
1522 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
1523 e.error_tag("required").unwrap_or("the latest version")
1524 )),
1525 _ => None,
1526 });
1527 }
1528
1529 pub fn leader_peer_id(&self) -> Option<PeerId> {
1530 self.leader_peer_id
1531 }
1532
1533 pub fn buffer(&self) -> &Model<MultiBuffer> {
1534 &self.buffer
1535 }
1536
1537 pub fn workspace(&self) -> Option<View<Workspace>> {
1538 self.workspace.as_ref()?.0.upgrade()
1539 }
1540
1541 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
1542 self.buffer().read(cx).title(cx)
1543 }
1544
1545 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
1546 let git_blame_gutter_max_author_length = self
1547 .render_git_blame_gutter(cx)
1548 .then(|| {
1549 if let Some(blame) = self.blame.as_ref() {
1550 let max_author_length =
1551 blame.update(cx, |blame, cx| blame.max_author_length(cx));
1552 Some(max_author_length)
1553 } else {
1554 None
1555 }
1556 })
1557 .flatten();
1558
1559 EditorSnapshot {
1560 mode: self.mode,
1561 show_gutter: self.show_gutter,
1562 show_line_numbers: self.show_line_numbers,
1563 show_git_diff_gutter: self.show_git_diff_gutter,
1564 show_code_actions: self.show_code_actions,
1565 show_runnables: self.show_runnables,
1566 git_blame_gutter_max_author_length,
1567 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1568 scroll_anchor: self.scroll_manager.anchor(),
1569 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1570 placeholder_text: self.placeholder_text.clone(),
1571 diff_map: self.diff_map.snapshot(),
1572 is_focused: self.focus_handle.is_focused(cx),
1573 current_line_highlight: self
1574 .current_line_highlight
1575 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
1576 gutter_hovered: self.gutter_hovered,
1577 }
1578 }
1579
1580 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
1581 self.buffer.read(cx).language_at(point, cx)
1582 }
1583
1584 pub fn file_at<T: ToOffset>(
1585 &self,
1586 point: T,
1587 cx: &AppContext,
1588 ) -> Option<Arc<dyn language::File>> {
1589 self.buffer.read(cx).read(cx).file_at(point).cloned()
1590 }
1591
1592 pub fn active_excerpt(
1593 &self,
1594 cx: &AppContext,
1595 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
1596 self.buffer
1597 .read(cx)
1598 .excerpt_containing(self.selections.newest_anchor().head(), cx)
1599 }
1600
1601 pub fn mode(&self) -> EditorMode {
1602 self.mode
1603 }
1604
1605 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1606 self.collaboration_hub.as_deref()
1607 }
1608
1609 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1610 self.collaboration_hub = Some(hub);
1611 }
1612
1613 pub fn set_custom_context_menu(
1614 &mut self,
1615 f: impl 'static
1616 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
1617 ) {
1618 self.custom_context_menu = Some(Box::new(f))
1619 }
1620
1621 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
1622 self.completion_provider = provider;
1623 }
1624
1625 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
1626 self.semantics_provider.clone()
1627 }
1628
1629 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
1630 self.semantics_provider = provider;
1631 }
1632
1633 pub fn set_inline_completion_provider<T>(
1634 &mut self,
1635 provider: Option<Model<T>>,
1636 cx: &mut ViewContext<Self>,
1637 ) where
1638 T: InlineCompletionProvider,
1639 {
1640 self.inline_completion_provider =
1641 provider.map(|provider| RegisteredInlineCompletionProvider {
1642 _subscription: cx.observe(&provider, |this, _, cx| {
1643 if this.focus_handle.is_focused(cx) {
1644 this.update_visible_inline_completion(cx);
1645 }
1646 }),
1647 provider: Arc::new(provider),
1648 });
1649 self.refresh_inline_completion(false, false, cx);
1650 }
1651
1652 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
1653 self.placeholder_text.as_deref()
1654 }
1655
1656 pub fn set_placeholder_text(
1657 &mut self,
1658 placeholder_text: impl Into<Arc<str>>,
1659 cx: &mut ViewContext<Self>,
1660 ) {
1661 let placeholder_text = Some(placeholder_text.into());
1662 if self.placeholder_text != placeholder_text {
1663 self.placeholder_text = placeholder_text;
1664 cx.notify();
1665 }
1666 }
1667
1668 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
1669 self.cursor_shape = cursor_shape;
1670
1671 // Disrupt blink for immediate user feedback that the cursor shape has changed
1672 self.blink_manager.update(cx, BlinkManager::show_cursor);
1673
1674 cx.notify();
1675 }
1676
1677 pub fn set_current_line_highlight(
1678 &mut self,
1679 current_line_highlight: Option<CurrentLineHighlight>,
1680 ) {
1681 self.current_line_highlight = current_line_highlight;
1682 }
1683
1684 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1685 self.collapse_matches = collapse_matches;
1686 }
1687
1688 pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
1689 let buffers = self.buffer.read(cx).all_buffers();
1690 let Some(lsp_store) = self.lsp_store(cx) else {
1691 return;
1692 };
1693 lsp_store.update(cx, |lsp_store, cx| {
1694 for buffer in buffers {
1695 self.registered_buffers
1696 .entry(buffer.read(cx).remote_id())
1697 .or_insert_with(|| {
1698 lsp_store.register_buffer_with_language_servers(&buffer, cx)
1699 });
1700 }
1701 })
1702 }
1703
1704 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1705 if self.collapse_matches {
1706 return range.start..range.start;
1707 }
1708 range.clone()
1709 }
1710
1711 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
1712 if self.display_map.read(cx).clip_at_line_ends != clip {
1713 self.display_map
1714 .update(cx, |map, _| map.clip_at_line_ends = clip);
1715 }
1716 }
1717
1718 pub fn set_input_enabled(&mut self, input_enabled: bool) {
1719 self.input_enabled = input_enabled;
1720 }
1721
1722 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
1723 self.enable_inline_completions = enabled;
1724 }
1725
1726 pub fn set_autoindent(&mut self, autoindent: bool) {
1727 if autoindent {
1728 self.autoindent_mode = Some(AutoindentMode::EachLine);
1729 } else {
1730 self.autoindent_mode = None;
1731 }
1732 }
1733
1734 pub fn read_only(&self, cx: &AppContext) -> bool {
1735 self.read_only || self.buffer.read(cx).read_only()
1736 }
1737
1738 pub fn set_read_only(&mut self, read_only: bool) {
1739 self.read_only = read_only;
1740 }
1741
1742 pub fn set_use_autoclose(&mut self, autoclose: bool) {
1743 self.use_autoclose = autoclose;
1744 }
1745
1746 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
1747 self.use_auto_surround = auto_surround;
1748 }
1749
1750 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
1751 self.auto_replace_emoji_shortcode = auto_replace;
1752 }
1753
1754 pub fn toggle_inline_completions(
1755 &mut self,
1756 _: &ToggleInlineCompletions,
1757 cx: &mut ViewContext<Self>,
1758 ) {
1759 if self.show_inline_completions_override.is_some() {
1760 self.set_show_inline_completions(None, cx);
1761 } else {
1762 let cursor = self.selections.newest_anchor().head();
1763 if let Some((buffer, cursor_buffer_position)) =
1764 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
1765 {
1766 let show_inline_completions =
1767 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
1768 self.set_show_inline_completions(Some(show_inline_completions), cx);
1769 }
1770 }
1771 }
1772
1773 pub fn set_show_inline_completions(
1774 &mut self,
1775 show_inline_completions: Option<bool>,
1776 cx: &mut ViewContext<Self>,
1777 ) {
1778 self.show_inline_completions_override = show_inline_completions;
1779 self.refresh_inline_completion(false, true, cx);
1780 }
1781
1782 fn should_show_inline_completions(
1783 &self,
1784 buffer: &Model<Buffer>,
1785 buffer_position: language::Anchor,
1786 cx: &AppContext,
1787 ) -> bool {
1788 if !self.snippet_stack.is_empty() {
1789 return false;
1790 }
1791
1792 if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
1793 return false;
1794 }
1795
1796 if let Some(provider) = self.inline_completion_provider() {
1797 if let Some(show_inline_completions) = self.show_inline_completions_override {
1798 show_inline_completions
1799 } else {
1800 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
1801 }
1802 } else {
1803 false
1804 }
1805 }
1806
1807 fn inline_completions_disabled_in_scope(
1808 &self,
1809 buffer: &Model<Buffer>,
1810 buffer_position: language::Anchor,
1811 cx: &AppContext,
1812 ) -> bool {
1813 let snapshot = buffer.read(cx).snapshot();
1814 let settings = snapshot.settings_at(buffer_position, cx);
1815
1816 let Some(scope) = snapshot.language_scope_at(buffer_position) else {
1817 return false;
1818 };
1819
1820 scope.override_name().map_or(false, |scope_name| {
1821 settings
1822 .inline_completions_disabled_in
1823 .iter()
1824 .any(|s| s == scope_name)
1825 })
1826 }
1827
1828 pub fn set_use_modal_editing(&mut self, to: bool) {
1829 self.use_modal_editing = to;
1830 }
1831
1832 pub fn use_modal_editing(&self) -> bool {
1833 self.use_modal_editing
1834 }
1835
1836 fn selections_did_change(
1837 &mut self,
1838 local: bool,
1839 old_cursor_position: &Anchor,
1840 show_completions: bool,
1841 cx: &mut ViewContext<Self>,
1842 ) {
1843 cx.invalidate_character_coordinates();
1844
1845 // Copy selections to primary selection buffer
1846 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1847 if local {
1848 let selections = self.selections.all::<usize>(cx);
1849 let buffer_handle = self.buffer.read(cx).read(cx);
1850
1851 let mut text = String::new();
1852 for (index, selection) in selections.iter().enumerate() {
1853 let text_for_selection = buffer_handle
1854 .text_for_range(selection.start..selection.end)
1855 .collect::<String>();
1856
1857 text.push_str(&text_for_selection);
1858 if index != selections.len() - 1 {
1859 text.push('\n');
1860 }
1861 }
1862
1863 if !text.is_empty() {
1864 cx.write_to_primary(ClipboardItem::new_string(text));
1865 }
1866 }
1867
1868 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
1869 self.buffer.update(cx, |buffer, cx| {
1870 buffer.set_active_selections(
1871 &self.selections.disjoint_anchors(),
1872 self.selections.line_mode,
1873 self.cursor_shape,
1874 cx,
1875 )
1876 });
1877 }
1878 let display_map = self
1879 .display_map
1880 .update(cx, |display_map, cx| display_map.snapshot(cx));
1881 let buffer = &display_map.buffer_snapshot;
1882 self.add_selections_state = None;
1883 self.select_next_state = None;
1884 self.select_prev_state = None;
1885 self.select_larger_syntax_node_stack.clear();
1886 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
1887 self.snippet_stack
1888 .invalidate(&self.selections.disjoint_anchors(), buffer);
1889 self.take_rename(false, cx);
1890
1891 let new_cursor_position = self.selections.newest_anchor().head();
1892
1893 self.push_to_nav_history(
1894 *old_cursor_position,
1895 Some(new_cursor_position.to_point(buffer)),
1896 cx,
1897 );
1898
1899 if local {
1900 let new_cursor_position = self.selections.newest_anchor().head();
1901 let mut context_menu = self.context_menu.borrow_mut();
1902 let completion_menu = match context_menu.as_ref() {
1903 Some(CodeContextMenu::Completions(menu)) => Some(menu),
1904 _ => {
1905 *context_menu = None;
1906 None
1907 }
1908 };
1909
1910 if let Some(completion_menu) = completion_menu {
1911 let cursor_position = new_cursor_position.to_offset(buffer);
1912 let (word_range, kind) =
1913 buffer.surrounding_word(completion_menu.initial_position, true);
1914 if kind == Some(CharKind::Word)
1915 && word_range.to_inclusive().contains(&cursor_position)
1916 {
1917 let mut completion_menu = completion_menu.clone();
1918 drop(context_menu);
1919
1920 let query = Self::completion_query(buffer, cursor_position);
1921 cx.spawn(move |this, mut cx| async move {
1922 completion_menu
1923 .filter(query.as_deref(), cx.background_executor().clone())
1924 .await;
1925
1926 this.update(&mut cx, |this, cx| {
1927 let mut context_menu = this.context_menu.borrow_mut();
1928 let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
1929 else {
1930 return;
1931 };
1932
1933 if menu.id > completion_menu.id {
1934 return;
1935 }
1936
1937 *context_menu = Some(CodeContextMenu::Completions(completion_menu));
1938 drop(context_menu);
1939 cx.notify();
1940 })
1941 })
1942 .detach();
1943
1944 if show_completions {
1945 self.show_completions(&ShowCompletions { trigger: None }, cx);
1946 }
1947 } else {
1948 drop(context_menu);
1949 self.hide_context_menu(cx);
1950 }
1951 } else {
1952 drop(context_menu);
1953 }
1954
1955 hide_hover(self, cx);
1956
1957 if old_cursor_position.to_display_point(&display_map).row()
1958 != new_cursor_position.to_display_point(&display_map).row()
1959 {
1960 self.available_code_actions.take();
1961 }
1962 self.refresh_code_actions(cx);
1963 self.refresh_document_highlights(cx);
1964 refresh_matching_bracket_highlights(self, cx);
1965 self.update_visible_inline_completion(cx);
1966 linked_editing_ranges::refresh_linked_ranges(self, cx);
1967 if self.git_blame_inline_enabled {
1968 self.start_inline_blame_timer(cx);
1969 }
1970 }
1971
1972 self.blink_manager.update(cx, BlinkManager::pause_blinking);
1973 cx.emit(EditorEvent::SelectionsChanged { local });
1974
1975 if self.selections.disjoint_anchors().len() == 1 {
1976 cx.emit(SearchEvent::ActiveMatchChanged)
1977 }
1978 cx.notify();
1979 }
1980
1981 pub fn change_selections<R>(
1982 &mut self,
1983 autoscroll: Option<Autoscroll>,
1984 cx: &mut ViewContext<Self>,
1985 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
1986 ) -> R {
1987 self.change_selections_inner(autoscroll, true, cx, change)
1988 }
1989
1990 pub fn change_selections_inner<R>(
1991 &mut self,
1992 autoscroll: Option<Autoscroll>,
1993 request_completions: bool,
1994 cx: &mut ViewContext<Self>,
1995 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
1996 ) -> R {
1997 let old_cursor_position = self.selections.newest_anchor().head();
1998 self.push_to_selection_history();
1999
2000 let (changed, result) = self.selections.change_with(cx, change);
2001
2002 if changed {
2003 if let Some(autoscroll) = autoscroll {
2004 self.request_autoscroll(autoscroll, cx);
2005 }
2006 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2007
2008 if self.should_open_signature_help_automatically(
2009 &old_cursor_position,
2010 self.signature_help_state.backspace_pressed(),
2011 cx,
2012 ) {
2013 self.show_signature_help(&ShowSignatureHelp, cx);
2014 }
2015 self.signature_help_state.set_backspace_pressed(false);
2016 }
2017
2018 result
2019 }
2020
2021 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2022 where
2023 I: IntoIterator<Item = (Range<S>, T)>,
2024 S: ToOffset,
2025 T: Into<Arc<str>>,
2026 {
2027 if self.read_only(cx) {
2028 return;
2029 }
2030
2031 self.buffer
2032 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2033 }
2034
2035 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2036 where
2037 I: IntoIterator<Item = (Range<S>, T)>,
2038 S: ToOffset,
2039 T: Into<Arc<str>>,
2040 {
2041 if self.read_only(cx) {
2042 return;
2043 }
2044
2045 self.buffer.update(cx, |buffer, cx| {
2046 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2047 });
2048 }
2049
2050 pub fn edit_with_block_indent<I, S, T>(
2051 &mut self,
2052 edits: I,
2053 original_indent_columns: Vec<u32>,
2054 cx: &mut ViewContext<Self>,
2055 ) where
2056 I: IntoIterator<Item = (Range<S>, T)>,
2057 S: ToOffset,
2058 T: Into<Arc<str>>,
2059 {
2060 if self.read_only(cx) {
2061 return;
2062 }
2063
2064 self.buffer.update(cx, |buffer, cx| {
2065 buffer.edit(
2066 edits,
2067 Some(AutoindentMode::Block {
2068 original_indent_columns,
2069 }),
2070 cx,
2071 )
2072 });
2073 }
2074
2075 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2076 self.hide_context_menu(cx);
2077
2078 match phase {
2079 SelectPhase::Begin {
2080 position,
2081 add,
2082 click_count,
2083 } => self.begin_selection(position, add, click_count, cx),
2084 SelectPhase::BeginColumnar {
2085 position,
2086 goal_column,
2087 reset,
2088 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2089 SelectPhase::Extend {
2090 position,
2091 click_count,
2092 } => self.extend_selection(position, click_count, cx),
2093 SelectPhase::Update {
2094 position,
2095 goal_column,
2096 scroll_delta,
2097 } => self.update_selection(position, goal_column, scroll_delta, cx),
2098 SelectPhase::End => self.end_selection(cx),
2099 }
2100 }
2101
2102 fn extend_selection(
2103 &mut self,
2104 position: DisplayPoint,
2105 click_count: usize,
2106 cx: &mut ViewContext<Self>,
2107 ) {
2108 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2109 let tail = self.selections.newest::<usize>(cx).tail();
2110 self.begin_selection(position, false, click_count, cx);
2111
2112 let position = position.to_offset(&display_map, Bias::Left);
2113 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2114
2115 let mut pending_selection = self
2116 .selections
2117 .pending_anchor()
2118 .expect("extend_selection not called with pending selection");
2119 if position >= tail {
2120 pending_selection.start = tail_anchor;
2121 } else {
2122 pending_selection.end = tail_anchor;
2123 pending_selection.reversed = true;
2124 }
2125
2126 let mut pending_mode = self.selections.pending_mode().unwrap();
2127 match &mut pending_mode {
2128 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2129 _ => {}
2130 }
2131
2132 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2133 s.set_pending(pending_selection, pending_mode)
2134 });
2135 }
2136
2137 fn begin_selection(
2138 &mut self,
2139 position: DisplayPoint,
2140 add: bool,
2141 click_count: usize,
2142 cx: &mut ViewContext<Self>,
2143 ) {
2144 if !self.focus_handle.is_focused(cx) {
2145 self.last_focused_descendant = None;
2146 cx.focus(&self.focus_handle);
2147 }
2148
2149 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2150 let buffer = &display_map.buffer_snapshot;
2151 let newest_selection = self.selections.newest_anchor().clone();
2152 let position = display_map.clip_point(position, Bias::Left);
2153
2154 let start;
2155 let end;
2156 let mode;
2157 let mut auto_scroll;
2158 match click_count {
2159 1 => {
2160 start = buffer.anchor_before(position.to_point(&display_map));
2161 end = start;
2162 mode = SelectMode::Character;
2163 auto_scroll = true;
2164 }
2165 2 => {
2166 let range = movement::surrounding_word(&display_map, position);
2167 start = buffer.anchor_before(range.start.to_point(&display_map));
2168 end = buffer.anchor_before(range.end.to_point(&display_map));
2169 mode = SelectMode::Word(start..end);
2170 auto_scroll = true;
2171 }
2172 3 => {
2173 let position = display_map
2174 .clip_point(position, Bias::Left)
2175 .to_point(&display_map);
2176 let line_start = display_map.prev_line_boundary(position).0;
2177 let next_line_start = buffer.clip_point(
2178 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2179 Bias::Left,
2180 );
2181 start = buffer.anchor_before(line_start);
2182 end = buffer.anchor_before(next_line_start);
2183 mode = SelectMode::Line(start..end);
2184 auto_scroll = true;
2185 }
2186 _ => {
2187 start = buffer.anchor_before(0);
2188 end = buffer.anchor_before(buffer.len());
2189 mode = SelectMode::All;
2190 auto_scroll = false;
2191 }
2192 }
2193 auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
2194
2195 let point_to_delete: Option<usize> = {
2196 let selected_points: Vec<Selection<Point>> =
2197 self.selections.disjoint_in_range(start..end, cx);
2198
2199 if !add || click_count > 1 {
2200 None
2201 } else if !selected_points.is_empty() {
2202 Some(selected_points[0].id)
2203 } else {
2204 let clicked_point_already_selected =
2205 self.selections.disjoint.iter().find(|selection| {
2206 selection.start.to_point(buffer) == start.to_point(buffer)
2207 || selection.end.to_point(buffer) == end.to_point(buffer)
2208 });
2209
2210 clicked_point_already_selected.map(|selection| selection.id)
2211 }
2212 };
2213
2214 let selections_count = self.selections.count();
2215
2216 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2217 if let Some(point_to_delete) = point_to_delete {
2218 s.delete(point_to_delete);
2219
2220 if selections_count == 1 {
2221 s.set_pending_anchor_range(start..end, mode);
2222 }
2223 } else {
2224 if !add {
2225 s.clear_disjoint();
2226 } else if click_count > 1 {
2227 s.delete(newest_selection.id)
2228 }
2229
2230 s.set_pending_anchor_range(start..end, mode);
2231 }
2232 });
2233 }
2234
2235 fn begin_columnar_selection(
2236 &mut self,
2237 position: DisplayPoint,
2238 goal_column: u32,
2239 reset: bool,
2240 cx: &mut ViewContext<Self>,
2241 ) {
2242 if !self.focus_handle.is_focused(cx) {
2243 self.last_focused_descendant = None;
2244 cx.focus(&self.focus_handle);
2245 }
2246
2247 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2248
2249 if reset {
2250 let pointer_position = display_map
2251 .buffer_snapshot
2252 .anchor_before(position.to_point(&display_map));
2253
2254 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2255 s.clear_disjoint();
2256 s.set_pending_anchor_range(
2257 pointer_position..pointer_position,
2258 SelectMode::Character,
2259 );
2260 });
2261 }
2262
2263 let tail = self.selections.newest::<Point>(cx).tail();
2264 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2265
2266 if !reset {
2267 self.select_columns(
2268 tail.to_display_point(&display_map),
2269 position,
2270 goal_column,
2271 &display_map,
2272 cx,
2273 );
2274 }
2275 }
2276
2277 fn update_selection(
2278 &mut self,
2279 position: DisplayPoint,
2280 goal_column: u32,
2281 scroll_delta: gpui::Point<f32>,
2282 cx: &mut ViewContext<Self>,
2283 ) {
2284 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2285
2286 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2287 let tail = tail.to_display_point(&display_map);
2288 self.select_columns(tail, position, goal_column, &display_map, cx);
2289 } else if let Some(mut pending) = self.selections.pending_anchor() {
2290 let buffer = self.buffer.read(cx).snapshot(cx);
2291 let head;
2292 let tail;
2293 let mode = self.selections.pending_mode().unwrap();
2294 match &mode {
2295 SelectMode::Character => {
2296 head = position.to_point(&display_map);
2297 tail = pending.tail().to_point(&buffer);
2298 }
2299 SelectMode::Word(original_range) => {
2300 let original_display_range = original_range.start.to_display_point(&display_map)
2301 ..original_range.end.to_display_point(&display_map);
2302 let original_buffer_range = original_display_range.start.to_point(&display_map)
2303 ..original_display_range.end.to_point(&display_map);
2304 if movement::is_inside_word(&display_map, position)
2305 || original_display_range.contains(&position)
2306 {
2307 let word_range = movement::surrounding_word(&display_map, position);
2308 if word_range.start < original_display_range.start {
2309 head = word_range.start.to_point(&display_map);
2310 } else {
2311 head = word_range.end.to_point(&display_map);
2312 }
2313 } else {
2314 head = position.to_point(&display_map);
2315 }
2316
2317 if head <= original_buffer_range.start {
2318 tail = original_buffer_range.end;
2319 } else {
2320 tail = original_buffer_range.start;
2321 }
2322 }
2323 SelectMode::Line(original_range) => {
2324 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2325
2326 let position = display_map
2327 .clip_point(position, Bias::Left)
2328 .to_point(&display_map);
2329 let line_start = display_map.prev_line_boundary(position).0;
2330 let next_line_start = buffer.clip_point(
2331 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2332 Bias::Left,
2333 );
2334
2335 if line_start < original_range.start {
2336 head = line_start
2337 } else {
2338 head = next_line_start
2339 }
2340
2341 if head <= original_range.start {
2342 tail = original_range.end;
2343 } else {
2344 tail = original_range.start;
2345 }
2346 }
2347 SelectMode::All => {
2348 return;
2349 }
2350 };
2351
2352 if head < tail {
2353 pending.start = buffer.anchor_before(head);
2354 pending.end = buffer.anchor_before(tail);
2355 pending.reversed = true;
2356 } else {
2357 pending.start = buffer.anchor_before(tail);
2358 pending.end = buffer.anchor_before(head);
2359 pending.reversed = false;
2360 }
2361
2362 self.change_selections(None, cx, |s| {
2363 s.set_pending(pending, mode);
2364 });
2365 } else {
2366 log::error!("update_selection dispatched with no pending selection");
2367 return;
2368 }
2369
2370 self.apply_scroll_delta(scroll_delta, cx);
2371 cx.notify();
2372 }
2373
2374 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2375 self.columnar_selection_tail.take();
2376 if self.selections.pending_anchor().is_some() {
2377 let selections = self.selections.all::<usize>(cx);
2378 self.change_selections(None, cx, |s| {
2379 s.select(selections);
2380 s.clear_pending();
2381 });
2382 }
2383 }
2384
2385 fn select_columns(
2386 &mut self,
2387 tail: DisplayPoint,
2388 head: DisplayPoint,
2389 goal_column: u32,
2390 display_map: &DisplaySnapshot,
2391 cx: &mut ViewContext<Self>,
2392 ) {
2393 let start_row = cmp::min(tail.row(), head.row());
2394 let end_row = cmp::max(tail.row(), head.row());
2395 let start_column = cmp::min(tail.column(), goal_column);
2396 let end_column = cmp::max(tail.column(), goal_column);
2397 let reversed = start_column < tail.column();
2398
2399 let selection_ranges = (start_row.0..=end_row.0)
2400 .map(DisplayRow)
2401 .filter_map(|row| {
2402 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2403 let start = display_map
2404 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2405 .to_point(display_map);
2406 let end = display_map
2407 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2408 .to_point(display_map);
2409 if reversed {
2410 Some(end..start)
2411 } else {
2412 Some(start..end)
2413 }
2414 } else {
2415 None
2416 }
2417 })
2418 .collect::<Vec<_>>();
2419
2420 self.change_selections(None, cx, |s| {
2421 s.select_ranges(selection_ranges);
2422 });
2423 cx.notify();
2424 }
2425
2426 pub fn has_pending_nonempty_selection(&self) -> bool {
2427 let pending_nonempty_selection = match self.selections.pending_anchor() {
2428 Some(Selection { start, end, .. }) => start != end,
2429 None => false,
2430 };
2431
2432 pending_nonempty_selection
2433 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2434 }
2435
2436 pub fn has_pending_selection(&self) -> bool {
2437 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2438 }
2439
2440 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2441 if self.clear_expanded_diff_hunks(cx) {
2442 cx.notify();
2443 return;
2444 }
2445 if self.dismiss_menus_and_popups(true, cx) {
2446 return;
2447 }
2448
2449 if self.mode == EditorMode::Full
2450 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
2451 {
2452 return;
2453 }
2454
2455 cx.propagate();
2456 }
2457
2458 pub fn dismiss_menus_and_popups(
2459 &mut self,
2460 should_report_inline_completion_event: bool,
2461 cx: &mut ViewContext<Self>,
2462 ) -> bool {
2463 if self.take_rename(false, cx).is_some() {
2464 return true;
2465 }
2466
2467 if hide_hover(self, cx) {
2468 return true;
2469 }
2470
2471 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2472 return true;
2473 }
2474
2475 if self.hide_context_menu(cx).is_some() {
2476 if self.has_active_inline_completion() {
2477 self.update_visible_inline_completion(cx);
2478 }
2479 return true;
2480 }
2481
2482 if self.mouse_context_menu.take().is_some() {
2483 return true;
2484 }
2485
2486 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2487 return true;
2488 }
2489
2490 if self.snippet_stack.pop().is_some() {
2491 return true;
2492 }
2493
2494 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
2495 self.dismiss_diagnostics(cx);
2496 return true;
2497 }
2498
2499 false
2500 }
2501
2502 fn linked_editing_ranges_for(
2503 &self,
2504 selection: Range<text::Anchor>,
2505 cx: &AppContext,
2506 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2507 if self.linked_edit_ranges.is_empty() {
2508 return None;
2509 }
2510 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2511 selection.end.buffer_id.and_then(|end_buffer_id| {
2512 if selection.start.buffer_id != Some(end_buffer_id) {
2513 return None;
2514 }
2515 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2516 let snapshot = buffer.read(cx).snapshot();
2517 self.linked_edit_ranges
2518 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2519 .map(|ranges| (ranges, snapshot, buffer))
2520 })?;
2521 use text::ToOffset as TO;
2522 // find offset from the start of current range to current cursor position
2523 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2524
2525 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2526 let start_difference = start_offset - start_byte_offset;
2527 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2528 let end_difference = end_offset - start_byte_offset;
2529 // Current range has associated linked ranges.
2530 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2531 for range in linked_ranges.iter() {
2532 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2533 let end_offset = start_offset + end_difference;
2534 let start_offset = start_offset + start_difference;
2535 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
2536 continue;
2537 }
2538 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
2539 if s.start.buffer_id != selection.start.buffer_id
2540 || s.end.buffer_id != selection.end.buffer_id
2541 {
2542 return false;
2543 }
2544 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
2545 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
2546 }) {
2547 continue;
2548 }
2549 let start = buffer_snapshot.anchor_after(start_offset);
2550 let end = buffer_snapshot.anchor_after(end_offset);
2551 linked_edits
2552 .entry(buffer.clone())
2553 .or_default()
2554 .push(start..end);
2555 }
2556 Some(linked_edits)
2557 }
2558
2559 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2560 let text: Arc<str> = text.into();
2561
2562 if self.read_only(cx) {
2563 return;
2564 }
2565
2566 let selections = self.selections.all_adjusted(cx);
2567 let mut bracket_inserted = false;
2568 let mut edits = Vec::new();
2569 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2570 let mut new_selections = Vec::with_capacity(selections.len());
2571 let mut new_autoclose_regions = Vec::new();
2572 let snapshot = self.buffer.read(cx).read(cx);
2573
2574 for (selection, autoclose_region) in
2575 self.selections_with_autoclose_regions(selections, &snapshot)
2576 {
2577 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2578 // Determine if the inserted text matches the opening or closing
2579 // bracket of any of this language's bracket pairs.
2580 let mut bracket_pair = None;
2581 let mut is_bracket_pair_start = false;
2582 let mut is_bracket_pair_end = false;
2583 if !text.is_empty() {
2584 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
2585 // and they are removing the character that triggered IME popup.
2586 for (pair, enabled) in scope.brackets() {
2587 if !pair.close && !pair.surround {
2588 continue;
2589 }
2590
2591 if enabled && pair.start.ends_with(text.as_ref()) {
2592 let prefix_len = pair.start.len() - text.len();
2593 let preceding_text_matches_prefix = prefix_len == 0
2594 || (selection.start.column >= (prefix_len as u32)
2595 && snapshot.contains_str_at(
2596 Point::new(
2597 selection.start.row,
2598 selection.start.column - (prefix_len as u32),
2599 ),
2600 &pair.start[..prefix_len],
2601 ));
2602 if preceding_text_matches_prefix {
2603 bracket_pair = Some(pair.clone());
2604 is_bracket_pair_start = true;
2605 break;
2606 }
2607 }
2608 if pair.end.as_str() == text.as_ref() {
2609 bracket_pair = Some(pair.clone());
2610 is_bracket_pair_end = true;
2611 break;
2612 }
2613 }
2614 }
2615
2616 if let Some(bracket_pair) = bracket_pair {
2617 let snapshot_settings = snapshot.settings_at(selection.start, cx);
2618 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
2619 let auto_surround =
2620 self.use_auto_surround && snapshot_settings.use_auto_surround;
2621 if selection.is_empty() {
2622 if is_bracket_pair_start {
2623 // If the inserted text is a suffix of an opening bracket and the
2624 // selection is preceded by the rest of the opening bracket, then
2625 // insert the closing bracket.
2626 let following_text_allows_autoclose = snapshot
2627 .chars_at(selection.start)
2628 .next()
2629 .map_or(true, |c| scope.should_autoclose_before(c));
2630
2631 let is_closing_quote = if bracket_pair.end == bracket_pair.start
2632 && bracket_pair.start.len() == 1
2633 {
2634 let target = bracket_pair.start.chars().next().unwrap();
2635 let current_line_count = snapshot
2636 .reversed_chars_at(selection.start)
2637 .take_while(|&c| c != '\n')
2638 .filter(|&c| c == target)
2639 .count();
2640 current_line_count % 2 == 1
2641 } else {
2642 false
2643 };
2644
2645 if autoclose
2646 && bracket_pair.close
2647 && following_text_allows_autoclose
2648 && !is_closing_quote
2649 {
2650 let anchor = snapshot.anchor_before(selection.end);
2651 new_selections.push((selection.map(|_| anchor), text.len()));
2652 new_autoclose_regions.push((
2653 anchor,
2654 text.len(),
2655 selection.id,
2656 bracket_pair.clone(),
2657 ));
2658 edits.push((
2659 selection.range(),
2660 format!("{}{}", text, bracket_pair.end).into(),
2661 ));
2662 bracket_inserted = true;
2663 continue;
2664 }
2665 }
2666
2667 if let Some(region) = autoclose_region {
2668 // If the selection is followed by an auto-inserted closing bracket,
2669 // then don't insert that closing bracket again; just move the selection
2670 // past the closing bracket.
2671 let should_skip = selection.end == region.range.end.to_point(&snapshot)
2672 && text.as_ref() == region.pair.end.as_str();
2673 if should_skip {
2674 let anchor = snapshot.anchor_after(selection.end);
2675 new_selections
2676 .push((selection.map(|_| anchor), region.pair.end.len()));
2677 continue;
2678 }
2679 }
2680
2681 let always_treat_brackets_as_autoclosed = snapshot
2682 .settings_at(selection.start, cx)
2683 .always_treat_brackets_as_autoclosed;
2684 if always_treat_brackets_as_autoclosed
2685 && is_bracket_pair_end
2686 && snapshot.contains_str_at(selection.end, text.as_ref())
2687 {
2688 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
2689 // and the inserted text is a closing bracket and the selection is followed
2690 // by the closing bracket then move the selection past the closing bracket.
2691 let anchor = snapshot.anchor_after(selection.end);
2692 new_selections.push((selection.map(|_| anchor), text.len()));
2693 continue;
2694 }
2695 }
2696 // If an opening bracket is 1 character long and is typed while
2697 // text is selected, then surround that text with the bracket pair.
2698 else if auto_surround
2699 && bracket_pair.surround
2700 && is_bracket_pair_start
2701 && bracket_pair.start.chars().count() == 1
2702 {
2703 edits.push((selection.start..selection.start, text.clone()));
2704 edits.push((
2705 selection.end..selection.end,
2706 bracket_pair.end.as_str().into(),
2707 ));
2708 bracket_inserted = true;
2709 new_selections.push((
2710 Selection {
2711 id: selection.id,
2712 start: snapshot.anchor_after(selection.start),
2713 end: snapshot.anchor_before(selection.end),
2714 reversed: selection.reversed,
2715 goal: selection.goal,
2716 },
2717 0,
2718 ));
2719 continue;
2720 }
2721 }
2722 }
2723
2724 if self.auto_replace_emoji_shortcode
2725 && selection.is_empty()
2726 && text.as_ref().ends_with(':')
2727 {
2728 if let Some(possible_emoji_short_code) =
2729 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
2730 {
2731 if !possible_emoji_short_code.is_empty() {
2732 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
2733 let emoji_shortcode_start = Point::new(
2734 selection.start.row,
2735 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
2736 );
2737
2738 // Remove shortcode from buffer
2739 edits.push((
2740 emoji_shortcode_start..selection.start,
2741 "".to_string().into(),
2742 ));
2743 new_selections.push((
2744 Selection {
2745 id: selection.id,
2746 start: snapshot.anchor_after(emoji_shortcode_start),
2747 end: snapshot.anchor_before(selection.start),
2748 reversed: selection.reversed,
2749 goal: selection.goal,
2750 },
2751 0,
2752 ));
2753
2754 // Insert emoji
2755 let selection_start_anchor = snapshot.anchor_after(selection.start);
2756 new_selections.push((selection.map(|_| selection_start_anchor), 0));
2757 edits.push((selection.start..selection.end, emoji.to_string().into()));
2758
2759 continue;
2760 }
2761 }
2762 }
2763 }
2764
2765 // If not handling any auto-close operation, then just replace the selected
2766 // text with the given input and move the selection to the end of the
2767 // newly inserted text.
2768 let anchor = snapshot.anchor_after(selection.end);
2769 if !self.linked_edit_ranges.is_empty() {
2770 let start_anchor = snapshot.anchor_before(selection.start);
2771
2772 let is_word_char = text.chars().next().map_or(true, |char| {
2773 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
2774 classifier.is_word(char)
2775 });
2776
2777 if is_word_char {
2778 if let Some(ranges) = self
2779 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
2780 {
2781 for (buffer, edits) in ranges {
2782 linked_edits
2783 .entry(buffer.clone())
2784 .or_default()
2785 .extend(edits.into_iter().map(|range| (range, text.clone())));
2786 }
2787 }
2788 }
2789 }
2790
2791 new_selections.push((selection.map(|_| anchor), 0));
2792 edits.push((selection.start..selection.end, text.clone()));
2793 }
2794
2795 drop(snapshot);
2796
2797 self.transact(cx, |this, cx| {
2798 this.buffer.update(cx, |buffer, cx| {
2799 buffer.edit(edits, this.autoindent_mode.clone(), cx);
2800 });
2801 for (buffer, edits) in linked_edits {
2802 buffer.update(cx, |buffer, cx| {
2803 let snapshot = buffer.snapshot();
2804 let edits = edits
2805 .into_iter()
2806 .map(|(range, text)| {
2807 use text::ToPoint as TP;
2808 let end_point = TP::to_point(&range.end, &snapshot);
2809 let start_point = TP::to_point(&range.start, &snapshot);
2810 (start_point..end_point, text)
2811 })
2812 .sorted_by_key(|(range, _)| range.start)
2813 .collect::<Vec<_>>();
2814 buffer.edit(edits, None, cx);
2815 })
2816 }
2817 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2818 let new_selection_deltas = new_selections.iter().map(|e| e.1);
2819 let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
2820 let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
2821 .zip(new_selection_deltas)
2822 .map(|(selection, delta)| Selection {
2823 id: selection.id,
2824 start: selection.start + delta,
2825 end: selection.end + delta,
2826 reversed: selection.reversed,
2827 goal: SelectionGoal::None,
2828 })
2829 .collect::<Vec<_>>();
2830
2831 let mut i = 0;
2832 for (position, delta, selection_id, pair) in new_autoclose_regions {
2833 let position = position.to_offset(&map.buffer_snapshot) + delta;
2834 let start = map.buffer_snapshot.anchor_before(position);
2835 let end = map.buffer_snapshot.anchor_after(position);
2836 while let Some(existing_state) = this.autoclose_regions.get(i) {
2837 match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
2838 Ordering::Less => i += 1,
2839 Ordering::Greater => break,
2840 Ordering::Equal => {
2841 match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
2842 Ordering::Less => i += 1,
2843 Ordering::Equal => break,
2844 Ordering::Greater => break,
2845 }
2846 }
2847 }
2848 }
2849 this.autoclose_regions.insert(
2850 i,
2851 AutocloseRegion {
2852 selection_id,
2853 range: start..end,
2854 pair,
2855 },
2856 );
2857 }
2858
2859 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
2860 s.select(new_selections)
2861 });
2862
2863 if !bracket_inserted {
2864 if let Some(on_type_format_task) =
2865 this.trigger_on_type_formatting(text.to_string(), cx)
2866 {
2867 on_type_format_task.detach_and_log_err(cx);
2868 }
2869 }
2870
2871 let editor_settings = EditorSettings::get_global(cx);
2872 if bracket_inserted
2873 && (editor_settings.auto_signature_help
2874 || editor_settings.show_signature_help_after_edits)
2875 {
2876 this.show_signature_help(&ShowSignatureHelp, cx);
2877 }
2878
2879 this.trigger_completion_on_input(&text, true, cx);
2880 linked_editing_ranges::refresh_linked_ranges(this, cx);
2881 this.refresh_inline_completion(true, false, cx);
2882 });
2883 }
2884
2885 fn find_possible_emoji_shortcode_at_position(
2886 snapshot: &MultiBufferSnapshot,
2887 position: Point,
2888 ) -> Option<String> {
2889 let mut chars = Vec::new();
2890 let mut found_colon = false;
2891 for char in snapshot.reversed_chars_at(position).take(100) {
2892 // Found a possible emoji shortcode in the middle of the buffer
2893 if found_colon {
2894 if char.is_whitespace() {
2895 chars.reverse();
2896 return Some(chars.iter().collect());
2897 }
2898 // If the previous character is not a whitespace, we are in the middle of a word
2899 // and we only want to complete the shortcode if the word is made up of other emojis
2900 let mut containing_word = String::new();
2901 for ch in snapshot
2902 .reversed_chars_at(position)
2903 .skip(chars.len() + 1)
2904 .take(100)
2905 {
2906 if ch.is_whitespace() {
2907 break;
2908 }
2909 containing_word.push(ch);
2910 }
2911 let containing_word = containing_word.chars().rev().collect::<String>();
2912 if util::word_consists_of_emojis(containing_word.as_str()) {
2913 chars.reverse();
2914 return Some(chars.iter().collect());
2915 }
2916 }
2917
2918 if char.is_whitespace() || !char.is_ascii() {
2919 return None;
2920 }
2921 if char == ':' {
2922 found_colon = true;
2923 } else {
2924 chars.push(char);
2925 }
2926 }
2927 // Found a possible emoji shortcode at the beginning of the buffer
2928 chars.reverse();
2929 Some(chars.iter().collect())
2930 }
2931
2932 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
2933 self.transact(cx, |this, cx| {
2934 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
2935 let selections = this.selections.all::<usize>(cx);
2936 let multi_buffer = this.buffer.read(cx);
2937 let buffer = multi_buffer.snapshot(cx);
2938 selections
2939 .iter()
2940 .map(|selection| {
2941 let start_point = selection.start.to_point(&buffer);
2942 let mut indent =
2943 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
2944 indent.len = cmp::min(indent.len, start_point.column);
2945 let start = selection.start;
2946 let end = selection.end;
2947 let selection_is_empty = start == end;
2948 let language_scope = buffer.language_scope_at(start);
2949 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
2950 &language_scope
2951 {
2952 let leading_whitespace_len = buffer
2953 .reversed_chars_at(start)
2954 .take_while(|c| c.is_whitespace() && *c != '\n')
2955 .map(|c| c.len_utf8())
2956 .sum::<usize>();
2957
2958 let trailing_whitespace_len = buffer
2959 .chars_at(end)
2960 .take_while(|c| c.is_whitespace() && *c != '\n')
2961 .map(|c| c.len_utf8())
2962 .sum::<usize>();
2963
2964 let insert_extra_newline =
2965 language.brackets().any(|(pair, enabled)| {
2966 let pair_start = pair.start.trim_end();
2967 let pair_end = pair.end.trim_start();
2968
2969 enabled
2970 && pair.newline
2971 && buffer.contains_str_at(
2972 end + trailing_whitespace_len,
2973 pair_end,
2974 )
2975 && buffer.contains_str_at(
2976 (start - leading_whitespace_len)
2977 .saturating_sub(pair_start.len()),
2978 pair_start,
2979 )
2980 });
2981
2982 // Comment extension on newline is allowed only for cursor selections
2983 let comment_delimiter = maybe!({
2984 if !selection_is_empty {
2985 return None;
2986 }
2987
2988 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
2989 return None;
2990 }
2991
2992 let delimiters = language.line_comment_prefixes();
2993 let max_len_of_delimiter =
2994 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
2995 let (snapshot, range) =
2996 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
2997
2998 let mut index_of_first_non_whitespace = 0;
2999 let comment_candidate = snapshot
3000 .chars_for_range(range)
3001 .skip_while(|c| {
3002 let should_skip = c.is_whitespace();
3003 if should_skip {
3004 index_of_first_non_whitespace += 1;
3005 }
3006 should_skip
3007 })
3008 .take(max_len_of_delimiter)
3009 .collect::<String>();
3010 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3011 comment_candidate.starts_with(comment_prefix.as_ref())
3012 })?;
3013 let cursor_is_placed_after_comment_marker =
3014 index_of_first_non_whitespace + comment_prefix.len()
3015 <= start_point.column as usize;
3016 if cursor_is_placed_after_comment_marker {
3017 Some(comment_prefix.clone())
3018 } else {
3019 None
3020 }
3021 });
3022 (comment_delimiter, insert_extra_newline)
3023 } else {
3024 (None, false)
3025 };
3026
3027 let capacity_for_delimiter = comment_delimiter
3028 .as_deref()
3029 .map(str::len)
3030 .unwrap_or_default();
3031 let mut new_text =
3032 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3033 new_text.push('\n');
3034 new_text.extend(indent.chars());
3035 if let Some(delimiter) = &comment_delimiter {
3036 new_text.push_str(delimiter);
3037 }
3038 if insert_extra_newline {
3039 new_text = new_text.repeat(2);
3040 }
3041
3042 let anchor = buffer.anchor_after(end);
3043 let new_selection = selection.map(|_| anchor);
3044 (
3045 (start..end, new_text),
3046 (insert_extra_newline, new_selection),
3047 )
3048 })
3049 .unzip()
3050 };
3051
3052 this.edit_with_autoindent(edits, cx);
3053 let buffer = this.buffer.read(cx).snapshot(cx);
3054 let new_selections = selection_fixup_info
3055 .into_iter()
3056 .map(|(extra_newline_inserted, new_selection)| {
3057 let mut cursor = new_selection.end.to_point(&buffer);
3058 if extra_newline_inserted {
3059 cursor.row -= 1;
3060 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3061 }
3062 new_selection.map(|_| cursor)
3063 })
3064 .collect();
3065
3066 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3067 this.refresh_inline_completion(true, false, cx);
3068 });
3069 }
3070
3071 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3072 let buffer = self.buffer.read(cx);
3073 let snapshot = buffer.snapshot(cx);
3074
3075 let mut edits = Vec::new();
3076 let mut rows = Vec::new();
3077
3078 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3079 let cursor = selection.head();
3080 let row = cursor.row;
3081
3082 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3083
3084 let newline = "\n".to_string();
3085 edits.push((start_of_line..start_of_line, newline));
3086
3087 rows.push(row + rows_inserted as u32);
3088 }
3089
3090 self.transact(cx, |editor, cx| {
3091 editor.edit(edits, cx);
3092
3093 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3094 let mut index = 0;
3095 s.move_cursors_with(|map, _, _| {
3096 let row = rows[index];
3097 index += 1;
3098
3099 let point = Point::new(row, 0);
3100 let boundary = map.next_line_boundary(point).1;
3101 let clipped = map.clip_point(boundary, Bias::Left);
3102
3103 (clipped, SelectionGoal::None)
3104 });
3105 });
3106
3107 let mut indent_edits = Vec::new();
3108 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3109 for row in rows {
3110 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3111 for (row, indent) in indents {
3112 if indent.len == 0 {
3113 continue;
3114 }
3115
3116 let text = match indent.kind {
3117 IndentKind::Space => " ".repeat(indent.len as usize),
3118 IndentKind::Tab => "\t".repeat(indent.len as usize),
3119 };
3120 let point = Point::new(row.0, 0);
3121 indent_edits.push((point..point, text));
3122 }
3123 }
3124 editor.edit(indent_edits, cx);
3125 });
3126 }
3127
3128 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3129 let buffer = self.buffer.read(cx);
3130 let snapshot = buffer.snapshot(cx);
3131
3132 let mut edits = Vec::new();
3133 let mut rows = Vec::new();
3134 let mut rows_inserted = 0;
3135
3136 for selection in self.selections.all_adjusted(cx) {
3137 let cursor = selection.head();
3138 let row = cursor.row;
3139
3140 let point = Point::new(row + 1, 0);
3141 let start_of_line = snapshot.clip_point(point, Bias::Left);
3142
3143 let newline = "\n".to_string();
3144 edits.push((start_of_line..start_of_line, newline));
3145
3146 rows_inserted += 1;
3147 rows.push(row + rows_inserted);
3148 }
3149
3150 self.transact(cx, |editor, cx| {
3151 editor.edit(edits, cx);
3152
3153 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3154 let mut index = 0;
3155 s.move_cursors_with(|map, _, _| {
3156 let row = rows[index];
3157 index += 1;
3158
3159 let point = Point::new(row, 0);
3160 let boundary = map.next_line_boundary(point).1;
3161 let clipped = map.clip_point(boundary, Bias::Left);
3162
3163 (clipped, SelectionGoal::None)
3164 });
3165 });
3166
3167 let mut indent_edits = Vec::new();
3168 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3169 for row in rows {
3170 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3171 for (row, indent) in indents {
3172 if indent.len == 0 {
3173 continue;
3174 }
3175
3176 let text = match indent.kind {
3177 IndentKind::Space => " ".repeat(indent.len as usize),
3178 IndentKind::Tab => "\t".repeat(indent.len as usize),
3179 };
3180 let point = Point::new(row.0, 0);
3181 indent_edits.push((point..point, text));
3182 }
3183 }
3184 editor.edit(indent_edits, cx);
3185 });
3186 }
3187
3188 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3189 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3190 original_indent_columns: Vec::new(),
3191 });
3192 self.insert_with_autoindent_mode(text, autoindent, cx);
3193 }
3194
3195 fn insert_with_autoindent_mode(
3196 &mut self,
3197 text: &str,
3198 autoindent_mode: Option<AutoindentMode>,
3199 cx: &mut ViewContext<Self>,
3200 ) {
3201 if self.read_only(cx) {
3202 return;
3203 }
3204
3205 let text: Arc<str> = text.into();
3206 self.transact(cx, |this, cx| {
3207 let old_selections = this.selections.all_adjusted(cx);
3208 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3209 let anchors = {
3210 let snapshot = buffer.read(cx);
3211 old_selections
3212 .iter()
3213 .map(|s| {
3214 let anchor = snapshot.anchor_after(s.head());
3215 s.map(|_| anchor)
3216 })
3217 .collect::<Vec<_>>()
3218 };
3219 buffer.edit(
3220 old_selections
3221 .iter()
3222 .map(|s| (s.start..s.end, text.clone())),
3223 autoindent_mode,
3224 cx,
3225 );
3226 anchors
3227 });
3228
3229 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3230 s.select_anchors(selection_anchors);
3231 })
3232 });
3233 }
3234
3235 fn trigger_completion_on_input(
3236 &mut self,
3237 text: &str,
3238 trigger_in_words: bool,
3239 cx: &mut ViewContext<Self>,
3240 ) {
3241 if self.is_completion_trigger(text, trigger_in_words, cx) {
3242 self.show_completions(
3243 &ShowCompletions {
3244 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3245 },
3246 cx,
3247 );
3248 } else {
3249 self.hide_context_menu(cx);
3250 }
3251 }
3252
3253 fn is_completion_trigger(
3254 &self,
3255 text: &str,
3256 trigger_in_words: bool,
3257 cx: &mut ViewContext<Self>,
3258 ) -> bool {
3259 let position = self.selections.newest_anchor().head();
3260 let multibuffer = self.buffer.read(cx);
3261 let Some(buffer) = position
3262 .buffer_id
3263 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3264 else {
3265 return false;
3266 };
3267
3268 if let Some(completion_provider) = &self.completion_provider {
3269 completion_provider.is_completion_trigger(
3270 &buffer,
3271 position.text_anchor,
3272 text,
3273 trigger_in_words,
3274 cx,
3275 )
3276 } else {
3277 false
3278 }
3279 }
3280
3281 /// If any empty selections is touching the start of its innermost containing autoclose
3282 /// region, expand it to select the brackets.
3283 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3284 let selections = self.selections.all::<usize>(cx);
3285 let buffer = self.buffer.read(cx).read(cx);
3286 let new_selections = self
3287 .selections_with_autoclose_regions(selections, &buffer)
3288 .map(|(mut selection, region)| {
3289 if !selection.is_empty() {
3290 return selection;
3291 }
3292
3293 if let Some(region) = region {
3294 let mut range = region.range.to_offset(&buffer);
3295 if selection.start == range.start && range.start >= region.pair.start.len() {
3296 range.start -= region.pair.start.len();
3297 if buffer.contains_str_at(range.start, ®ion.pair.start)
3298 && buffer.contains_str_at(range.end, ®ion.pair.end)
3299 {
3300 range.end += region.pair.end.len();
3301 selection.start = range.start;
3302 selection.end = range.end;
3303
3304 return selection;
3305 }
3306 }
3307 }
3308
3309 let always_treat_brackets_as_autoclosed = buffer
3310 .settings_at(selection.start, cx)
3311 .always_treat_brackets_as_autoclosed;
3312
3313 if !always_treat_brackets_as_autoclosed {
3314 return selection;
3315 }
3316
3317 if let Some(scope) = buffer.language_scope_at(selection.start) {
3318 for (pair, enabled) in scope.brackets() {
3319 if !enabled || !pair.close {
3320 continue;
3321 }
3322
3323 if buffer.contains_str_at(selection.start, &pair.end) {
3324 let pair_start_len = pair.start.len();
3325 if buffer.contains_str_at(
3326 selection.start.saturating_sub(pair_start_len),
3327 &pair.start,
3328 ) {
3329 selection.start -= pair_start_len;
3330 selection.end += pair.end.len();
3331
3332 return selection;
3333 }
3334 }
3335 }
3336 }
3337
3338 selection
3339 })
3340 .collect();
3341
3342 drop(buffer);
3343 self.change_selections(None, cx, |selections| selections.select(new_selections));
3344 }
3345
3346 /// Iterate the given selections, and for each one, find the smallest surrounding
3347 /// autoclose region. This uses the ordering of the selections and the autoclose
3348 /// regions to avoid repeated comparisons.
3349 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3350 &'a self,
3351 selections: impl IntoIterator<Item = Selection<D>>,
3352 buffer: &'a MultiBufferSnapshot,
3353 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3354 let mut i = 0;
3355 let mut regions = self.autoclose_regions.as_slice();
3356 selections.into_iter().map(move |selection| {
3357 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3358
3359 let mut enclosing = None;
3360 while let Some(pair_state) = regions.get(i) {
3361 if pair_state.range.end.to_offset(buffer) < range.start {
3362 regions = ®ions[i + 1..];
3363 i = 0;
3364 } else if pair_state.range.start.to_offset(buffer) > range.end {
3365 break;
3366 } else {
3367 if pair_state.selection_id == selection.id {
3368 enclosing = Some(pair_state);
3369 }
3370 i += 1;
3371 }
3372 }
3373
3374 (selection, enclosing)
3375 })
3376 }
3377
3378 /// Remove any autoclose regions that no longer contain their selection.
3379 fn invalidate_autoclose_regions(
3380 &mut self,
3381 mut selections: &[Selection<Anchor>],
3382 buffer: &MultiBufferSnapshot,
3383 ) {
3384 self.autoclose_regions.retain(|state| {
3385 let mut i = 0;
3386 while let Some(selection) = selections.get(i) {
3387 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3388 selections = &selections[1..];
3389 continue;
3390 }
3391 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3392 break;
3393 }
3394 if selection.id == state.selection_id {
3395 return true;
3396 } else {
3397 i += 1;
3398 }
3399 }
3400 false
3401 });
3402 }
3403
3404 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3405 let offset = position.to_offset(buffer);
3406 let (word_range, kind) = buffer.surrounding_word(offset, true);
3407 if offset > word_range.start && kind == Some(CharKind::Word) {
3408 Some(
3409 buffer
3410 .text_for_range(word_range.start..offset)
3411 .collect::<String>(),
3412 )
3413 } else {
3414 None
3415 }
3416 }
3417
3418 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3419 self.refresh_inlay_hints(
3420 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3421 cx,
3422 );
3423 }
3424
3425 pub fn inlay_hints_enabled(&self) -> bool {
3426 self.inlay_hint_cache.enabled
3427 }
3428
3429 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3430 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
3431 return;
3432 }
3433
3434 let reason_description = reason.description();
3435 let ignore_debounce = matches!(
3436 reason,
3437 InlayHintRefreshReason::SettingsChange(_)
3438 | InlayHintRefreshReason::Toggle(_)
3439 | InlayHintRefreshReason::ExcerptsRemoved(_)
3440 );
3441 let (invalidate_cache, required_languages) = match reason {
3442 InlayHintRefreshReason::Toggle(enabled) => {
3443 self.inlay_hint_cache.enabled = enabled;
3444 if enabled {
3445 (InvalidationStrategy::RefreshRequested, None)
3446 } else {
3447 self.inlay_hint_cache.clear();
3448 self.splice_inlays(
3449 self.visible_inlay_hints(cx)
3450 .iter()
3451 .map(|inlay| inlay.id)
3452 .collect(),
3453 Vec::new(),
3454 cx,
3455 );
3456 return;
3457 }
3458 }
3459 InlayHintRefreshReason::SettingsChange(new_settings) => {
3460 match self.inlay_hint_cache.update_settings(
3461 &self.buffer,
3462 new_settings,
3463 self.visible_inlay_hints(cx),
3464 cx,
3465 ) {
3466 ControlFlow::Break(Some(InlaySplice {
3467 to_remove,
3468 to_insert,
3469 })) => {
3470 self.splice_inlays(to_remove, to_insert, cx);
3471 return;
3472 }
3473 ControlFlow::Break(None) => return,
3474 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3475 }
3476 }
3477 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3478 if let Some(InlaySplice {
3479 to_remove,
3480 to_insert,
3481 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3482 {
3483 self.splice_inlays(to_remove, to_insert, cx);
3484 }
3485 return;
3486 }
3487 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3488 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3489 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3490 }
3491 InlayHintRefreshReason::RefreshRequested => {
3492 (InvalidationStrategy::RefreshRequested, None)
3493 }
3494 };
3495
3496 if let Some(InlaySplice {
3497 to_remove,
3498 to_insert,
3499 }) = self.inlay_hint_cache.spawn_hint_refresh(
3500 reason_description,
3501 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3502 invalidate_cache,
3503 ignore_debounce,
3504 cx,
3505 ) {
3506 self.splice_inlays(to_remove, to_insert, cx);
3507 }
3508 }
3509
3510 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
3511 self.display_map
3512 .read(cx)
3513 .current_inlays()
3514 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3515 .cloned()
3516 .collect()
3517 }
3518
3519 pub fn excerpts_for_inlay_hints_query(
3520 &self,
3521 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3522 cx: &mut ViewContext<Editor>,
3523 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3524 let Some(project) = self.project.as_ref() else {
3525 return HashMap::default();
3526 };
3527 let project = project.read(cx);
3528 let multi_buffer = self.buffer().read(cx);
3529 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3530 let multi_buffer_visible_start = self
3531 .scroll_manager
3532 .anchor()
3533 .anchor
3534 .to_point(&multi_buffer_snapshot);
3535 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3536 multi_buffer_visible_start
3537 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3538 Bias::Left,
3539 );
3540 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3541 multi_buffer
3542 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
3543 .into_iter()
3544 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3545 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
3546 let buffer = buffer_handle.read(cx);
3547 let buffer_file = project::File::from_dyn(buffer.file())?;
3548 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3549 let worktree_entry = buffer_worktree
3550 .read(cx)
3551 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3552 if worktree_entry.is_ignored {
3553 return None;
3554 }
3555
3556 let language = buffer.language()?;
3557 if let Some(restrict_to_languages) = restrict_to_languages {
3558 if !restrict_to_languages.contains(language) {
3559 return None;
3560 }
3561 }
3562 Some((
3563 excerpt_id,
3564 (
3565 buffer_handle,
3566 buffer.version().clone(),
3567 excerpt_visible_range,
3568 ),
3569 ))
3570 })
3571 .collect()
3572 }
3573
3574 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3575 TextLayoutDetails {
3576 text_system: cx.text_system().clone(),
3577 editor_style: self.style.clone().unwrap(),
3578 rem_size: cx.rem_size(),
3579 scroll_anchor: self.scroll_manager.anchor(),
3580 visible_rows: self.visible_line_count(),
3581 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
3582 }
3583 }
3584
3585 fn splice_inlays(
3586 &self,
3587 to_remove: Vec<InlayId>,
3588 to_insert: Vec<Inlay>,
3589 cx: &mut ViewContext<Self>,
3590 ) {
3591 self.display_map.update(cx, |display_map, cx| {
3592 display_map.splice_inlays(to_remove, to_insert, cx)
3593 });
3594 cx.notify();
3595 }
3596
3597 fn trigger_on_type_formatting(
3598 &self,
3599 input: String,
3600 cx: &mut ViewContext<Self>,
3601 ) -> Option<Task<Result<()>>> {
3602 if input.len() != 1 {
3603 return None;
3604 }
3605
3606 let project = self.project.as_ref()?;
3607 let position = self.selections.newest_anchor().head();
3608 let (buffer, buffer_position) = self
3609 .buffer
3610 .read(cx)
3611 .text_anchor_for_position(position, cx)?;
3612
3613 let settings = language_settings::language_settings(
3614 buffer
3615 .read(cx)
3616 .language_at(buffer_position)
3617 .map(|l| l.name()),
3618 buffer.read(cx).file(),
3619 cx,
3620 );
3621 if !settings.use_on_type_format {
3622 return None;
3623 }
3624
3625 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3626 // hence we do LSP request & edit on host side only — add formats to host's history.
3627 let push_to_lsp_host_history = true;
3628 // If this is not the host, append its history with new edits.
3629 let push_to_client_history = project.read(cx).is_via_collab();
3630
3631 let on_type_formatting = project.update(cx, |project, cx| {
3632 project.on_type_format(
3633 buffer.clone(),
3634 buffer_position,
3635 input,
3636 push_to_lsp_host_history,
3637 cx,
3638 )
3639 });
3640 Some(cx.spawn(|editor, mut cx| async move {
3641 if let Some(transaction) = on_type_formatting.await? {
3642 if push_to_client_history {
3643 buffer
3644 .update(&mut cx, |buffer, _| {
3645 buffer.push_transaction(transaction, Instant::now());
3646 })
3647 .ok();
3648 }
3649 editor.update(&mut cx, |editor, cx| {
3650 editor.refresh_document_highlights(cx);
3651 })?;
3652 }
3653 Ok(())
3654 }))
3655 }
3656
3657 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
3658 if self.pending_rename.is_some() {
3659 return;
3660 }
3661
3662 let Some(provider) = self.completion_provider.as_ref() else {
3663 return;
3664 };
3665
3666 if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
3667 return;
3668 }
3669
3670 let position = self.selections.newest_anchor().head();
3671 let (buffer, buffer_position) =
3672 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
3673 output
3674 } else {
3675 return;
3676 };
3677 let show_completion_documentation = buffer
3678 .read(cx)
3679 .snapshot()
3680 .settings_at(buffer_position, cx)
3681 .show_completion_documentation;
3682
3683 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
3684
3685 let aside_was_displayed = match self.context_menu.borrow().deref() {
3686 Some(CodeContextMenu::Completions(menu)) => menu.aside_was_displayed.get(),
3687 _ => false,
3688 };
3689 let trigger_kind = match &options.trigger {
3690 Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
3691 CompletionTriggerKind::TRIGGER_CHARACTER
3692 }
3693 _ => CompletionTriggerKind::INVOKED,
3694 };
3695 let completion_context = CompletionContext {
3696 trigger_character: options.trigger.as_ref().and_then(|trigger| {
3697 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
3698 Some(String::from(trigger))
3699 } else {
3700 None
3701 }
3702 }),
3703 trigger_kind,
3704 };
3705 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
3706 let sort_completions = provider.sort_completions();
3707
3708 let id = post_inc(&mut self.next_completion_id);
3709 let task = cx.spawn(|editor, mut cx| {
3710 async move {
3711 editor.update(&mut cx, |this, _| {
3712 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3713 })?;
3714 let completions = completions.await.log_err();
3715 let menu = if let Some(completions) = completions {
3716 let mut menu = CompletionsMenu::new(
3717 id,
3718 sort_completions,
3719 show_completion_documentation,
3720 position,
3721 buffer.clone(),
3722 completions.into(),
3723 aside_was_displayed,
3724 );
3725
3726 menu.filter(query.as_deref(), cx.background_executor().clone())
3727 .await;
3728
3729 menu.visible().then_some(menu)
3730 } else {
3731 None
3732 };
3733
3734 editor.update(&mut cx, |editor, cx| {
3735 match editor.context_menu.borrow().as_ref() {
3736 None => {}
3737 Some(CodeContextMenu::Completions(prev_menu)) => {
3738 if prev_menu.id > id {
3739 return;
3740 }
3741 }
3742 _ => return,
3743 }
3744
3745 if editor.focus_handle.is_focused(cx) && menu.is_some() {
3746 let mut menu = menu.unwrap();
3747 menu.resolve_selected_completion(editor.completion_provider.as_deref(), cx);
3748
3749 if let Some(hint) = editor.inline_completion_menu_hint(cx) {
3750 editor.hide_active_inline_completion(cx);
3751 menu.show_inline_completion_hint(hint);
3752 }
3753
3754 *editor.context_menu.borrow_mut() =
3755 Some(CodeContextMenu::Completions(menu));
3756
3757 cx.notify();
3758 } else if editor.completion_tasks.len() <= 1 {
3759 // If there are no more completion tasks and the last menu was
3760 // empty, we should hide it. If it was already hidden, we should
3761 // also show the copilot completion when available.
3762 editor.hide_context_menu(cx);
3763 }
3764 })?;
3765
3766 Ok::<_, anyhow::Error>(())
3767 }
3768 .log_err()
3769 });
3770
3771 self.completion_tasks.push((id, task));
3772 }
3773
3774 pub fn confirm_completion(
3775 &mut self,
3776 action: &ConfirmCompletion,
3777 cx: &mut ViewContext<Self>,
3778 ) -> Option<Task<Result<()>>> {
3779 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
3780 }
3781
3782 pub fn compose_completion(
3783 &mut self,
3784 action: &ComposeCompletion,
3785 cx: &mut ViewContext<Self>,
3786 ) -> Option<Task<Result<()>>> {
3787 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
3788 }
3789
3790 fn do_completion(
3791 &mut self,
3792 item_ix: Option<usize>,
3793 intent: CompletionIntent,
3794 cx: &mut ViewContext<Editor>,
3795 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
3796 use language::ToOffset as _;
3797
3798 let completions_menu =
3799 if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3800 menu
3801 } else {
3802 return None;
3803 };
3804
3805 let mat = completions_menu
3806 .entries
3807 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
3808
3809 let mat = match mat {
3810 CompletionEntry::InlineCompletionHint { .. } => {
3811 self.accept_inline_completion(&AcceptInlineCompletion, cx);
3812 cx.stop_propagation();
3813 return Some(Task::ready(Ok(())));
3814 }
3815 CompletionEntry::Match(mat) => {
3816 self.discard_inline_completion(true, cx);
3817 mat
3818 }
3819 };
3820
3821 let buffer_handle = completions_menu.buffer;
3822 let completions = completions_menu.completions.borrow_mut();
3823 let completion = completions.get(mat.candidate_id)?;
3824 cx.stop_propagation();
3825
3826 let snippet;
3827 let text;
3828
3829 if completion.is_snippet() {
3830 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3831 text = snippet.as_ref().unwrap().text.clone();
3832 } else {
3833 snippet = None;
3834 text = completion.new_text.clone();
3835 };
3836 let selections = self.selections.all::<usize>(cx);
3837 let buffer = buffer_handle.read(cx);
3838 let old_range = completion.old_range.to_offset(buffer);
3839 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3840
3841 let newest_selection = self.selections.newest_anchor();
3842 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3843 return None;
3844 }
3845
3846 let lookbehind = newest_selection
3847 .start
3848 .text_anchor
3849 .to_offset(buffer)
3850 .saturating_sub(old_range.start);
3851 let lookahead = old_range
3852 .end
3853 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3854 let mut common_prefix_len = old_text
3855 .bytes()
3856 .zip(text.bytes())
3857 .take_while(|(a, b)| a == b)
3858 .count();
3859
3860 let snapshot = self.buffer.read(cx).snapshot(cx);
3861 let mut range_to_replace: Option<Range<isize>> = None;
3862 let mut ranges = Vec::new();
3863 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3864 for selection in &selections {
3865 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3866 let start = selection.start.saturating_sub(lookbehind);
3867 let end = selection.end + lookahead;
3868 if selection.id == newest_selection.id {
3869 range_to_replace = Some(
3870 ((start + common_prefix_len) as isize - selection.start as isize)
3871 ..(end as isize - selection.start as isize),
3872 );
3873 }
3874 ranges.push(start + common_prefix_len..end);
3875 } else {
3876 common_prefix_len = 0;
3877 ranges.clear();
3878 ranges.extend(selections.iter().map(|s| {
3879 if s.id == newest_selection.id {
3880 range_to_replace = Some(
3881 old_range.start.to_offset_utf16(&snapshot).0 as isize
3882 - selection.start as isize
3883 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3884 - selection.start as isize,
3885 );
3886 old_range.clone()
3887 } else {
3888 s.start..s.end
3889 }
3890 }));
3891 break;
3892 }
3893 if !self.linked_edit_ranges.is_empty() {
3894 let start_anchor = snapshot.anchor_before(selection.head());
3895 let end_anchor = snapshot.anchor_after(selection.tail());
3896 if let Some(ranges) = self
3897 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
3898 {
3899 for (buffer, edits) in ranges {
3900 linked_edits.entry(buffer.clone()).or_default().extend(
3901 edits
3902 .into_iter()
3903 .map(|range| (range, text[common_prefix_len..].to_owned())),
3904 );
3905 }
3906 }
3907 }
3908 }
3909 let text = &text[common_prefix_len..];
3910
3911 cx.emit(EditorEvent::InputHandled {
3912 utf16_range_to_replace: range_to_replace,
3913 text: text.into(),
3914 });
3915
3916 self.transact(cx, |this, cx| {
3917 if let Some(mut snippet) = snippet {
3918 snippet.text = text.to_string();
3919 for tabstop in snippet
3920 .tabstops
3921 .iter_mut()
3922 .flat_map(|tabstop| tabstop.ranges.iter_mut())
3923 {
3924 tabstop.start -= common_prefix_len as isize;
3925 tabstop.end -= common_prefix_len as isize;
3926 }
3927
3928 this.insert_snippet(&ranges, snippet, cx).log_err();
3929 } else {
3930 this.buffer.update(cx, |buffer, cx| {
3931 buffer.edit(
3932 ranges.iter().map(|range| (range.clone(), text)),
3933 this.autoindent_mode.clone(),
3934 cx,
3935 );
3936 });
3937 }
3938 for (buffer, edits) in linked_edits {
3939 buffer.update(cx, |buffer, cx| {
3940 let snapshot = buffer.snapshot();
3941 let edits = edits
3942 .into_iter()
3943 .map(|(range, text)| {
3944 use text::ToPoint as TP;
3945 let end_point = TP::to_point(&range.end, &snapshot);
3946 let start_point = TP::to_point(&range.start, &snapshot);
3947 (start_point..end_point, text)
3948 })
3949 .sorted_by_key(|(range, _)| range.start)
3950 .collect::<Vec<_>>();
3951 buffer.edit(edits, None, cx);
3952 })
3953 }
3954
3955 this.refresh_inline_completion(true, false, cx);
3956 });
3957
3958 let show_new_completions_on_confirm = completion
3959 .confirm
3960 .as_ref()
3961 .map_or(false, |confirm| confirm(intent, cx));
3962 if show_new_completions_on_confirm {
3963 self.show_completions(&ShowCompletions { trigger: None }, cx);
3964 }
3965
3966 let provider = self.completion_provider.as_ref()?;
3967 let apply_edits = provider.apply_additional_edits_for_completion(
3968 buffer_handle,
3969 completion.clone(),
3970 true,
3971 cx,
3972 );
3973
3974 let editor_settings = EditorSettings::get_global(cx);
3975 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
3976 // After the code completion is finished, users often want to know what signatures are needed.
3977 // so we should automatically call signature_help
3978 self.show_signature_help(&ShowSignatureHelp, cx);
3979 }
3980
3981 Some(cx.foreground_executor().spawn(async move {
3982 apply_edits.await?;
3983 Ok(())
3984 }))
3985 }
3986
3987 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
3988 let mut context_menu = self.context_menu.borrow_mut();
3989 if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
3990 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
3991 // Toggle if we're selecting the same one
3992 *context_menu = None;
3993 cx.notify();
3994 return;
3995 } else {
3996 // Otherwise, clear it and start a new one
3997 *context_menu = None;
3998 cx.notify();
3999 }
4000 }
4001 drop(context_menu);
4002 let snapshot = self.snapshot(cx);
4003 let deployed_from_indicator = action.deployed_from_indicator;
4004 let mut task = self.code_actions_task.take();
4005 let action = action.clone();
4006 cx.spawn(|editor, mut cx| async move {
4007 while let Some(prev_task) = task {
4008 prev_task.await.log_err();
4009 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4010 }
4011
4012 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4013 if editor.focus_handle.is_focused(cx) {
4014 let multibuffer_point = action
4015 .deployed_from_indicator
4016 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4017 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4018 let (buffer, buffer_row) = snapshot
4019 .buffer_snapshot
4020 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4021 .and_then(|(buffer_snapshot, range)| {
4022 editor
4023 .buffer
4024 .read(cx)
4025 .buffer(buffer_snapshot.remote_id())
4026 .map(|buffer| (buffer, range.start.row))
4027 })?;
4028 let (_, code_actions) = editor
4029 .available_code_actions
4030 .clone()
4031 .and_then(|(location, code_actions)| {
4032 let snapshot = location.buffer.read(cx).snapshot();
4033 let point_range = location.range.to_point(&snapshot);
4034 let point_range = point_range.start.row..=point_range.end.row;
4035 if point_range.contains(&buffer_row) {
4036 Some((location, code_actions))
4037 } else {
4038 None
4039 }
4040 })
4041 .unzip();
4042 let buffer_id = buffer.read(cx).remote_id();
4043 let tasks = editor
4044 .tasks
4045 .get(&(buffer_id, buffer_row))
4046 .map(|t| Arc::new(t.to_owned()));
4047 if tasks.is_none() && code_actions.is_none() {
4048 return None;
4049 }
4050
4051 editor.completion_tasks.clear();
4052 editor.discard_inline_completion(false, cx);
4053 let task_context =
4054 tasks
4055 .as_ref()
4056 .zip(editor.project.clone())
4057 .map(|(tasks, project)| {
4058 Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
4059 });
4060
4061 Some(cx.spawn(|editor, mut cx| async move {
4062 let task_context = match task_context {
4063 Some(task_context) => task_context.await,
4064 None => None,
4065 };
4066 let resolved_tasks =
4067 tasks.zip(task_context).map(|(tasks, task_context)| {
4068 Rc::new(ResolvedTasks {
4069 templates: tasks.resolve(&task_context).collect(),
4070 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4071 multibuffer_point.row,
4072 tasks.column,
4073 )),
4074 })
4075 });
4076 let spawn_straight_away = resolved_tasks
4077 .as_ref()
4078 .map_or(false, |tasks| tasks.templates.len() == 1)
4079 && code_actions
4080 .as_ref()
4081 .map_or(true, |actions| actions.is_empty());
4082 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4083 *editor.context_menu.borrow_mut() =
4084 Some(CodeContextMenu::CodeActions(CodeActionsMenu {
4085 buffer,
4086 actions: CodeActionContents {
4087 tasks: resolved_tasks,
4088 actions: code_actions,
4089 },
4090 selected_item: Default::default(),
4091 scroll_handle: UniformListScrollHandle::default(),
4092 deployed_from_indicator,
4093 }));
4094 if spawn_straight_away {
4095 if let Some(task) = editor.confirm_code_action(
4096 &ConfirmCodeAction { item_ix: Some(0) },
4097 cx,
4098 ) {
4099 cx.notify();
4100 return task;
4101 }
4102 }
4103 cx.notify();
4104 Task::ready(Ok(()))
4105 }) {
4106 task.await
4107 } else {
4108 Ok(())
4109 }
4110 }))
4111 } else {
4112 Some(Task::ready(Ok(())))
4113 }
4114 })?;
4115 if let Some(task) = spawned_test_task {
4116 task.await?;
4117 }
4118
4119 Ok::<_, anyhow::Error>(())
4120 })
4121 .detach_and_log_err(cx);
4122 }
4123
4124 pub fn confirm_code_action(
4125 &mut self,
4126 action: &ConfirmCodeAction,
4127 cx: &mut ViewContext<Self>,
4128 ) -> Option<Task<Result<()>>> {
4129 let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4130 menu
4131 } else {
4132 return None;
4133 };
4134 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4135 let action = actions_menu.actions.get(action_ix)?;
4136 let title = action.label();
4137 let buffer = actions_menu.buffer;
4138 let workspace = self.workspace()?;
4139
4140 match action {
4141 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4142 workspace.update(cx, |workspace, cx| {
4143 workspace::tasks::schedule_resolved_task(
4144 workspace,
4145 task_source_kind,
4146 resolved_task,
4147 false,
4148 cx,
4149 );
4150
4151 Some(Task::ready(Ok(())))
4152 })
4153 }
4154 CodeActionsItem::CodeAction {
4155 excerpt_id,
4156 action,
4157 provider,
4158 } => {
4159 let apply_code_action =
4160 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4161 let workspace = workspace.downgrade();
4162 Some(cx.spawn(|editor, cx| async move {
4163 let project_transaction = apply_code_action.await?;
4164 Self::open_project_transaction(
4165 &editor,
4166 workspace,
4167 project_transaction,
4168 title,
4169 cx,
4170 )
4171 .await
4172 }))
4173 }
4174 }
4175 }
4176
4177 pub async fn open_project_transaction(
4178 this: &WeakView<Editor>,
4179 workspace: WeakView<Workspace>,
4180 transaction: ProjectTransaction,
4181 title: String,
4182 mut cx: AsyncWindowContext,
4183 ) -> Result<()> {
4184 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4185 cx.update(|cx| {
4186 entries.sort_unstable_by_key(|(buffer, _)| {
4187 buffer.read(cx).file().map(|f| f.path().clone())
4188 });
4189 })?;
4190
4191 // If the project transaction's edits are all contained within this editor, then
4192 // avoid opening a new editor to display them.
4193
4194 if let Some((buffer, transaction)) = entries.first() {
4195 if entries.len() == 1 {
4196 let excerpt = this.update(&mut cx, |editor, cx| {
4197 editor
4198 .buffer()
4199 .read(cx)
4200 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4201 })?;
4202 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4203 if excerpted_buffer == *buffer {
4204 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4205 let excerpt_range = excerpt_range.to_offset(buffer);
4206 buffer
4207 .edited_ranges_for_transaction::<usize>(transaction)
4208 .all(|range| {
4209 excerpt_range.start <= range.start
4210 && excerpt_range.end >= range.end
4211 })
4212 })?;
4213
4214 if all_edits_within_excerpt {
4215 return Ok(());
4216 }
4217 }
4218 }
4219 }
4220 } else {
4221 return Ok(());
4222 }
4223
4224 let mut ranges_to_highlight = Vec::new();
4225 let excerpt_buffer = cx.new_model(|cx| {
4226 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4227 for (buffer_handle, transaction) in &entries {
4228 let buffer = buffer_handle.read(cx);
4229 ranges_to_highlight.extend(
4230 multibuffer.push_excerpts_with_context_lines(
4231 buffer_handle.clone(),
4232 buffer
4233 .edited_ranges_for_transaction::<usize>(transaction)
4234 .collect(),
4235 DEFAULT_MULTIBUFFER_CONTEXT,
4236 cx,
4237 ),
4238 );
4239 }
4240 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4241 multibuffer
4242 })?;
4243
4244 workspace.update(&mut cx, |workspace, cx| {
4245 let project = workspace.project().clone();
4246 let editor =
4247 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4248 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4249 editor.update(cx, |editor, cx| {
4250 editor.highlight_background::<Self>(
4251 &ranges_to_highlight,
4252 |theme| theme.editor_highlighted_line_background,
4253 cx,
4254 );
4255 });
4256 })?;
4257
4258 Ok(())
4259 }
4260
4261 pub fn clear_code_action_providers(&mut self) {
4262 self.code_action_providers.clear();
4263 self.available_code_actions.take();
4264 }
4265
4266 pub fn push_code_action_provider(
4267 &mut self,
4268 provider: Rc<dyn CodeActionProvider>,
4269 cx: &mut ViewContext<Self>,
4270 ) {
4271 self.code_action_providers.push(provider);
4272 self.refresh_code_actions(cx);
4273 }
4274
4275 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4276 let buffer = self.buffer.read(cx);
4277 let newest_selection = self.selections.newest_anchor().clone();
4278 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4279 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4280 if start_buffer != end_buffer {
4281 return None;
4282 }
4283
4284 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4285 cx.background_executor()
4286 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4287 .await;
4288
4289 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4290 let providers = this.code_action_providers.clone();
4291 let tasks = this
4292 .code_action_providers
4293 .iter()
4294 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4295 .collect::<Vec<_>>();
4296 (providers, tasks)
4297 })?;
4298
4299 let mut actions = Vec::new();
4300 for (provider, provider_actions) in
4301 providers.into_iter().zip(future::join_all(tasks).await)
4302 {
4303 if let Some(provider_actions) = provider_actions.log_err() {
4304 actions.extend(provider_actions.into_iter().map(|action| {
4305 AvailableCodeAction {
4306 excerpt_id: newest_selection.start.excerpt_id,
4307 action,
4308 provider: provider.clone(),
4309 }
4310 }));
4311 }
4312 }
4313
4314 this.update(&mut cx, |this, cx| {
4315 this.available_code_actions = if actions.is_empty() {
4316 None
4317 } else {
4318 Some((
4319 Location {
4320 buffer: start_buffer,
4321 range: start..end,
4322 },
4323 actions.into(),
4324 ))
4325 };
4326 cx.notify();
4327 })
4328 }));
4329 None
4330 }
4331
4332 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4333 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4334 self.show_git_blame_inline = false;
4335
4336 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4337 cx.background_executor().timer(delay).await;
4338
4339 this.update(&mut cx, |this, cx| {
4340 this.show_git_blame_inline = true;
4341 cx.notify();
4342 })
4343 .log_err();
4344 }));
4345 }
4346 }
4347
4348 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4349 if self.pending_rename.is_some() {
4350 return None;
4351 }
4352
4353 let provider = self.semantics_provider.clone()?;
4354 let buffer = self.buffer.read(cx);
4355 let newest_selection = self.selections.newest_anchor().clone();
4356 let cursor_position = newest_selection.head();
4357 let (cursor_buffer, cursor_buffer_position) =
4358 buffer.text_anchor_for_position(cursor_position, cx)?;
4359 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4360 if cursor_buffer != tail_buffer {
4361 return None;
4362 }
4363 let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
4364 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4365 cx.background_executor()
4366 .timer(Duration::from_millis(debounce))
4367 .await;
4368
4369 let highlights = if let Some(highlights) = cx
4370 .update(|cx| {
4371 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4372 })
4373 .ok()
4374 .flatten()
4375 {
4376 highlights.await.log_err()
4377 } else {
4378 None
4379 };
4380
4381 if let Some(highlights) = highlights {
4382 this.update(&mut cx, |this, cx| {
4383 if this.pending_rename.is_some() {
4384 return;
4385 }
4386
4387 let buffer_id = cursor_position.buffer_id;
4388 let buffer = this.buffer.read(cx);
4389 if !buffer
4390 .text_anchor_for_position(cursor_position, cx)
4391 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4392 {
4393 return;
4394 }
4395
4396 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4397 let mut write_ranges = Vec::new();
4398 let mut read_ranges = Vec::new();
4399 for highlight in highlights {
4400 for (excerpt_id, excerpt_range) in
4401 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4402 {
4403 let start = highlight
4404 .range
4405 .start
4406 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4407 let end = highlight
4408 .range
4409 .end
4410 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4411 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4412 continue;
4413 }
4414
4415 let range = Anchor {
4416 buffer_id,
4417 excerpt_id,
4418 text_anchor: start,
4419 }..Anchor {
4420 buffer_id,
4421 excerpt_id,
4422 text_anchor: end,
4423 };
4424 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4425 write_ranges.push(range);
4426 } else {
4427 read_ranges.push(range);
4428 }
4429 }
4430 }
4431
4432 this.highlight_background::<DocumentHighlightRead>(
4433 &read_ranges,
4434 |theme| theme.editor_document_highlight_read_background,
4435 cx,
4436 );
4437 this.highlight_background::<DocumentHighlightWrite>(
4438 &write_ranges,
4439 |theme| theme.editor_document_highlight_write_background,
4440 cx,
4441 );
4442 cx.notify();
4443 })
4444 .log_err();
4445 }
4446 }));
4447 None
4448 }
4449
4450 pub fn refresh_inline_completion(
4451 &mut self,
4452 debounce: bool,
4453 user_requested: bool,
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
4461 if !user_requested
4462 && (!self.enable_inline_completions
4463 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4464 || !self.is_focused(cx))
4465 {
4466 self.discard_inline_completion(false, cx);
4467 return None;
4468 }
4469
4470 self.update_visible_inline_completion(cx);
4471 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4472 Some(())
4473 }
4474
4475 fn cycle_inline_completion(
4476 &mut self,
4477 direction: Direction,
4478 cx: &mut ViewContext<Self>,
4479 ) -> Option<()> {
4480 let provider = self.inline_completion_provider()?;
4481 let cursor = self.selections.newest_anchor().head();
4482 let (buffer, cursor_buffer_position) =
4483 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4484 if !self.enable_inline_completions
4485 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
4486 {
4487 return None;
4488 }
4489
4490 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4491 self.update_visible_inline_completion(cx);
4492
4493 Some(())
4494 }
4495
4496 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4497 if !self.has_active_inline_completion() {
4498 self.refresh_inline_completion(false, true, cx);
4499 return;
4500 }
4501
4502 self.update_visible_inline_completion(cx);
4503 }
4504
4505 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4506 self.show_cursor_names(cx);
4507 }
4508
4509 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4510 self.show_cursor_names = true;
4511 cx.notify();
4512 cx.spawn(|this, mut cx| async move {
4513 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4514 this.update(&mut cx, |this, cx| {
4515 this.show_cursor_names = false;
4516 cx.notify()
4517 })
4518 .ok()
4519 })
4520 .detach();
4521 }
4522
4523 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4524 if self.has_active_inline_completion() {
4525 self.cycle_inline_completion(Direction::Next, cx);
4526 } else {
4527 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4528 if is_copilot_disabled {
4529 cx.propagate();
4530 }
4531 }
4532 }
4533
4534 pub fn previous_inline_completion(
4535 &mut self,
4536 _: &PreviousInlineCompletion,
4537 cx: &mut ViewContext<Self>,
4538 ) {
4539 if self.has_active_inline_completion() {
4540 self.cycle_inline_completion(Direction::Prev, cx);
4541 } else {
4542 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4543 if is_copilot_disabled {
4544 cx.propagate();
4545 }
4546 }
4547 }
4548
4549 pub fn accept_inline_completion(
4550 &mut self,
4551 _: &AcceptInlineCompletion,
4552 cx: &mut ViewContext<Self>,
4553 ) {
4554 self.hide_context_menu(cx);
4555
4556 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4557 return;
4558 };
4559
4560 self.report_inline_completion_event(true, cx);
4561
4562 match &active_inline_completion.completion {
4563 InlineCompletion::Move(position) => {
4564 let position = *position;
4565 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4566 selections.select_anchor_ranges([position..position]);
4567 });
4568 }
4569 InlineCompletion::Edit(edits) => {
4570 if let Some(provider) = self.inline_completion_provider() {
4571 provider.accept(cx);
4572 }
4573
4574 let snapshot = self.buffer.read(cx).snapshot(cx);
4575 let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
4576
4577 self.buffer.update(cx, |buffer, cx| {
4578 buffer.edit(edits.iter().cloned(), None, cx)
4579 });
4580
4581 self.change_selections(None, cx, |s| {
4582 s.select_anchor_ranges([last_edit_end..last_edit_end])
4583 });
4584
4585 self.update_visible_inline_completion(cx);
4586 if self.active_inline_completion.is_none() {
4587 self.refresh_inline_completion(true, true, cx);
4588 }
4589
4590 cx.notify();
4591 }
4592 }
4593 }
4594
4595 pub fn accept_partial_inline_completion(
4596 &mut self,
4597 _: &AcceptPartialInlineCompletion,
4598 cx: &mut ViewContext<Self>,
4599 ) {
4600 let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
4601 return;
4602 };
4603 if self.selections.count() != 1 {
4604 return;
4605 }
4606
4607 self.report_inline_completion_event(true, cx);
4608
4609 match &active_inline_completion.completion {
4610 InlineCompletion::Move(position) => {
4611 let position = *position;
4612 self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
4613 selections.select_anchor_ranges([position..position]);
4614 });
4615 }
4616 InlineCompletion::Edit(edits) => {
4617 if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
4618 let text = edits[0].1.as_str();
4619 let mut partial_completion = text
4620 .chars()
4621 .by_ref()
4622 .take_while(|c| c.is_alphabetic())
4623 .collect::<String>();
4624 if partial_completion.is_empty() {
4625 partial_completion = text
4626 .chars()
4627 .by_ref()
4628 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
4629 .collect::<String>();
4630 }
4631
4632 cx.emit(EditorEvent::InputHandled {
4633 utf16_range_to_replace: None,
4634 text: partial_completion.clone().into(),
4635 });
4636
4637 self.insert_with_autoindent_mode(&partial_completion, None, cx);
4638
4639 self.refresh_inline_completion(true, true, cx);
4640 cx.notify();
4641 }
4642 }
4643 }
4644 }
4645
4646 fn discard_inline_completion(
4647 &mut self,
4648 should_report_inline_completion_event: bool,
4649 cx: &mut ViewContext<Self>,
4650 ) -> bool {
4651 if should_report_inline_completion_event {
4652 self.report_inline_completion_event(false, cx);
4653 }
4654
4655 if let Some(provider) = self.inline_completion_provider() {
4656 provider.discard(cx);
4657 }
4658
4659 self.take_active_inline_completion(cx).is_some()
4660 }
4661
4662 fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
4663 let Some(provider) = self.inline_completion_provider() else {
4664 return;
4665 };
4666 let Some(project) = self.project.as_ref() else {
4667 return;
4668 };
4669 let Some((_, buffer, _)) = self
4670 .buffer
4671 .read(cx)
4672 .excerpt_containing(self.selections.newest_anchor().head(), cx)
4673 else {
4674 return;
4675 };
4676
4677 let project = project.read(cx);
4678 let extension = buffer
4679 .read(cx)
4680 .file()
4681 .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
4682 project.client().telemetry().report_inline_completion_event(
4683 provider.name().into(),
4684 accepted,
4685 extension,
4686 );
4687 }
4688
4689 pub fn has_active_inline_completion(&self) -> bool {
4690 self.active_inline_completion.is_some()
4691 }
4692
4693 fn take_active_inline_completion(
4694 &mut self,
4695 cx: &mut ViewContext<Self>,
4696 ) -> Option<InlineCompletion> {
4697 let active_inline_completion = self.active_inline_completion.take()?;
4698 self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
4699 self.clear_highlights::<InlineCompletionHighlight>(cx);
4700 Some(active_inline_completion.completion)
4701 }
4702
4703 fn hide_active_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
4704 if let Some(active_inline_completion) = self.active_inline_completion.as_ref() {
4705 self.splice_inlays(
4706 active_inline_completion.inlay_ids.clone(),
4707 Default::default(),
4708 cx,
4709 );
4710 self.clear_highlights::<InlineCompletionHighlight>(cx);
4711 }
4712 }
4713
4714 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4715 let selection = self.selections.newest_anchor();
4716 let cursor = selection.head();
4717 let multibuffer = self.buffer.read(cx).snapshot(cx);
4718 let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
4719 let excerpt_id = cursor.excerpt_id;
4720
4721 if !offset_selection.is_empty()
4722 || self
4723 .active_inline_completion
4724 .as_ref()
4725 .map_or(false, |completion| {
4726 let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
4727 let invalidation_range = invalidation_range.start..=invalidation_range.end;
4728 !invalidation_range.contains(&offset_selection.head())
4729 })
4730 {
4731 self.discard_inline_completion(false, cx);
4732 return None;
4733 }
4734
4735 self.take_active_inline_completion(cx);
4736 let provider = self.inline_completion_provider()?;
4737
4738 let (buffer, cursor_buffer_position) =
4739 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4740
4741 let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
4742 let edits = completion
4743 .edits
4744 .into_iter()
4745 .map(|(range, new_text)| {
4746 (
4747 multibuffer
4748 .anchor_in_excerpt(excerpt_id, range.start)
4749 .unwrap()
4750 ..multibuffer
4751 .anchor_in_excerpt(excerpt_id, range.end)
4752 .unwrap(),
4753 new_text,
4754 )
4755 })
4756 .collect::<Vec<_>>();
4757 if edits.is_empty() {
4758 return None;
4759 }
4760
4761 let first_edit_start = edits.first().unwrap().0.start;
4762 let edit_start_row = first_edit_start
4763 .to_point(&multibuffer)
4764 .row
4765 .saturating_sub(2);
4766
4767 let last_edit_end = edits.last().unwrap().0.end;
4768 let edit_end_row = cmp::min(
4769 multibuffer.max_point().row,
4770 last_edit_end.to_point(&multibuffer).row + 2,
4771 );
4772
4773 let cursor_row = cursor.to_point(&multibuffer).row;
4774
4775 let mut inlay_ids = Vec::new();
4776 let invalidation_row_range;
4777 let completion;
4778 if cursor_row < edit_start_row {
4779 invalidation_row_range = cursor_row..edit_end_row;
4780 completion = InlineCompletion::Move(first_edit_start);
4781 } else if cursor_row > edit_end_row {
4782 invalidation_row_range = edit_start_row..cursor_row;
4783 completion = InlineCompletion::Move(first_edit_start);
4784 } else {
4785 if !self.has_active_completions_menu() {
4786 if edits
4787 .iter()
4788 .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
4789 {
4790 let mut inlays = Vec::new();
4791 for (range, new_text) in &edits {
4792 let inlay = Inlay::inline_completion(
4793 post_inc(&mut self.next_inlay_id),
4794 range.start,
4795 new_text.as_str(),
4796 );
4797 inlay_ids.push(inlay.id);
4798 inlays.push(inlay);
4799 }
4800
4801 self.splice_inlays(vec![], inlays, cx);
4802 } else {
4803 let background_color = cx.theme().status().deleted_background;
4804 self.highlight_text::<InlineCompletionHighlight>(
4805 edits.iter().map(|(range, _)| range.clone()).collect(),
4806 HighlightStyle {
4807 background_color: Some(background_color),
4808 ..Default::default()
4809 },
4810 cx,
4811 );
4812 }
4813 }
4814
4815 invalidation_row_range = edit_start_row..edit_end_row;
4816 completion = InlineCompletion::Edit(edits);
4817 };
4818
4819 let invalidation_range = multibuffer
4820 .anchor_before(Point::new(invalidation_row_range.start, 0))
4821 ..multibuffer.anchor_after(Point::new(
4822 invalidation_row_range.end,
4823 multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
4824 ));
4825
4826 self.active_inline_completion = Some(InlineCompletionState {
4827 inlay_ids,
4828 completion,
4829 invalidation_range,
4830 });
4831
4832 if self.has_active_completions_menu() {
4833 if let Some(hint) = self.inline_completion_menu_hint(cx) {
4834 match self.context_menu.borrow_mut().as_mut() {
4835 Some(CodeContextMenu::Completions(menu)) => {
4836 menu.show_inline_completion_hint(hint);
4837 }
4838 _ => {}
4839 }
4840 }
4841 }
4842
4843 cx.notify();
4844
4845 Some(())
4846 }
4847
4848 fn inline_completion_menu_hint(
4849 &mut self,
4850 cx: &mut ViewContext<Self>,
4851 ) -> Option<InlineCompletionMenuHint> {
4852 if self.has_active_inline_completion() {
4853 let provider_name = self.inline_completion_provider()?.display_name();
4854 let editor_snapshot = self.snapshot(cx);
4855
4856 let text = match &self.active_inline_completion.as_ref()?.completion {
4857 InlineCompletion::Edit(edits) => {
4858 inline_completion_edit_text(&editor_snapshot, edits, cx)
4859 }
4860 InlineCompletion::Move(target) => {
4861 let target_point =
4862 target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
4863 let target_line = target_point.row + 1;
4864 InlineCompletionText::Move(
4865 format!("Jump to edit in line {}", target_line).into(),
4866 )
4867 }
4868 };
4869
4870 Some(InlineCompletionMenuHint {
4871 provider_name,
4872 text,
4873 })
4874 } else {
4875 None
4876 }
4877 }
4878
4879 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
4880 Some(self.inline_completion_provider.as_ref()?.provider.clone())
4881 }
4882
4883 fn render_code_actions_indicator(
4884 &self,
4885 _style: &EditorStyle,
4886 row: DisplayRow,
4887 is_active: bool,
4888 cx: &mut ViewContext<Self>,
4889 ) -> Option<IconButton> {
4890 if self.available_code_actions.is_some() {
4891 Some(
4892 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
4893 .shape(ui::IconButtonShape::Square)
4894 .icon_size(IconSize::XSmall)
4895 .icon_color(Color::Muted)
4896 .toggle_state(is_active)
4897 .tooltip({
4898 let focus_handle = self.focus_handle.clone();
4899 move |cx| {
4900 Tooltip::for_action_in(
4901 "Toggle Code Actions",
4902 &ToggleCodeActions {
4903 deployed_from_indicator: None,
4904 },
4905 &focus_handle,
4906 cx,
4907 )
4908 }
4909 })
4910 .on_click(cx.listener(move |editor, _e, cx| {
4911 editor.focus(cx);
4912 editor.toggle_code_actions(
4913 &ToggleCodeActions {
4914 deployed_from_indicator: Some(row),
4915 },
4916 cx,
4917 );
4918 })),
4919 )
4920 } else {
4921 None
4922 }
4923 }
4924
4925 fn clear_tasks(&mut self) {
4926 self.tasks.clear()
4927 }
4928
4929 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
4930 if self.tasks.insert(key, value).is_some() {
4931 // This case should hopefully be rare, but just in case...
4932 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
4933 }
4934 }
4935
4936 fn build_tasks_context(
4937 project: &Model<Project>,
4938 buffer: &Model<Buffer>,
4939 buffer_row: u32,
4940 tasks: &Arc<RunnableTasks>,
4941 cx: &mut ViewContext<Self>,
4942 ) -> Task<Option<task::TaskContext>> {
4943 let position = Point::new(buffer_row, tasks.column);
4944 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4945 let location = Location {
4946 buffer: buffer.clone(),
4947 range: range_start..range_start,
4948 };
4949 // Fill in the environmental variables from the tree-sitter captures
4950 let mut captured_task_variables = TaskVariables::default();
4951 for (capture_name, value) in tasks.extra_variables.clone() {
4952 captured_task_variables.insert(
4953 task::VariableName::Custom(capture_name.into()),
4954 value.clone(),
4955 );
4956 }
4957 project.update(cx, |project, cx| {
4958 project.task_store().update(cx, |task_store, cx| {
4959 task_store.task_context_for_location(captured_task_variables, location, cx)
4960 })
4961 })
4962 }
4963
4964 pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
4965 let Some((workspace, _)) = self.workspace.clone() else {
4966 return;
4967 };
4968 let Some(project) = self.project.clone() else {
4969 return;
4970 };
4971
4972 // Try to find a closest, enclosing node using tree-sitter that has a
4973 // task
4974 let Some((buffer, buffer_row, tasks)) = self
4975 .find_enclosing_node_task(cx)
4976 // Or find the task that's closest in row-distance.
4977 .or_else(|| self.find_closest_task(cx))
4978 else {
4979 return;
4980 };
4981
4982 let reveal_strategy = action.reveal;
4983 let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
4984 cx.spawn(|_, mut cx| async move {
4985 let context = task_context.await?;
4986 let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
4987
4988 let resolved = resolved_task.resolved.as_mut()?;
4989 resolved.reveal = reveal_strategy;
4990
4991 workspace
4992 .update(&mut cx, |workspace, cx| {
4993 workspace::tasks::schedule_resolved_task(
4994 workspace,
4995 task_source_kind,
4996 resolved_task,
4997 false,
4998 cx,
4999 );
5000 })
5001 .ok()
5002 })
5003 .detach();
5004 }
5005
5006 fn find_closest_task(
5007 &mut self,
5008 cx: &mut ViewContext<Self>,
5009 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5010 let cursor_row = self.selections.newest_adjusted(cx).head().row;
5011
5012 let ((buffer_id, row), tasks) = self
5013 .tasks
5014 .iter()
5015 .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
5016
5017 let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
5018 let tasks = Arc::new(tasks.to_owned());
5019 Some((buffer, *row, tasks))
5020 }
5021
5022 fn find_enclosing_node_task(
5023 &mut self,
5024 cx: &mut ViewContext<Self>,
5025 ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
5026 let snapshot = self.buffer.read(cx).snapshot(cx);
5027 let offset = self.selections.newest::<usize>(cx).head();
5028 let excerpt = snapshot.excerpt_containing(offset..offset)?;
5029 let buffer_id = excerpt.buffer().remote_id();
5030
5031 let layer = excerpt.buffer().syntax_layer_at(offset)?;
5032 let mut cursor = layer.node().walk();
5033
5034 while cursor.goto_first_child_for_byte(offset).is_some() {
5035 if cursor.node().end_byte() == offset {
5036 cursor.goto_next_sibling();
5037 }
5038 }
5039
5040 // Ascend to the smallest ancestor that contains the range and has a task.
5041 loop {
5042 let node = cursor.node();
5043 let node_range = node.byte_range();
5044 let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
5045
5046 // Check if this node contains our offset
5047 if node_range.start <= offset && node_range.end >= offset {
5048 // If it contains offset, check for task
5049 if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
5050 let buffer = self.buffer.read(cx).buffer(buffer_id)?;
5051 return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
5052 }
5053 }
5054
5055 if !cursor.goto_parent() {
5056 break;
5057 }
5058 }
5059 None
5060 }
5061
5062 fn render_run_indicator(
5063 &self,
5064 _style: &EditorStyle,
5065 is_active: bool,
5066 row: DisplayRow,
5067 cx: &mut ViewContext<Self>,
5068 ) -> IconButton {
5069 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5070 .shape(ui::IconButtonShape::Square)
5071 .icon_size(IconSize::XSmall)
5072 .icon_color(Color::Muted)
5073 .toggle_state(is_active)
5074 .on_click(cx.listener(move |editor, _e, cx| {
5075 editor.focus(cx);
5076 editor.toggle_code_actions(
5077 &ToggleCodeActions {
5078 deployed_from_indicator: Some(row),
5079 },
5080 cx,
5081 );
5082 }))
5083 }
5084
5085 #[cfg(feature = "test-support")]
5086 pub fn context_menu_visible(&self) -> bool {
5087 self.context_menu
5088 .borrow()
5089 .as_ref()
5090 .map_or(false, |menu| menu.visible())
5091 }
5092
5093 #[cfg(feature = "test-support")]
5094 pub fn context_menu_contains_inline_completion(&self) -> bool {
5095 self.context_menu
5096 .borrow()
5097 .as_ref()
5098 .map_or(false, |menu| match menu {
5099 CodeContextMenu::Completions(menu) => menu.entries.first().map_or(false, |entry| {
5100 matches!(entry, CompletionEntry::InlineCompletionHint(_))
5101 }),
5102 CodeContextMenu::CodeActions(_) => false,
5103 })
5104 }
5105
5106 fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
5107 self.context_menu
5108 .borrow()
5109 .as_ref()
5110 .map(|menu| menu.origin(cursor_position))
5111 }
5112
5113 fn render_context_menu(
5114 &self,
5115 style: &EditorStyle,
5116 max_height_in_lines: u32,
5117 cx: &mut ViewContext<Editor>,
5118 ) -> Option<AnyElement> {
5119 self.context_menu.borrow().as_ref().and_then(|menu| {
5120 if menu.visible() {
5121 Some(menu.render(
5122 style,
5123 max_height_in_lines,
5124 self.workspace.as_ref().map(|(w, _)| w.clone()),
5125 cx,
5126 ))
5127 } else {
5128 None
5129 }
5130 })
5131 }
5132
5133 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
5134 cx.notify();
5135 self.completion_tasks.clear();
5136 self.context_menu.borrow_mut().take()
5137 }
5138
5139 fn show_snippet_choices(
5140 &mut self,
5141 choices: &Vec<String>,
5142 selection: Range<Anchor>,
5143 cx: &mut ViewContext<Self>,
5144 ) {
5145 if selection.start.buffer_id.is_none() {
5146 return;
5147 }
5148 let buffer_id = selection.start.buffer_id.unwrap();
5149 let buffer = self.buffer().read(cx).buffer(buffer_id);
5150 let id = post_inc(&mut self.next_completion_id);
5151
5152 if let Some(buffer) = buffer {
5153 *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
5154 CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
5155 ));
5156 }
5157 }
5158
5159 pub fn insert_snippet(
5160 &mut self,
5161 insertion_ranges: &[Range<usize>],
5162 snippet: Snippet,
5163 cx: &mut ViewContext<Self>,
5164 ) -> Result<()> {
5165 struct Tabstop<T> {
5166 is_end_tabstop: bool,
5167 ranges: Vec<Range<T>>,
5168 choices: Option<Vec<String>>,
5169 }
5170
5171 let tabstops = self.buffer.update(cx, |buffer, cx| {
5172 let snippet_text: Arc<str> = snippet.text.clone().into();
5173 buffer.edit(
5174 insertion_ranges
5175 .iter()
5176 .cloned()
5177 .map(|range| (range, snippet_text.clone())),
5178 Some(AutoindentMode::EachLine),
5179 cx,
5180 );
5181
5182 let snapshot = &*buffer.read(cx);
5183 let snippet = &snippet;
5184 snippet
5185 .tabstops
5186 .iter()
5187 .map(|tabstop| {
5188 let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
5189 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5190 });
5191 let mut tabstop_ranges = tabstop
5192 .ranges
5193 .iter()
5194 .flat_map(|tabstop_range| {
5195 let mut delta = 0_isize;
5196 insertion_ranges.iter().map(move |insertion_range| {
5197 let insertion_start = insertion_range.start as isize + delta;
5198 delta +=
5199 snippet.text.len() as isize - insertion_range.len() as isize;
5200
5201 let start = ((insertion_start + tabstop_range.start) as usize)
5202 .min(snapshot.len());
5203 let end = ((insertion_start + tabstop_range.end) as usize)
5204 .min(snapshot.len());
5205 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5206 })
5207 })
5208 .collect::<Vec<_>>();
5209 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5210
5211 Tabstop {
5212 is_end_tabstop,
5213 ranges: tabstop_ranges,
5214 choices: tabstop.choices.clone(),
5215 }
5216 })
5217 .collect::<Vec<_>>()
5218 });
5219 if let Some(tabstop) = tabstops.first() {
5220 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5221 s.select_ranges(tabstop.ranges.iter().cloned());
5222 });
5223
5224 if let Some(choices) = &tabstop.choices {
5225 if let Some(selection) = tabstop.ranges.first() {
5226 self.show_snippet_choices(choices, selection.clone(), cx)
5227 }
5228 }
5229
5230 // If we're already at the last tabstop and it's at the end of the snippet,
5231 // we're done, we don't need to keep the state around.
5232 if !tabstop.is_end_tabstop {
5233 let choices = tabstops
5234 .iter()
5235 .map(|tabstop| tabstop.choices.clone())
5236 .collect();
5237
5238 let ranges = tabstops
5239 .into_iter()
5240 .map(|tabstop| tabstop.ranges)
5241 .collect::<Vec<_>>();
5242
5243 self.snippet_stack.push(SnippetState {
5244 active_index: 0,
5245 ranges,
5246 choices,
5247 });
5248 }
5249
5250 // Check whether the just-entered snippet ends with an auto-closable bracket.
5251 if self.autoclose_regions.is_empty() {
5252 let snapshot = self.buffer.read(cx).snapshot(cx);
5253 for selection in &mut self.selections.all::<Point>(cx) {
5254 let selection_head = selection.head();
5255 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5256 continue;
5257 };
5258
5259 let mut bracket_pair = None;
5260 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5261 let prev_chars = snapshot
5262 .reversed_chars_at(selection_head)
5263 .collect::<String>();
5264 for (pair, enabled) in scope.brackets() {
5265 if enabled
5266 && pair.close
5267 && prev_chars.starts_with(pair.start.as_str())
5268 && next_chars.starts_with(pair.end.as_str())
5269 {
5270 bracket_pair = Some(pair.clone());
5271 break;
5272 }
5273 }
5274 if let Some(pair) = bracket_pair {
5275 let start = snapshot.anchor_after(selection_head);
5276 let end = snapshot.anchor_after(selection_head);
5277 self.autoclose_regions.push(AutocloseRegion {
5278 selection_id: selection.id,
5279 range: start..end,
5280 pair,
5281 });
5282 }
5283 }
5284 }
5285 }
5286 Ok(())
5287 }
5288
5289 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5290 self.move_to_snippet_tabstop(Bias::Right, cx)
5291 }
5292
5293 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5294 self.move_to_snippet_tabstop(Bias::Left, cx)
5295 }
5296
5297 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5298 if let Some(mut snippet) = self.snippet_stack.pop() {
5299 match bias {
5300 Bias::Left => {
5301 if snippet.active_index > 0 {
5302 snippet.active_index -= 1;
5303 } else {
5304 self.snippet_stack.push(snippet);
5305 return false;
5306 }
5307 }
5308 Bias::Right => {
5309 if snippet.active_index + 1 < snippet.ranges.len() {
5310 snippet.active_index += 1;
5311 } else {
5312 self.snippet_stack.push(snippet);
5313 return false;
5314 }
5315 }
5316 }
5317 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5318 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5319 s.select_anchor_ranges(current_ranges.iter().cloned())
5320 });
5321
5322 if let Some(choices) = &snippet.choices[snippet.active_index] {
5323 if let Some(selection) = current_ranges.first() {
5324 self.show_snippet_choices(&choices, selection.clone(), cx);
5325 }
5326 }
5327
5328 // If snippet state is not at the last tabstop, push it back on the stack
5329 if snippet.active_index + 1 < snippet.ranges.len() {
5330 self.snippet_stack.push(snippet);
5331 }
5332 return true;
5333 }
5334 }
5335
5336 false
5337 }
5338
5339 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5340 self.transact(cx, |this, cx| {
5341 this.select_all(&SelectAll, cx);
5342 this.insert("", cx);
5343 });
5344 }
5345
5346 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5347 self.transact(cx, |this, cx| {
5348 this.select_autoclose_pair(cx);
5349 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5350 if !this.linked_edit_ranges.is_empty() {
5351 let selections = this.selections.all::<MultiBufferPoint>(cx);
5352 let snapshot = this.buffer.read(cx).snapshot(cx);
5353
5354 for selection in selections.iter() {
5355 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5356 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5357 if selection_start.buffer_id != selection_end.buffer_id {
5358 continue;
5359 }
5360 if let Some(ranges) =
5361 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5362 {
5363 for (buffer, entries) in ranges {
5364 linked_ranges.entry(buffer).or_default().extend(entries);
5365 }
5366 }
5367 }
5368 }
5369
5370 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5371 if !this.selections.line_mode {
5372 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5373 for selection in &mut selections {
5374 if selection.is_empty() {
5375 let old_head = selection.head();
5376 let mut new_head =
5377 movement::left(&display_map, old_head.to_display_point(&display_map))
5378 .to_point(&display_map);
5379 if let Some((buffer, line_buffer_range)) = display_map
5380 .buffer_snapshot
5381 .buffer_line_for_row(MultiBufferRow(old_head.row))
5382 {
5383 let indent_size =
5384 buffer.indent_size_for_line(line_buffer_range.start.row);
5385 let indent_len = match indent_size.kind {
5386 IndentKind::Space => {
5387 buffer.settings_at(line_buffer_range.start, cx).tab_size
5388 }
5389 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5390 };
5391 if old_head.column <= indent_size.len && old_head.column > 0 {
5392 let indent_len = indent_len.get();
5393 new_head = cmp::min(
5394 new_head,
5395 MultiBufferPoint::new(
5396 old_head.row,
5397 ((old_head.column - 1) / indent_len) * indent_len,
5398 ),
5399 );
5400 }
5401 }
5402
5403 selection.set_head(new_head, SelectionGoal::None);
5404 }
5405 }
5406 }
5407
5408 this.signature_help_state.set_backspace_pressed(true);
5409 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5410 this.insert("", cx);
5411 let empty_str: Arc<str> = Arc::from("");
5412 for (buffer, edits) in linked_ranges {
5413 let snapshot = buffer.read(cx).snapshot();
5414 use text::ToPoint as TP;
5415
5416 let edits = edits
5417 .into_iter()
5418 .map(|range| {
5419 let end_point = TP::to_point(&range.end, &snapshot);
5420 let mut start_point = TP::to_point(&range.start, &snapshot);
5421
5422 if end_point == start_point {
5423 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5424 .saturating_sub(1);
5425 start_point = TP::to_point(&offset, &snapshot);
5426 };
5427
5428 (start_point..end_point, empty_str.clone())
5429 })
5430 .sorted_by_key(|(range, _)| range.start)
5431 .collect::<Vec<_>>();
5432 buffer.update(cx, |this, cx| {
5433 this.edit(edits, None, cx);
5434 })
5435 }
5436 this.refresh_inline_completion(true, false, cx);
5437 linked_editing_ranges::refresh_linked_ranges(this, cx);
5438 });
5439 }
5440
5441 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5442 self.transact(cx, |this, cx| {
5443 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5444 let line_mode = s.line_mode;
5445 s.move_with(|map, selection| {
5446 if selection.is_empty() && !line_mode {
5447 let cursor = movement::right(map, selection.head());
5448 selection.end = cursor;
5449 selection.reversed = true;
5450 selection.goal = SelectionGoal::None;
5451 }
5452 })
5453 });
5454 this.insert("", cx);
5455 this.refresh_inline_completion(true, false, cx);
5456 });
5457 }
5458
5459 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5460 if self.move_to_prev_snippet_tabstop(cx) {
5461 return;
5462 }
5463
5464 self.outdent(&Outdent, cx);
5465 }
5466
5467 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5468 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5469 return;
5470 }
5471
5472 let mut selections = self.selections.all_adjusted(cx);
5473 let buffer = self.buffer.read(cx);
5474 let snapshot = buffer.snapshot(cx);
5475 let rows_iter = selections.iter().map(|s| s.head().row);
5476 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5477
5478 let mut edits = Vec::new();
5479 let mut prev_edited_row = 0;
5480 let mut row_delta = 0;
5481 for selection in &mut selections {
5482 if selection.start.row != prev_edited_row {
5483 row_delta = 0;
5484 }
5485 prev_edited_row = selection.end.row;
5486
5487 // If the selection is non-empty, then increase the indentation of the selected lines.
5488 if !selection.is_empty() {
5489 row_delta =
5490 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5491 continue;
5492 }
5493
5494 // If the selection is empty and the cursor is in the leading whitespace before the
5495 // suggested indentation, then auto-indent the line.
5496 let cursor = selection.head();
5497 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5498 if let Some(suggested_indent) =
5499 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5500 {
5501 if cursor.column < suggested_indent.len
5502 && cursor.column <= current_indent.len
5503 && current_indent.len <= suggested_indent.len
5504 {
5505 selection.start = Point::new(cursor.row, suggested_indent.len);
5506 selection.end = selection.start;
5507 if row_delta == 0 {
5508 edits.extend(Buffer::edit_for_indent_size_adjustment(
5509 cursor.row,
5510 current_indent,
5511 suggested_indent,
5512 ));
5513 row_delta = suggested_indent.len - current_indent.len;
5514 }
5515 continue;
5516 }
5517 }
5518
5519 // Otherwise, insert a hard or soft tab.
5520 let settings = buffer.settings_at(cursor, cx);
5521 let tab_size = if settings.hard_tabs {
5522 IndentSize::tab()
5523 } else {
5524 let tab_size = settings.tab_size.get();
5525 let char_column = snapshot
5526 .text_for_range(Point::new(cursor.row, 0)..cursor)
5527 .flat_map(str::chars)
5528 .count()
5529 + row_delta as usize;
5530 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5531 IndentSize::spaces(chars_to_next_tab_stop)
5532 };
5533 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5534 selection.end = selection.start;
5535 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5536 row_delta += tab_size.len;
5537 }
5538
5539 self.transact(cx, |this, cx| {
5540 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5541 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5542 this.refresh_inline_completion(true, false, cx);
5543 });
5544 }
5545
5546 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5547 if self.read_only(cx) {
5548 return;
5549 }
5550 let mut selections = self.selections.all::<Point>(cx);
5551 let mut prev_edited_row = 0;
5552 let mut row_delta = 0;
5553 let mut edits = Vec::new();
5554 let buffer = self.buffer.read(cx);
5555 let snapshot = buffer.snapshot(cx);
5556 for selection in &mut selections {
5557 if selection.start.row != prev_edited_row {
5558 row_delta = 0;
5559 }
5560 prev_edited_row = selection.end.row;
5561
5562 row_delta =
5563 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5564 }
5565
5566 self.transact(cx, |this, cx| {
5567 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5568 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5569 });
5570 }
5571
5572 fn indent_selection(
5573 buffer: &MultiBuffer,
5574 snapshot: &MultiBufferSnapshot,
5575 selection: &mut Selection<Point>,
5576 edits: &mut Vec<(Range<Point>, String)>,
5577 delta_for_start_row: u32,
5578 cx: &AppContext,
5579 ) -> u32 {
5580 let settings = buffer.settings_at(selection.start, cx);
5581 let tab_size = settings.tab_size.get();
5582 let indent_kind = if settings.hard_tabs {
5583 IndentKind::Tab
5584 } else {
5585 IndentKind::Space
5586 };
5587 let mut start_row = selection.start.row;
5588 let mut end_row = selection.end.row + 1;
5589
5590 // If a selection ends at the beginning of a line, don't indent
5591 // that last line.
5592 if selection.end.column == 0 && selection.end.row > selection.start.row {
5593 end_row -= 1;
5594 }
5595
5596 // Avoid re-indenting a row that has already been indented by a
5597 // previous selection, but still update this selection's column
5598 // to reflect that indentation.
5599 if delta_for_start_row > 0 {
5600 start_row += 1;
5601 selection.start.column += delta_for_start_row;
5602 if selection.end.row == selection.start.row {
5603 selection.end.column += delta_for_start_row;
5604 }
5605 }
5606
5607 let mut delta_for_end_row = 0;
5608 let has_multiple_rows = start_row + 1 != end_row;
5609 for row in start_row..end_row {
5610 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5611 let indent_delta = match (current_indent.kind, indent_kind) {
5612 (IndentKind::Space, IndentKind::Space) => {
5613 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5614 IndentSize::spaces(columns_to_next_tab_stop)
5615 }
5616 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5617 (_, IndentKind::Tab) => IndentSize::tab(),
5618 };
5619
5620 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5621 0
5622 } else {
5623 selection.start.column
5624 };
5625 let row_start = Point::new(row, start);
5626 edits.push((
5627 row_start..row_start,
5628 indent_delta.chars().collect::<String>(),
5629 ));
5630
5631 // Update this selection's endpoints to reflect the indentation.
5632 if row == selection.start.row {
5633 selection.start.column += indent_delta.len;
5634 }
5635 if row == selection.end.row {
5636 selection.end.column += indent_delta.len;
5637 delta_for_end_row = indent_delta.len;
5638 }
5639 }
5640
5641 if selection.start.row == selection.end.row {
5642 delta_for_start_row + delta_for_end_row
5643 } else {
5644 delta_for_end_row
5645 }
5646 }
5647
5648 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5649 if self.read_only(cx) {
5650 return;
5651 }
5652 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5653 let selections = self.selections.all::<Point>(cx);
5654 let mut deletion_ranges = Vec::new();
5655 let mut last_outdent = None;
5656 {
5657 let buffer = self.buffer.read(cx);
5658 let snapshot = buffer.snapshot(cx);
5659 for selection in &selections {
5660 let settings = buffer.settings_at(selection.start, cx);
5661 let tab_size = settings.tab_size.get();
5662 let mut rows = selection.spanned_rows(false, &display_map);
5663
5664 // Avoid re-outdenting a row that has already been outdented by a
5665 // previous selection.
5666 if let Some(last_row) = last_outdent {
5667 if last_row == rows.start {
5668 rows.start = rows.start.next_row();
5669 }
5670 }
5671 let has_multiple_rows = rows.len() > 1;
5672 for row in rows.iter_rows() {
5673 let indent_size = snapshot.indent_size_for_line(row);
5674 if indent_size.len > 0 {
5675 let deletion_len = match indent_size.kind {
5676 IndentKind::Space => {
5677 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5678 if columns_to_prev_tab_stop == 0 {
5679 tab_size
5680 } else {
5681 columns_to_prev_tab_stop
5682 }
5683 }
5684 IndentKind::Tab => 1,
5685 };
5686 let start = if has_multiple_rows
5687 || deletion_len > selection.start.column
5688 || indent_size.len < selection.start.column
5689 {
5690 0
5691 } else {
5692 selection.start.column - deletion_len
5693 };
5694 deletion_ranges.push(
5695 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5696 );
5697 last_outdent = Some(row);
5698 }
5699 }
5700 }
5701 }
5702
5703 self.transact(cx, |this, cx| {
5704 this.buffer.update(cx, |buffer, cx| {
5705 let empty_str: Arc<str> = Arc::default();
5706 buffer.edit(
5707 deletion_ranges
5708 .into_iter()
5709 .map(|range| (range, empty_str.clone())),
5710 None,
5711 cx,
5712 );
5713 });
5714 let selections = this.selections.all::<usize>(cx);
5715 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5716 });
5717 }
5718
5719 pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
5720 if self.read_only(cx) {
5721 return;
5722 }
5723 let selections = self
5724 .selections
5725 .all::<usize>(cx)
5726 .into_iter()
5727 .map(|s| s.range());
5728
5729 self.transact(cx, |this, cx| {
5730 this.buffer.update(cx, |buffer, cx| {
5731 buffer.autoindent_ranges(selections, cx);
5732 });
5733 let selections = this.selections.all::<usize>(cx);
5734 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5735 });
5736 }
5737
5738 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5739 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5740 let selections = self.selections.all::<Point>(cx);
5741
5742 let mut new_cursors = Vec::new();
5743 let mut edit_ranges = Vec::new();
5744 let mut selections = selections.iter().peekable();
5745 while let Some(selection) = selections.next() {
5746 let mut rows = selection.spanned_rows(false, &display_map);
5747 let goal_display_column = selection.head().to_display_point(&display_map).column();
5748
5749 // Accumulate contiguous regions of rows that we want to delete.
5750 while let Some(next_selection) = selections.peek() {
5751 let next_rows = next_selection.spanned_rows(false, &display_map);
5752 if next_rows.start <= rows.end {
5753 rows.end = next_rows.end;
5754 selections.next().unwrap();
5755 } else {
5756 break;
5757 }
5758 }
5759
5760 let buffer = &display_map.buffer_snapshot;
5761 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5762 let edit_end;
5763 let cursor_buffer_row;
5764 if buffer.max_point().row >= rows.end.0 {
5765 // If there's a line after the range, delete the \n from the end of the row range
5766 // and position the cursor on the next line.
5767 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5768 cursor_buffer_row = rows.end;
5769 } else {
5770 // If there isn't a line after the range, delete the \n from the line before the
5771 // start of the row range and position the cursor there.
5772 edit_start = edit_start.saturating_sub(1);
5773 edit_end = buffer.len();
5774 cursor_buffer_row = rows.start.previous_row();
5775 }
5776
5777 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5778 *cursor.column_mut() =
5779 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5780
5781 new_cursors.push((
5782 selection.id,
5783 buffer.anchor_after(cursor.to_point(&display_map)),
5784 ));
5785 edit_ranges.push(edit_start..edit_end);
5786 }
5787
5788 self.transact(cx, |this, cx| {
5789 let buffer = this.buffer.update(cx, |buffer, cx| {
5790 let empty_str: Arc<str> = Arc::default();
5791 buffer.edit(
5792 edit_ranges
5793 .into_iter()
5794 .map(|range| (range, empty_str.clone())),
5795 None,
5796 cx,
5797 );
5798 buffer.snapshot(cx)
5799 });
5800 let new_selections = new_cursors
5801 .into_iter()
5802 .map(|(id, cursor)| {
5803 let cursor = cursor.to_point(&buffer);
5804 Selection {
5805 id,
5806 start: cursor,
5807 end: cursor,
5808 reversed: false,
5809 goal: SelectionGoal::None,
5810 }
5811 })
5812 .collect();
5813
5814 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5815 s.select(new_selections);
5816 });
5817 });
5818 }
5819
5820 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5821 if self.read_only(cx) {
5822 return;
5823 }
5824 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5825 for selection in self.selections.all::<Point>(cx) {
5826 let start = MultiBufferRow(selection.start.row);
5827 // Treat single line selections as if they include the next line. Otherwise this action
5828 // would do nothing for single line selections individual cursors.
5829 let end = if selection.start.row == selection.end.row {
5830 MultiBufferRow(selection.start.row + 1)
5831 } else {
5832 MultiBufferRow(selection.end.row)
5833 };
5834
5835 if let Some(last_row_range) = row_ranges.last_mut() {
5836 if start <= last_row_range.end {
5837 last_row_range.end = end;
5838 continue;
5839 }
5840 }
5841 row_ranges.push(start..end);
5842 }
5843
5844 let snapshot = self.buffer.read(cx).snapshot(cx);
5845 let mut cursor_positions = Vec::new();
5846 for row_range in &row_ranges {
5847 let anchor = snapshot.anchor_before(Point::new(
5848 row_range.end.previous_row().0,
5849 snapshot.line_len(row_range.end.previous_row()),
5850 ));
5851 cursor_positions.push(anchor..anchor);
5852 }
5853
5854 self.transact(cx, |this, cx| {
5855 for row_range in row_ranges.into_iter().rev() {
5856 for row in row_range.iter_rows().rev() {
5857 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5858 let next_line_row = row.next_row();
5859 let indent = snapshot.indent_size_for_line(next_line_row);
5860 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5861
5862 let replace = if snapshot.line_len(next_line_row) > indent.len {
5863 " "
5864 } else {
5865 ""
5866 };
5867
5868 this.buffer.update(cx, |buffer, cx| {
5869 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5870 });
5871 }
5872 }
5873
5874 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5875 s.select_anchor_ranges(cursor_positions)
5876 });
5877 });
5878 }
5879
5880 pub fn sort_lines_case_sensitive(
5881 &mut self,
5882 _: &SortLinesCaseSensitive,
5883 cx: &mut ViewContext<Self>,
5884 ) {
5885 self.manipulate_lines(cx, |lines| lines.sort())
5886 }
5887
5888 pub fn sort_lines_case_insensitive(
5889 &mut self,
5890 _: &SortLinesCaseInsensitive,
5891 cx: &mut ViewContext<Self>,
5892 ) {
5893 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5894 }
5895
5896 pub fn unique_lines_case_insensitive(
5897 &mut self,
5898 _: &UniqueLinesCaseInsensitive,
5899 cx: &mut ViewContext<Self>,
5900 ) {
5901 self.manipulate_lines(cx, |lines| {
5902 let mut seen = HashSet::default();
5903 lines.retain(|line| seen.insert(line.to_lowercase()));
5904 })
5905 }
5906
5907 pub fn unique_lines_case_sensitive(
5908 &mut self,
5909 _: &UniqueLinesCaseSensitive,
5910 cx: &mut ViewContext<Self>,
5911 ) {
5912 self.manipulate_lines(cx, |lines| {
5913 let mut seen = HashSet::default();
5914 lines.retain(|line| seen.insert(*line));
5915 })
5916 }
5917
5918 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
5919 let mut revert_changes = HashMap::default();
5920 let snapshot = self.snapshot(cx);
5921 for hunk in hunks_for_ranges(
5922 Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
5923 &snapshot,
5924 ) {
5925 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
5926 }
5927 if !revert_changes.is_empty() {
5928 self.transact(cx, |editor, cx| {
5929 editor.revert(revert_changes, cx);
5930 });
5931 }
5932 }
5933
5934 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
5935 let Some(project) = self.project.clone() else {
5936 return;
5937 };
5938 self.reload(project, cx).detach_and_notify_err(cx);
5939 }
5940
5941 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
5942 let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
5943 if !revert_changes.is_empty() {
5944 self.transact(cx, |editor, cx| {
5945 editor.revert(revert_changes, cx);
5946 });
5947 }
5948 }
5949
5950 fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
5951 let snapshot = self.buffer.read(cx).read(cx);
5952 if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
5953 drop(snapshot);
5954 let mut revert_changes = HashMap::default();
5955 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
5956 if !revert_changes.is_empty() {
5957 self.revert(revert_changes, cx)
5958 }
5959 }
5960 }
5961
5962 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
5963 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
5964 let project_path = buffer.read(cx).project_path(cx)?;
5965 let project = self.project.as_ref()?.read(cx);
5966 let entry = project.entry_for_path(&project_path, cx)?;
5967 let parent = match &entry.canonical_path {
5968 Some(canonical_path) => canonical_path.to_path_buf(),
5969 None => project.absolute_path(&project_path, cx)?,
5970 }
5971 .parent()?
5972 .to_path_buf();
5973 Some(parent)
5974 }) {
5975 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
5976 }
5977 }
5978
5979 fn gather_revert_changes(
5980 &mut self,
5981 selections: &[Selection<Point>],
5982 cx: &mut ViewContext<'_, Editor>,
5983 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
5984 let mut revert_changes = HashMap::default();
5985 let snapshot = self.snapshot(cx);
5986 for hunk in hunks_for_selections(&snapshot, selections) {
5987 self.prepare_revert_change(&mut revert_changes, &hunk, cx);
5988 }
5989 revert_changes
5990 }
5991
5992 pub fn prepare_revert_change(
5993 &mut self,
5994 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
5995 hunk: &MultiBufferDiffHunk,
5996 cx: &AppContext,
5997 ) -> Option<()> {
5998 let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
5999 let buffer = buffer.read(cx);
6000 let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
6001 let original_text = change_set
6002 .read(cx)
6003 .base_text
6004 .as_ref()?
6005 .read(cx)
6006 .as_rope()
6007 .slice(hunk.diff_base_byte_range.clone());
6008 let buffer_snapshot = buffer.snapshot();
6009 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6010 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6011 probe
6012 .0
6013 .start
6014 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6015 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6016 }) {
6017 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6018 Some(())
6019 } else {
6020 None
6021 }
6022 }
6023
6024 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6025 self.manipulate_lines(cx, |lines| lines.reverse())
6026 }
6027
6028 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6029 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6030 }
6031
6032 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6033 where
6034 Fn: FnMut(&mut Vec<&str>),
6035 {
6036 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6037 let buffer = self.buffer.read(cx).snapshot(cx);
6038
6039 let mut edits = Vec::new();
6040
6041 let selections = self.selections.all::<Point>(cx);
6042 let mut selections = selections.iter().peekable();
6043 let mut contiguous_row_selections = Vec::new();
6044 let mut new_selections = Vec::new();
6045 let mut added_lines = 0;
6046 let mut removed_lines = 0;
6047
6048 while let Some(selection) = selections.next() {
6049 let (start_row, end_row) = consume_contiguous_rows(
6050 &mut contiguous_row_selections,
6051 selection,
6052 &display_map,
6053 &mut selections,
6054 );
6055
6056 let start_point = Point::new(start_row.0, 0);
6057 let end_point = Point::new(
6058 end_row.previous_row().0,
6059 buffer.line_len(end_row.previous_row()),
6060 );
6061 let text = buffer
6062 .text_for_range(start_point..end_point)
6063 .collect::<String>();
6064
6065 let mut lines = text.split('\n').collect_vec();
6066
6067 let lines_before = lines.len();
6068 callback(&mut lines);
6069 let lines_after = lines.len();
6070
6071 edits.push((start_point..end_point, lines.join("\n")));
6072
6073 // Selections must change based on added and removed line count
6074 let start_row =
6075 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6076 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6077 new_selections.push(Selection {
6078 id: selection.id,
6079 start: start_row,
6080 end: end_row,
6081 goal: SelectionGoal::None,
6082 reversed: selection.reversed,
6083 });
6084
6085 if lines_after > lines_before {
6086 added_lines += lines_after - lines_before;
6087 } else if lines_before > lines_after {
6088 removed_lines += lines_before - lines_after;
6089 }
6090 }
6091
6092 self.transact(cx, |this, cx| {
6093 let buffer = this.buffer.update(cx, |buffer, cx| {
6094 buffer.edit(edits, None, cx);
6095 buffer.snapshot(cx)
6096 });
6097
6098 // Recalculate offsets on newly edited buffer
6099 let new_selections = new_selections
6100 .iter()
6101 .map(|s| {
6102 let start_point = Point::new(s.start.0, 0);
6103 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6104 Selection {
6105 id: s.id,
6106 start: buffer.point_to_offset(start_point),
6107 end: buffer.point_to_offset(end_point),
6108 goal: s.goal,
6109 reversed: s.reversed,
6110 }
6111 })
6112 .collect();
6113
6114 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6115 s.select(new_selections);
6116 });
6117
6118 this.request_autoscroll(Autoscroll::fit(), cx);
6119 });
6120 }
6121
6122 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6123 self.manipulate_text(cx, |text| text.to_uppercase())
6124 }
6125
6126 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6127 self.manipulate_text(cx, |text| text.to_lowercase())
6128 }
6129
6130 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6131 self.manipulate_text(cx, |text| {
6132 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6133 // https://github.com/rutrum/convert-case/issues/16
6134 text.split('\n')
6135 .map(|line| line.to_case(Case::Title))
6136 .join("\n")
6137 })
6138 }
6139
6140 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6141 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6142 }
6143
6144 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6145 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6146 }
6147
6148 pub fn convert_to_upper_camel_case(
6149 &mut self,
6150 _: &ConvertToUpperCamelCase,
6151 cx: &mut ViewContext<Self>,
6152 ) {
6153 self.manipulate_text(cx, |text| {
6154 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6155 // https://github.com/rutrum/convert-case/issues/16
6156 text.split('\n')
6157 .map(|line| line.to_case(Case::UpperCamel))
6158 .join("\n")
6159 })
6160 }
6161
6162 pub fn convert_to_lower_camel_case(
6163 &mut self,
6164 _: &ConvertToLowerCamelCase,
6165 cx: &mut ViewContext<Self>,
6166 ) {
6167 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6168 }
6169
6170 pub fn convert_to_opposite_case(
6171 &mut self,
6172 _: &ConvertToOppositeCase,
6173 cx: &mut ViewContext<Self>,
6174 ) {
6175 self.manipulate_text(cx, |text| {
6176 text.chars()
6177 .fold(String::with_capacity(text.len()), |mut t, c| {
6178 if c.is_uppercase() {
6179 t.extend(c.to_lowercase());
6180 } else {
6181 t.extend(c.to_uppercase());
6182 }
6183 t
6184 })
6185 })
6186 }
6187
6188 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6189 where
6190 Fn: FnMut(&str) -> String,
6191 {
6192 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6193 let buffer = self.buffer.read(cx).snapshot(cx);
6194
6195 let mut new_selections = Vec::new();
6196 let mut edits = Vec::new();
6197 let mut selection_adjustment = 0i32;
6198
6199 for selection in self.selections.all::<usize>(cx) {
6200 let selection_is_empty = selection.is_empty();
6201
6202 let (start, end) = if selection_is_empty {
6203 let word_range = movement::surrounding_word(
6204 &display_map,
6205 selection.start.to_display_point(&display_map),
6206 );
6207 let start = word_range.start.to_offset(&display_map, Bias::Left);
6208 let end = word_range.end.to_offset(&display_map, Bias::Left);
6209 (start, end)
6210 } else {
6211 (selection.start, selection.end)
6212 };
6213
6214 let text = buffer.text_for_range(start..end).collect::<String>();
6215 let old_length = text.len() as i32;
6216 let text = callback(&text);
6217
6218 new_selections.push(Selection {
6219 start: (start as i32 - selection_adjustment) as usize,
6220 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6221 goal: SelectionGoal::None,
6222 ..selection
6223 });
6224
6225 selection_adjustment += old_length - text.len() as i32;
6226
6227 edits.push((start..end, text));
6228 }
6229
6230 self.transact(cx, |this, cx| {
6231 this.buffer.update(cx, |buffer, cx| {
6232 buffer.edit(edits, None, cx);
6233 });
6234
6235 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6236 s.select(new_selections);
6237 });
6238
6239 this.request_autoscroll(Autoscroll::fit(), cx);
6240 });
6241 }
6242
6243 pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
6244 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6245 let buffer = &display_map.buffer_snapshot;
6246 let selections = self.selections.all::<Point>(cx);
6247
6248 let mut edits = Vec::new();
6249 let mut selections_iter = selections.iter().peekable();
6250 while let Some(selection) = selections_iter.next() {
6251 let mut rows = selection.spanned_rows(false, &display_map);
6252 // duplicate line-wise
6253 if whole_lines || selection.start == selection.end {
6254 // Avoid duplicating the same lines twice.
6255 while let Some(next_selection) = selections_iter.peek() {
6256 let next_rows = next_selection.spanned_rows(false, &display_map);
6257 if next_rows.start < rows.end {
6258 rows.end = next_rows.end;
6259 selections_iter.next().unwrap();
6260 } else {
6261 break;
6262 }
6263 }
6264
6265 // Copy the text from the selected row region and splice it either at the start
6266 // or end of the region.
6267 let start = Point::new(rows.start.0, 0);
6268 let end = Point::new(
6269 rows.end.previous_row().0,
6270 buffer.line_len(rows.end.previous_row()),
6271 );
6272 let text = buffer
6273 .text_for_range(start..end)
6274 .chain(Some("\n"))
6275 .collect::<String>();
6276 let insert_location = if upwards {
6277 Point::new(rows.end.0, 0)
6278 } else {
6279 start
6280 };
6281 edits.push((insert_location..insert_location, text));
6282 } else {
6283 // duplicate character-wise
6284 let start = selection.start;
6285 let end = selection.end;
6286 let text = buffer.text_for_range(start..end).collect::<String>();
6287 edits.push((selection.end..selection.end, text));
6288 }
6289 }
6290
6291 self.transact(cx, |this, cx| {
6292 this.buffer.update(cx, |buffer, cx| {
6293 buffer.edit(edits, None, cx);
6294 });
6295
6296 this.request_autoscroll(Autoscroll::fit(), cx);
6297 });
6298 }
6299
6300 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6301 self.duplicate(true, true, cx);
6302 }
6303
6304 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6305 self.duplicate(false, true, cx);
6306 }
6307
6308 pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
6309 self.duplicate(false, false, cx);
6310 }
6311
6312 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6313 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6314 let buffer = self.buffer.read(cx).snapshot(cx);
6315
6316 let mut edits = Vec::new();
6317 let mut unfold_ranges = Vec::new();
6318 let mut refold_creases = Vec::new();
6319
6320 let selections = self.selections.all::<Point>(cx);
6321 let mut selections = selections.iter().peekable();
6322 let mut contiguous_row_selections = Vec::new();
6323 let mut new_selections = Vec::new();
6324
6325 while let Some(selection) = selections.next() {
6326 // Find all the selections that span a contiguous row range
6327 let (start_row, end_row) = consume_contiguous_rows(
6328 &mut contiguous_row_selections,
6329 selection,
6330 &display_map,
6331 &mut selections,
6332 );
6333
6334 // Move the text spanned by the row range to be before the line preceding the row range
6335 if start_row.0 > 0 {
6336 let range_to_move = Point::new(
6337 start_row.previous_row().0,
6338 buffer.line_len(start_row.previous_row()),
6339 )
6340 ..Point::new(
6341 end_row.previous_row().0,
6342 buffer.line_len(end_row.previous_row()),
6343 );
6344 let insertion_point = display_map
6345 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6346 .0;
6347
6348 // Don't move lines across excerpts
6349 if buffer
6350 .excerpt_boundaries_in_range((
6351 Bound::Excluded(insertion_point),
6352 Bound::Included(range_to_move.end),
6353 ))
6354 .next()
6355 .is_none()
6356 {
6357 let text = buffer
6358 .text_for_range(range_to_move.clone())
6359 .flat_map(|s| s.chars())
6360 .skip(1)
6361 .chain(['\n'])
6362 .collect::<String>();
6363
6364 edits.push((
6365 buffer.anchor_after(range_to_move.start)
6366 ..buffer.anchor_before(range_to_move.end),
6367 String::new(),
6368 ));
6369 let insertion_anchor = buffer.anchor_after(insertion_point);
6370 edits.push((insertion_anchor..insertion_anchor, text));
6371
6372 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6373
6374 // Move selections up
6375 new_selections.extend(contiguous_row_selections.drain(..).map(
6376 |mut selection| {
6377 selection.start.row -= row_delta;
6378 selection.end.row -= row_delta;
6379 selection
6380 },
6381 ));
6382
6383 // Move folds up
6384 unfold_ranges.push(range_to_move.clone());
6385 for fold in display_map.folds_in_range(
6386 buffer.anchor_before(range_to_move.start)
6387 ..buffer.anchor_after(range_to_move.end),
6388 ) {
6389 let mut start = fold.range.start.to_point(&buffer);
6390 let mut end = fold.range.end.to_point(&buffer);
6391 start.row -= row_delta;
6392 end.row -= row_delta;
6393 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6394 }
6395 }
6396 }
6397
6398 // If we didn't move line(s), preserve the existing selections
6399 new_selections.append(&mut contiguous_row_selections);
6400 }
6401
6402 self.transact(cx, |this, cx| {
6403 this.unfold_ranges(&unfold_ranges, true, true, cx);
6404 this.buffer.update(cx, |buffer, cx| {
6405 for (range, text) in edits {
6406 buffer.edit([(range, text)], None, cx);
6407 }
6408 });
6409 this.fold_creases(refold_creases, true, cx);
6410 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6411 s.select(new_selections);
6412 })
6413 });
6414 }
6415
6416 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6417 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6418 let buffer = self.buffer.read(cx).snapshot(cx);
6419
6420 let mut edits = Vec::new();
6421 let mut unfold_ranges = Vec::new();
6422 let mut refold_creases = Vec::new();
6423
6424 let selections = self.selections.all::<Point>(cx);
6425 let mut selections = selections.iter().peekable();
6426 let mut contiguous_row_selections = Vec::new();
6427 let mut new_selections = Vec::new();
6428
6429 while let Some(selection) = selections.next() {
6430 // Find all the selections that span a contiguous row range
6431 let (start_row, end_row) = consume_contiguous_rows(
6432 &mut contiguous_row_selections,
6433 selection,
6434 &display_map,
6435 &mut selections,
6436 );
6437
6438 // Move the text spanned by the row range to be after the last line of the row range
6439 if end_row.0 <= buffer.max_point().row {
6440 let range_to_move =
6441 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6442 let insertion_point = display_map
6443 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6444 .0;
6445
6446 // Don't move lines across excerpt boundaries
6447 if buffer
6448 .excerpt_boundaries_in_range((
6449 Bound::Excluded(range_to_move.start),
6450 Bound::Included(insertion_point),
6451 ))
6452 .next()
6453 .is_none()
6454 {
6455 let mut text = String::from("\n");
6456 text.extend(buffer.text_for_range(range_to_move.clone()));
6457 text.pop(); // Drop trailing newline
6458 edits.push((
6459 buffer.anchor_after(range_to_move.start)
6460 ..buffer.anchor_before(range_to_move.end),
6461 String::new(),
6462 ));
6463 let insertion_anchor = buffer.anchor_after(insertion_point);
6464 edits.push((insertion_anchor..insertion_anchor, text));
6465
6466 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6467
6468 // Move selections down
6469 new_selections.extend(contiguous_row_selections.drain(..).map(
6470 |mut selection| {
6471 selection.start.row += row_delta;
6472 selection.end.row += row_delta;
6473 selection
6474 },
6475 ));
6476
6477 // Move folds down
6478 unfold_ranges.push(range_to_move.clone());
6479 for fold in display_map.folds_in_range(
6480 buffer.anchor_before(range_to_move.start)
6481 ..buffer.anchor_after(range_to_move.end),
6482 ) {
6483 let mut start = fold.range.start.to_point(&buffer);
6484 let mut end = fold.range.end.to_point(&buffer);
6485 start.row += row_delta;
6486 end.row += row_delta;
6487 refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
6488 }
6489 }
6490 }
6491
6492 // If we didn't move line(s), preserve the existing selections
6493 new_selections.append(&mut contiguous_row_selections);
6494 }
6495
6496 self.transact(cx, |this, cx| {
6497 this.unfold_ranges(&unfold_ranges, true, true, cx);
6498 this.buffer.update(cx, |buffer, cx| {
6499 for (range, text) in edits {
6500 buffer.edit([(range, text)], None, cx);
6501 }
6502 });
6503 this.fold_creases(refold_creases, true, cx);
6504 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6505 });
6506 }
6507
6508 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6509 let text_layout_details = &self.text_layout_details(cx);
6510 self.transact(cx, |this, cx| {
6511 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6512 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6513 let line_mode = s.line_mode;
6514 s.move_with(|display_map, selection| {
6515 if !selection.is_empty() || line_mode {
6516 return;
6517 }
6518
6519 let mut head = selection.head();
6520 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6521 if head.column() == display_map.line_len(head.row()) {
6522 transpose_offset = display_map
6523 .buffer_snapshot
6524 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6525 }
6526
6527 if transpose_offset == 0 {
6528 return;
6529 }
6530
6531 *head.column_mut() += 1;
6532 head = display_map.clip_point(head, Bias::Right);
6533 let goal = SelectionGoal::HorizontalPosition(
6534 display_map
6535 .x_for_display_point(head, text_layout_details)
6536 .into(),
6537 );
6538 selection.collapse_to(head, goal);
6539
6540 let transpose_start = display_map
6541 .buffer_snapshot
6542 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6543 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6544 let transpose_end = display_map
6545 .buffer_snapshot
6546 .clip_offset(transpose_offset + 1, Bias::Right);
6547 if let Some(ch) =
6548 display_map.buffer_snapshot.chars_at(transpose_start).next()
6549 {
6550 edits.push((transpose_start..transpose_offset, String::new()));
6551 edits.push((transpose_end..transpose_end, ch.to_string()));
6552 }
6553 }
6554 });
6555 edits
6556 });
6557 this.buffer
6558 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6559 let selections = this.selections.all::<usize>(cx);
6560 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6561 s.select(selections);
6562 });
6563 });
6564 }
6565
6566 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6567 self.rewrap_impl(IsVimMode::No, cx)
6568 }
6569
6570 pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
6571 let buffer = self.buffer.read(cx).snapshot(cx);
6572 let selections = self.selections.all::<Point>(cx);
6573 let mut selections = selections.iter().peekable();
6574
6575 let mut edits = Vec::new();
6576 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6577
6578 while let Some(selection) = selections.next() {
6579 let mut start_row = selection.start.row;
6580 let mut end_row = selection.end.row;
6581
6582 // Skip selections that overlap with a range that has already been rewrapped.
6583 let selection_range = start_row..end_row;
6584 if rewrapped_row_ranges
6585 .iter()
6586 .any(|range| range.overlaps(&selection_range))
6587 {
6588 continue;
6589 }
6590
6591 let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
6592
6593 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6594 match language_scope.language_name().0.as_ref() {
6595 "Markdown" | "Plain Text" => {
6596 should_rewrap = true;
6597 }
6598 _ => {}
6599 }
6600 }
6601
6602 let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
6603
6604 // Since not all lines in the selection may be at the same indent
6605 // level, choose the indent size that is the most common between all
6606 // of the lines.
6607 //
6608 // If there is a tie, we use the deepest indent.
6609 let (indent_size, indent_end) = {
6610 let mut indent_size_occurrences = HashMap::default();
6611 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6612
6613 for row in start_row..=end_row {
6614 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6615 rows_by_indent_size.entry(indent).or_default().push(row);
6616 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6617 }
6618
6619 let indent_size = indent_size_occurrences
6620 .into_iter()
6621 .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
6622 .map(|(indent, _)| indent)
6623 .unwrap_or_default();
6624 let row = rows_by_indent_size[&indent_size][0];
6625 let indent_end = Point::new(row, indent_size.len);
6626
6627 (indent_size, indent_end)
6628 };
6629
6630 let mut line_prefix = indent_size.chars().collect::<String>();
6631
6632 if let Some(comment_prefix) =
6633 buffer
6634 .language_scope_at(selection.head())
6635 .and_then(|language| {
6636 language
6637 .line_comment_prefixes()
6638 .iter()
6639 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6640 .cloned()
6641 })
6642 {
6643 line_prefix.push_str(&comment_prefix);
6644 should_rewrap = true;
6645 }
6646
6647 if !should_rewrap {
6648 continue;
6649 }
6650
6651 if selection.is_empty() {
6652 'expand_upwards: while start_row > 0 {
6653 let prev_row = start_row - 1;
6654 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6655 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6656 {
6657 start_row = prev_row;
6658 } else {
6659 break 'expand_upwards;
6660 }
6661 }
6662
6663 'expand_downwards: while end_row < buffer.max_point().row {
6664 let next_row = end_row + 1;
6665 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6666 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6667 {
6668 end_row = next_row;
6669 } else {
6670 break 'expand_downwards;
6671 }
6672 }
6673 }
6674
6675 let start = Point::new(start_row, 0);
6676 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6677 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6678 let Some(lines_without_prefixes) = selection_text
6679 .lines()
6680 .map(|line| {
6681 line.strip_prefix(&line_prefix)
6682 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6683 .ok_or_else(|| {
6684 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6685 })
6686 })
6687 .collect::<Result<Vec<_>, _>>()
6688 .log_err()
6689 else {
6690 continue;
6691 };
6692
6693 let wrap_column = buffer
6694 .settings_at(Point::new(start_row, 0), cx)
6695 .preferred_line_length as usize;
6696 let wrapped_text = wrap_with_prefix(
6697 line_prefix,
6698 lines_without_prefixes.join(" "),
6699 wrap_column,
6700 tab_size,
6701 );
6702
6703 // TODO: should always use char-based diff while still supporting cursor behavior that
6704 // matches vim.
6705 let diff = match is_vim_mode {
6706 IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
6707 IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
6708 };
6709 let mut offset = start.to_offset(&buffer);
6710 let mut moved_since_edit = true;
6711
6712 for change in diff.iter_all_changes() {
6713 let value = change.value();
6714 match change.tag() {
6715 ChangeTag::Equal => {
6716 offset += value.len();
6717 moved_since_edit = true;
6718 }
6719 ChangeTag::Delete => {
6720 let start = buffer.anchor_after(offset);
6721 let end = buffer.anchor_before(offset + value.len());
6722
6723 if moved_since_edit {
6724 edits.push((start..end, String::new()));
6725 } else {
6726 edits.last_mut().unwrap().0.end = end;
6727 }
6728
6729 offset += value.len();
6730 moved_since_edit = false;
6731 }
6732 ChangeTag::Insert => {
6733 if moved_since_edit {
6734 let anchor = buffer.anchor_after(offset);
6735 edits.push((anchor..anchor, value.to_string()));
6736 } else {
6737 edits.last_mut().unwrap().1.push_str(value);
6738 }
6739
6740 moved_since_edit = false;
6741 }
6742 }
6743 }
6744
6745 rewrapped_row_ranges.push(start_row..=end_row);
6746 }
6747
6748 self.buffer
6749 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6750 }
6751
6752 pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
6753 let mut text = String::new();
6754 let buffer = self.buffer.read(cx).snapshot(cx);
6755 let mut selections = self.selections.all::<Point>(cx);
6756 let mut clipboard_selections = Vec::with_capacity(selections.len());
6757 {
6758 let max_point = buffer.max_point();
6759 let mut is_first = true;
6760 for selection in &mut selections {
6761 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6762 if is_entire_line {
6763 selection.start = Point::new(selection.start.row, 0);
6764 if !selection.is_empty() && selection.end.column == 0 {
6765 selection.end = cmp::min(max_point, selection.end);
6766 } else {
6767 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6768 }
6769 selection.goal = SelectionGoal::None;
6770 }
6771 if is_first {
6772 is_first = false;
6773 } else {
6774 text += "\n";
6775 }
6776 let mut len = 0;
6777 for chunk in buffer.text_for_range(selection.start..selection.end) {
6778 text.push_str(chunk);
6779 len += chunk.len();
6780 }
6781 clipboard_selections.push(ClipboardSelection {
6782 len,
6783 is_entire_line,
6784 first_line_indent: buffer
6785 .indent_size_for_line(MultiBufferRow(selection.start.row))
6786 .len,
6787 });
6788 }
6789 }
6790
6791 self.transact(cx, |this, cx| {
6792 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6793 s.select(selections);
6794 });
6795 this.insert("", cx);
6796 });
6797 ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
6798 }
6799
6800 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6801 let item = self.cut_common(cx);
6802 cx.write_to_clipboard(item);
6803 }
6804
6805 pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
6806 self.change_selections(None, cx, |s| {
6807 s.move_with(|snapshot, sel| {
6808 if sel.is_empty() {
6809 sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
6810 }
6811 });
6812 });
6813 let item = self.cut_common(cx);
6814 cx.set_global(KillRing(item))
6815 }
6816
6817 pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
6818 let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
6819 if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
6820 (kill_ring.text().to_string(), kill_ring.metadata_json())
6821 } else {
6822 return;
6823 }
6824 } else {
6825 return;
6826 };
6827 self.do_paste(&text, metadata, false, cx);
6828 }
6829
6830 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6831 let selections = self.selections.all::<Point>(cx);
6832 let buffer = self.buffer.read(cx).read(cx);
6833 let mut text = String::new();
6834
6835 let mut clipboard_selections = Vec::with_capacity(selections.len());
6836 {
6837 let max_point = buffer.max_point();
6838 let mut is_first = true;
6839 for selection in selections.iter() {
6840 let mut start = selection.start;
6841 let mut end = selection.end;
6842 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6843 if is_entire_line {
6844 start = Point::new(start.row, 0);
6845 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6846 }
6847 if is_first {
6848 is_first = false;
6849 } else {
6850 text += "\n";
6851 }
6852 let mut len = 0;
6853 for chunk in buffer.text_for_range(start..end) {
6854 text.push_str(chunk);
6855 len += chunk.len();
6856 }
6857 clipboard_selections.push(ClipboardSelection {
6858 len,
6859 is_entire_line,
6860 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6861 });
6862 }
6863 }
6864
6865 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6866 text,
6867 clipboard_selections,
6868 ));
6869 }
6870
6871 pub fn do_paste(
6872 &mut self,
6873 text: &String,
6874 clipboard_selections: Option<Vec<ClipboardSelection>>,
6875 handle_entire_lines: bool,
6876 cx: &mut ViewContext<Self>,
6877 ) {
6878 if self.read_only(cx) {
6879 return;
6880 }
6881
6882 let clipboard_text = Cow::Borrowed(text);
6883
6884 self.transact(cx, |this, cx| {
6885 if let Some(mut clipboard_selections) = clipboard_selections {
6886 let old_selections = this.selections.all::<usize>(cx);
6887 let all_selections_were_entire_line =
6888 clipboard_selections.iter().all(|s| s.is_entire_line);
6889 let first_selection_indent_column =
6890 clipboard_selections.first().map(|s| s.first_line_indent);
6891 if clipboard_selections.len() != old_selections.len() {
6892 clipboard_selections.drain(..);
6893 }
6894 let cursor_offset = this.selections.last::<usize>(cx).head();
6895 let mut auto_indent_on_paste = true;
6896
6897 this.buffer.update(cx, |buffer, cx| {
6898 let snapshot = buffer.read(cx);
6899 auto_indent_on_paste =
6900 snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
6901
6902 let mut start_offset = 0;
6903 let mut edits = Vec::new();
6904 let mut original_indent_columns = Vec::new();
6905 for (ix, selection) in old_selections.iter().enumerate() {
6906 let to_insert;
6907 let entire_line;
6908 let original_indent_column;
6909 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6910 let end_offset = start_offset + clipboard_selection.len;
6911 to_insert = &clipboard_text[start_offset..end_offset];
6912 entire_line = clipboard_selection.is_entire_line;
6913 start_offset = end_offset + 1;
6914 original_indent_column = Some(clipboard_selection.first_line_indent);
6915 } else {
6916 to_insert = clipboard_text.as_str();
6917 entire_line = all_selections_were_entire_line;
6918 original_indent_column = first_selection_indent_column
6919 }
6920
6921 // If the corresponding selection was empty when this slice of the
6922 // clipboard text was written, then the entire line containing the
6923 // selection was copied. If this selection is also currently empty,
6924 // then paste the line before the current line of the buffer.
6925 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6926 let column = selection.start.to_point(&snapshot).column as usize;
6927 let line_start = selection.start - column;
6928 line_start..line_start
6929 } else {
6930 selection.range()
6931 };
6932
6933 edits.push((range, to_insert));
6934 original_indent_columns.extend(original_indent_column);
6935 }
6936 drop(snapshot);
6937
6938 buffer.edit(
6939 edits,
6940 if auto_indent_on_paste {
6941 Some(AutoindentMode::Block {
6942 original_indent_columns,
6943 })
6944 } else {
6945 None
6946 },
6947 cx,
6948 );
6949 });
6950
6951 let selections = this.selections.all::<usize>(cx);
6952 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6953 } else {
6954 this.insert(&clipboard_text, cx);
6955 }
6956 });
6957 }
6958
6959 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
6960 if let Some(item) = cx.read_from_clipboard() {
6961 let entries = item.entries();
6962
6963 match entries.first() {
6964 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
6965 // of all the pasted entries.
6966 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
6967 .do_paste(
6968 clipboard_string.text(),
6969 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
6970 true,
6971 cx,
6972 ),
6973 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
6974 }
6975 }
6976 }
6977
6978 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
6979 if self.read_only(cx) {
6980 return;
6981 }
6982
6983 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
6984 if let Some((selections, _)) =
6985 self.selection_history.transaction(transaction_id).cloned()
6986 {
6987 self.change_selections(None, cx, |s| {
6988 s.select_anchors(selections.to_vec());
6989 });
6990 }
6991 self.request_autoscroll(Autoscroll::fit(), cx);
6992 self.unmark_text(cx);
6993 self.refresh_inline_completion(true, false, cx);
6994 cx.emit(EditorEvent::Edited { transaction_id });
6995 cx.emit(EditorEvent::TransactionUndone { transaction_id });
6996 }
6997 }
6998
6999 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7000 if self.read_only(cx) {
7001 return;
7002 }
7003
7004 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7005 if let Some((_, Some(selections))) =
7006 self.selection_history.transaction(transaction_id).cloned()
7007 {
7008 self.change_selections(None, cx, |s| {
7009 s.select_anchors(selections.to_vec());
7010 });
7011 }
7012 self.request_autoscroll(Autoscroll::fit(), cx);
7013 self.unmark_text(cx);
7014 self.refresh_inline_completion(true, false, cx);
7015 cx.emit(EditorEvent::Edited { transaction_id });
7016 }
7017 }
7018
7019 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7020 self.buffer
7021 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7022 }
7023
7024 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7025 self.buffer
7026 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7027 }
7028
7029 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7030 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7031 let line_mode = s.line_mode;
7032 s.move_with(|map, selection| {
7033 let cursor = if selection.is_empty() && !line_mode {
7034 movement::left(map, selection.start)
7035 } else {
7036 selection.start
7037 };
7038 selection.collapse_to(cursor, SelectionGoal::None);
7039 });
7040 })
7041 }
7042
7043 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7044 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7045 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7046 })
7047 }
7048
7049 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7050 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7051 let line_mode = s.line_mode;
7052 s.move_with(|map, selection| {
7053 let cursor = if selection.is_empty() && !line_mode {
7054 movement::right(map, selection.end)
7055 } else {
7056 selection.end
7057 };
7058 selection.collapse_to(cursor, SelectionGoal::None)
7059 });
7060 })
7061 }
7062
7063 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7064 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7065 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7066 })
7067 }
7068
7069 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7070 if self.take_rename(true, cx).is_some() {
7071 return;
7072 }
7073
7074 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7075 cx.propagate();
7076 return;
7077 }
7078
7079 let text_layout_details = &self.text_layout_details(cx);
7080 let selection_count = self.selections.count();
7081 let first_selection = self.selections.first_anchor();
7082
7083 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7084 let line_mode = s.line_mode;
7085 s.move_with(|map, selection| {
7086 if !selection.is_empty() && !line_mode {
7087 selection.goal = SelectionGoal::None;
7088 }
7089 let (cursor, goal) = movement::up(
7090 map,
7091 selection.start,
7092 selection.goal,
7093 false,
7094 text_layout_details,
7095 );
7096 selection.collapse_to(cursor, goal);
7097 });
7098 });
7099
7100 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7101 {
7102 cx.propagate();
7103 }
7104 }
7105
7106 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7107 if self.take_rename(true, cx).is_some() {
7108 return;
7109 }
7110
7111 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7112 cx.propagate();
7113 return;
7114 }
7115
7116 let text_layout_details = &self.text_layout_details(cx);
7117
7118 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7119 let line_mode = s.line_mode;
7120 s.move_with(|map, selection| {
7121 if !selection.is_empty() && !line_mode {
7122 selection.goal = SelectionGoal::None;
7123 }
7124 let (cursor, goal) = movement::up_by_rows(
7125 map,
7126 selection.start,
7127 action.lines,
7128 selection.goal,
7129 false,
7130 text_layout_details,
7131 );
7132 selection.collapse_to(cursor, goal);
7133 });
7134 })
7135 }
7136
7137 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7138 if self.take_rename(true, cx).is_some() {
7139 return;
7140 }
7141
7142 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7143 cx.propagate();
7144 return;
7145 }
7146
7147 let text_layout_details = &self.text_layout_details(cx);
7148
7149 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7150 let line_mode = s.line_mode;
7151 s.move_with(|map, selection| {
7152 if !selection.is_empty() && !line_mode {
7153 selection.goal = SelectionGoal::None;
7154 }
7155 let (cursor, goal) = movement::down_by_rows(
7156 map,
7157 selection.start,
7158 action.lines,
7159 selection.goal,
7160 false,
7161 text_layout_details,
7162 );
7163 selection.collapse_to(cursor, goal);
7164 });
7165 })
7166 }
7167
7168 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7169 let text_layout_details = &self.text_layout_details(cx);
7170 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7171 s.move_heads_with(|map, head, goal| {
7172 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7173 })
7174 })
7175 }
7176
7177 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7178 let text_layout_details = &self.text_layout_details(cx);
7179 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7180 s.move_heads_with(|map, head, goal| {
7181 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7182 })
7183 })
7184 }
7185
7186 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7187 let Some(row_count) = self.visible_row_count() else {
7188 return;
7189 };
7190
7191 let text_layout_details = &self.text_layout_details(cx);
7192
7193 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7194 s.move_heads_with(|map, head, goal| {
7195 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7196 })
7197 })
7198 }
7199
7200 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7201 if self.take_rename(true, cx).is_some() {
7202 return;
7203 }
7204
7205 if self
7206 .context_menu
7207 .borrow_mut()
7208 .as_mut()
7209 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7210 .unwrap_or(false)
7211 {
7212 return;
7213 }
7214
7215 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7216 cx.propagate();
7217 return;
7218 }
7219
7220 let Some(row_count) = self.visible_row_count() else {
7221 return;
7222 };
7223
7224 let autoscroll = if action.center_cursor {
7225 Autoscroll::center()
7226 } else {
7227 Autoscroll::fit()
7228 };
7229
7230 let text_layout_details = &self.text_layout_details(cx);
7231
7232 self.change_selections(Some(autoscroll), cx, |s| {
7233 let line_mode = s.line_mode;
7234 s.move_with(|map, selection| {
7235 if !selection.is_empty() && !line_mode {
7236 selection.goal = SelectionGoal::None;
7237 }
7238 let (cursor, goal) = movement::up_by_rows(
7239 map,
7240 selection.end,
7241 row_count,
7242 selection.goal,
7243 false,
7244 text_layout_details,
7245 );
7246 selection.collapse_to(cursor, goal);
7247 });
7248 });
7249 }
7250
7251 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7252 let text_layout_details = &self.text_layout_details(cx);
7253 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7254 s.move_heads_with(|map, head, goal| {
7255 movement::up(map, head, goal, false, text_layout_details)
7256 })
7257 })
7258 }
7259
7260 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7261 self.take_rename(true, cx);
7262
7263 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7264 cx.propagate();
7265 return;
7266 }
7267
7268 let text_layout_details = &self.text_layout_details(cx);
7269 let selection_count = self.selections.count();
7270 let first_selection = self.selections.first_anchor();
7271
7272 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7273 let line_mode = s.line_mode;
7274 s.move_with(|map, selection| {
7275 if !selection.is_empty() && !line_mode {
7276 selection.goal = SelectionGoal::None;
7277 }
7278 let (cursor, goal) = movement::down(
7279 map,
7280 selection.end,
7281 selection.goal,
7282 false,
7283 text_layout_details,
7284 );
7285 selection.collapse_to(cursor, goal);
7286 });
7287 });
7288
7289 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7290 {
7291 cx.propagate();
7292 }
7293 }
7294
7295 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7296 let Some(row_count) = self.visible_row_count() else {
7297 return;
7298 };
7299
7300 let text_layout_details = &self.text_layout_details(cx);
7301
7302 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7303 s.move_heads_with(|map, head, goal| {
7304 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7305 })
7306 })
7307 }
7308
7309 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7310 if self.take_rename(true, cx).is_some() {
7311 return;
7312 }
7313
7314 if self
7315 .context_menu
7316 .borrow_mut()
7317 .as_mut()
7318 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7319 .unwrap_or(false)
7320 {
7321 return;
7322 }
7323
7324 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7325 cx.propagate();
7326 return;
7327 }
7328
7329 let Some(row_count) = self.visible_row_count() else {
7330 return;
7331 };
7332
7333 let autoscroll = if action.center_cursor {
7334 Autoscroll::center()
7335 } else {
7336 Autoscroll::fit()
7337 };
7338
7339 let text_layout_details = &self.text_layout_details(cx);
7340 self.change_selections(Some(autoscroll), cx, |s| {
7341 let line_mode = s.line_mode;
7342 s.move_with(|map, selection| {
7343 if !selection.is_empty() && !line_mode {
7344 selection.goal = SelectionGoal::None;
7345 }
7346 let (cursor, goal) = movement::down_by_rows(
7347 map,
7348 selection.end,
7349 row_count,
7350 selection.goal,
7351 false,
7352 text_layout_details,
7353 );
7354 selection.collapse_to(cursor, goal);
7355 });
7356 });
7357 }
7358
7359 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7360 let text_layout_details = &self.text_layout_details(cx);
7361 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7362 s.move_heads_with(|map, head, goal| {
7363 movement::down(map, head, goal, false, text_layout_details)
7364 })
7365 });
7366 }
7367
7368 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7369 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7370 context_menu.select_first(self.completion_provider.as_deref(), cx);
7371 }
7372 }
7373
7374 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7375 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7376 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7377 }
7378 }
7379
7380 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7381 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7382 context_menu.select_next(self.completion_provider.as_deref(), cx);
7383 }
7384 }
7385
7386 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7387 if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
7388 context_menu.select_last(self.completion_provider.as_deref(), cx);
7389 }
7390 }
7391
7392 pub fn move_to_previous_word_start(
7393 &mut self,
7394 _: &MoveToPreviousWordStart,
7395 cx: &mut ViewContext<Self>,
7396 ) {
7397 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7398 s.move_cursors_with(|map, head, _| {
7399 (
7400 movement::previous_word_start(map, head),
7401 SelectionGoal::None,
7402 )
7403 });
7404 })
7405 }
7406
7407 pub fn move_to_previous_subword_start(
7408 &mut self,
7409 _: &MoveToPreviousSubwordStart,
7410 cx: &mut ViewContext<Self>,
7411 ) {
7412 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7413 s.move_cursors_with(|map, head, _| {
7414 (
7415 movement::previous_subword_start(map, head),
7416 SelectionGoal::None,
7417 )
7418 });
7419 })
7420 }
7421
7422 pub fn select_to_previous_word_start(
7423 &mut self,
7424 _: &SelectToPreviousWordStart,
7425 cx: &mut ViewContext<Self>,
7426 ) {
7427 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7428 s.move_heads_with(|map, head, _| {
7429 (
7430 movement::previous_word_start(map, head),
7431 SelectionGoal::None,
7432 )
7433 });
7434 })
7435 }
7436
7437 pub fn select_to_previous_subword_start(
7438 &mut self,
7439 _: &SelectToPreviousSubwordStart,
7440 cx: &mut ViewContext<Self>,
7441 ) {
7442 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7443 s.move_heads_with(|map, head, _| {
7444 (
7445 movement::previous_subword_start(map, head),
7446 SelectionGoal::None,
7447 )
7448 });
7449 })
7450 }
7451
7452 pub fn delete_to_previous_word_start(
7453 &mut self,
7454 action: &DeleteToPreviousWordStart,
7455 cx: &mut ViewContext<Self>,
7456 ) {
7457 self.transact(cx, |this, cx| {
7458 this.select_autoclose_pair(cx);
7459 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7460 let line_mode = s.line_mode;
7461 s.move_with(|map, selection| {
7462 if selection.is_empty() && !line_mode {
7463 let cursor = if action.ignore_newlines {
7464 movement::previous_word_start(map, selection.head())
7465 } else {
7466 movement::previous_word_start_or_newline(map, selection.head())
7467 };
7468 selection.set_head(cursor, SelectionGoal::None);
7469 }
7470 });
7471 });
7472 this.insert("", cx);
7473 });
7474 }
7475
7476 pub fn delete_to_previous_subword_start(
7477 &mut self,
7478 _: &DeleteToPreviousSubwordStart,
7479 cx: &mut ViewContext<Self>,
7480 ) {
7481 self.transact(cx, |this, cx| {
7482 this.select_autoclose_pair(cx);
7483 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7484 let line_mode = s.line_mode;
7485 s.move_with(|map, selection| {
7486 if selection.is_empty() && !line_mode {
7487 let cursor = movement::previous_subword_start(map, selection.head());
7488 selection.set_head(cursor, SelectionGoal::None);
7489 }
7490 });
7491 });
7492 this.insert("", cx);
7493 });
7494 }
7495
7496 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7497 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7498 s.move_cursors_with(|map, head, _| {
7499 (movement::next_word_end(map, head), SelectionGoal::None)
7500 });
7501 })
7502 }
7503
7504 pub fn move_to_next_subword_end(
7505 &mut self,
7506 _: &MoveToNextSubwordEnd,
7507 cx: &mut ViewContext<Self>,
7508 ) {
7509 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7510 s.move_cursors_with(|map, head, _| {
7511 (movement::next_subword_end(map, head), SelectionGoal::None)
7512 });
7513 })
7514 }
7515
7516 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7517 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7518 s.move_heads_with(|map, head, _| {
7519 (movement::next_word_end(map, head), SelectionGoal::None)
7520 });
7521 })
7522 }
7523
7524 pub fn select_to_next_subword_end(
7525 &mut self,
7526 _: &SelectToNextSubwordEnd,
7527 cx: &mut ViewContext<Self>,
7528 ) {
7529 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7530 s.move_heads_with(|map, head, _| {
7531 (movement::next_subword_end(map, head), SelectionGoal::None)
7532 });
7533 })
7534 }
7535
7536 pub fn delete_to_next_word_end(
7537 &mut self,
7538 action: &DeleteToNextWordEnd,
7539 cx: &mut ViewContext<Self>,
7540 ) {
7541 self.transact(cx, |this, cx| {
7542 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7543 let line_mode = s.line_mode;
7544 s.move_with(|map, selection| {
7545 if selection.is_empty() && !line_mode {
7546 let cursor = if action.ignore_newlines {
7547 movement::next_word_end(map, selection.head())
7548 } else {
7549 movement::next_word_end_or_newline(map, selection.head())
7550 };
7551 selection.set_head(cursor, SelectionGoal::None);
7552 }
7553 });
7554 });
7555 this.insert("", cx);
7556 });
7557 }
7558
7559 pub fn delete_to_next_subword_end(
7560 &mut self,
7561 _: &DeleteToNextSubwordEnd,
7562 cx: &mut ViewContext<Self>,
7563 ) {
7564 self.transact(cx, |this, cx| {
7565 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7566 s.move_with(|map, selection| {
7567 if selection.is_empty() {
7568 let cursor = movement::next_subword_end(map, selection.head());
7569 selection.set_head(cursor, SelectionGoal::None);
7570 }
7571 });
7572 });
7573 this.insert("", cx);
7574 });
7575 }
7576
7577 pub fn move_to_beginning_of_line(
7578 &mut self,
7579 action: &MoveToBeginningOfLine,
7580 cx: &mut ViewContext<Self>,
7581 ) {
7582 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7583 s.move_cursors_with(|map, head, _| {
7584 (
7585 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7586 SelectionGoal::None,
7587 )
7588 });
7589 })
7590 }
7591
7592 pub fn select_to_beginning_of_line(
7593 &mut self,
7594 action: &SelectToBeginningOfLine,
7595 cx: &mut ViewContext<Self>,
7596 ) {
7597 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7598 s.move_heads_with(|map, head, _| {
7599 (
7600 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7601 SelectionGoal::None,
7602 )
7603 });
7604 });
7605 }
7606
7607 pub fn delete_to_beginning_of_line(
7608 &mut self,
7609 _: &DeleteToBeginningOfLine,
7610 cx: &mut ViewContext<Self>,
7611 ) {
7612 self.transact(cx, |this, cx| {
7613 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7614 s.move_with(|_, selection| {
7615 selection.reversed = true;
7616 });
7617 });
7618
7619 this.select_to_beginning_of_line(
7620 &SelectToBeginningOfLine {
7621 stop_at_soft_wraps: false,
7622 },
7623 cx,
7624 );
7625 this.backspace(&Backspace, cx);
7626 });
7627 }
7628
7629 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7630 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7631 s.move_cursors_with(|map, head, _| {
7632 (
7633 movement::line_end(map, head, action.stop_at_soft_wraps),
7634 SelectionGoal::None,
7635 )
7636 });
7637 })
7638 }
7639
7640 pub fn select_to_end_of_line(
7641 &mut self,
7642 action: &SelectToEndOfLine,
7643 cx: &mut ViewContext<Self>,
7644 ) {
7645 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7646 s.move_heads_with(|map, head, _| {
7647 (
7648 movement::line_end(map, head, action.stop_at_soft_wraps),
7649 SelectionGoal::None,
7650 )
7651 });
7652 })
7653 }
7654
7655 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7656 self.transact(cx, |this, cx| {
7657 this.select_to_end_of_line(
7658 &SelectToEndOfLine {
7659 stop_at_soft_wraps: false,
7660 },
7661 cx,
7662 );
7663 this.delete(&Delete, cx);
7664 });
7665 }
7666
7667 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7668 self.transact(cx, |this, cx| {
7669 this.select_to_end_of_line(
7670 &SelectToEndOfLine {
7671 stop_at_soft_wraps: false,
7672 },
7673 cx,
7674 );
7675 this.cut(&Cut, cx);
7676 });
7677 }
7678
7679 pub fn move_to_start_of_paragraph(
7680 &mut self,
7681 _: &MoveToStartOfParagraph,
7682 cx: &mut ViewContext<Self>,
7683 ) {
7684 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7685 cx.propagate();
7686 return;
7687 }
7688
7689 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7690 s.move_with(|map, selection| {
7691 selection.collapse_to(
7692 movement::start_of_paragraph(map, selection.head(), 1),
7693 SelectionGoal::None,
7694 )
7695 });
7696 })
7697 }
7698
7699 pub fn move_to_end_of_paragraph(
7700 &mut self,
7701 _: &MoveToEndOfParagraph,
7702 cx: &mut ViewContext<Self>,
7703 ) {
7704 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7705 cx.propagate();
7706 return;
7707 }
7708
7709 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7710 s.move_with(|map, selection| {
7711 selection.collapse_to(
7712 movement::end_of_paragraph(map, selection.head(), 1),
7713 SelectionGoal::None,
7714 )
7715 });
7716 })
7717 }
7718
7719 pub fn select_to_start_of_paragraph(
7720 &mut self,
7721 _: &SelectToStartOfParagraph,
7722 cx: &mut ViewContext<Self>,
7723 ) {
7724 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7725 cx.propagate();
7726 return;
7727 }
7728
7729 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7730 s.move_heads_with(|map, head, _| {
7731 (
7732 movement::start_of_paragraph(map, head, 1),
7733 SelectionGoal::None,
7734 )
7735 });
7736 })
7737 }
7738
7739 pub fn select_to_end_of_paragraph(
7740 &mut self,
7741 _: &SelectToEndOfParagraph,
7742 cx: &mut ViewContext<Self>,
7743 ) {
7744 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7745 cx.propagate();
7746 return;
7747 }
7748
7749 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7750 s.move_heads_with(|map, head, _| {
7751 (
7752 movement::end_of_paragraph(map, head, 1),
7753 SelectionGoal::None,
7754 )
7755 });
7756 })
7757 }
7758
7759 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7760 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7761 cx.propagate();
7762 return;
7763 }
7764
7765 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7766 s.select_ranges(vec![0..0]);
7767 });
7768 }
7769
7770 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7771 let mut selection = self.selections.last::<Point>(cx);
7772 selection.set_head(Point::zero(), SelectionGoal::None);
7773
7774 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7775 s.select(vec![selection]);
7776 });
7777 }
7778
7779 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7780 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7781 cx.propagate();
7782 return;
7783 }
7784
7785 let cursor = self.buffer.read(cx).read(cx).len();
7786 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7787 s.select_ranges(vec![cursor..cursor])
7788 });
7789 }
7790
7791 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7792 self.nav_history = nav_history;
7793 }
7794
7795 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7796 self.nav_history.as_ref()
7797 }
7798
7799 fn push_to_nav_history(
7800 &mut self,
7801 cursor_anchor: Anchor,
7802 new_position: Option<Point>,
7803 cx: &mut ViewContext<Self>,
7804 ) {
7805 if let Some(nav_history) = self.nav_history.as_mut() {
7806 let buffer = self.buffer.read(cx).read(cx);
7807 let cursor_position = cursor_anchor.to_point(&buffer);
7808 let scroll_state = self.scroll_manager.anchor();
7809 let scroll_top_row = scroll_state.top_row(&buffer);
7810 drop(buffer);
7811
7812 if let Some(new_position) = new_position {
7813 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7814 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7815 return;
7816 }
7817 }
7818
7819 nav_history.push(
7820 Some(NavigationData {
7821 cursor_anchor,
7822 cursor_position,
7823 scroll_anchor: scroll_state,
7824 scroll_top_row,
7825 }),
7826 cx,
7827 );
7828 }
7829 }
7830
7831 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7832 let buffer = self.buffer.read(cx).snapshot(cx);
7833 let mut selection = self.selections.first::<usize>(cx);
7834 selection.set_head(buffer.len(), SelectionGoal::None);
7835 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7836 s.select(vec![selection]);
7837 });
7838 }
7839
7840 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7841 let end = self.buffer.read(cx).read(cx).len();
7842 self.change_selections(None, cx, |s| {
7843 s.select_ranges(vec![0..end]);
7844 });
7845 }
7846
7847 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7848 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7849 let mut selections = self.selections.all::<Point>(cx);
7850 let max_point = display_map.buffer_snapshot.max_point();
7851 for selection in &mut selections {
7852 let rows = selection.spanned_rows(true, &display_map);
7853 selection.start = Point::new(rows.start.0, 0);
7854 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7855 selection.reversed = false;
7856 }
7857 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7858 s.select(selections);
7859 });
7860 }
7861
7862 pub fn split_selection_into_lines(
7863 &mut self,
7864 _: &SplitSelectionIntoLines,
7865 cx: &mut ViewContext<Self>,
7866 ) {
7867 let mut to_unfold = Vec::new();
7868 let mut new_selection_ranges = Vec::new();
7869 {
7870 let selections = self.selections.all::<Point>(cx);
7871 let buffer = self.buffer.read(cx).read(cx);
7872 for selection in selections {
7873 for row in selection.start.row..selection.end.row {
7874 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7875 new_selection_ranges.push(cursor..cursor);
7876 }
7877 new_selection_ranges.push(selection.end..selection.end);
7878 to_unfold.push(selection.start..selection.end);
7879 }
7880 }
7881 self.unfold_ranges(&to_unfold, true, true, cx);
7882 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7883 s.select_ranges(new_selection_ranges);
7884 });
7885 }
7886
7887 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7888 self.add_selection(true, cx);
7889 }
7890
7891 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7892 self.add_selection(false, cx);
7893 }
7894
7895 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7896 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7897 let mut selections = self.selections.all::<Point>(cx);
7898 let text_layout_details = self.text_layout_details(cx);
7899 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7900 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7901 let range = oldest_selection.display_range(&display_map).sorted();
7902
7903 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7904 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7905 let positions = start_x.min(end_x)..start_x.max(end_x);
7906
7907 selections.clear();
7908 let mut stack = Vec::new();
7909 for row in range.start.row().0..=range.end.row().0 {
7910 if let Some(selection) = self.selections.build_columnar_selection(
7911 &display_map,
7912 DisplayRow(row),
7913 &positions,
7914 oldest_selection.reversed,
7915 &text_layout_details,
7916 ) {
7917 stack.push(selection.id);
7918 selections.push(selection);
7919 }
7920 }
7921
7922 if above {
7923 stack.reverse();
7924 }
7925
7926 AddSelectionsState { above, stack }
7927 });
7928
7929 let last_added_selection = *state.stack.last().unwrap();
7930 let mut new_selections = Vec::new();
7931 if above == state.above {
7932 let end_row = if above {
7933 DisplayRow(0)
7934 } else {
7935 display_map.max_point().row()
7936 };
7937
7938 'outer: for selection in selections {
7939 if selection.id == last_added_selection {
7940 let range = selection.display_range(&display_map).sorted();
7941 debug_assert_eq!(range.start.row(), range.end.row());
7942 let mut row = range.start.row();
7943 let positions =
7944 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7945 px(start)..px(end)
7946 } else {
7947 let start_x =
7948 display_map.x_for_display_point(range.start, &text_layout_details);
7949 let end_x =
7950 display_map.x_for_display_point(range.end, &text_layout_details);
7951 start_x.min(end_x)..start_x.max(end_x)
7952 };
7953
7954 while row != end_row {
7955 if above {
7956 row.0 -= 1;
7957 } else {
7958 row.0 += 1;
7959 }
7960
7961 if let Some(new_selection) = self.selections.build_columnar_selection(
7962 &display_map,
7963 row,
7964 &positions,
7965 selection.reversed,
7966 &text_layout_details,
7967 ) {
7968 state.stack.push(new_selection.id);
7969 if above {
7970 new_selections.push(new_selection);
7971 new_selections.push(selection);
7972 } else {
7973 new_selections.push(selection);
7974 new_selections.push(new_selection);
7975 }
7976
7977 continue 'outer;
7978 }
7979 }
7980 }
7981
7982 new_selections.push(selection);
7983 }
7984 } else {
7985 new_selections = selections;
7986 new_selections.retain(|s| s.id != last_added_selection);
7987 state.stack.pop();
7988 }
7989
7990 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7991 s.select(new_selections);
7992 });
7993 if state.stack.len() > 1 {
7994 self.add_selections_state = Some(state);
7995 }
7996 }
7997
7998 pub fn select_next_match_internal(
7999 &mut self,
8000 display_map: &DisplaySnapshot,
8001 replace_newest: bool,
8002 autoscroll: Option<Autoscroll>,
8003 cx: &mut ViewContext<Self>,
8004 ) -> Result<()> {
8005 fn select_next_match_ranges(
8006 this: &mut Editor,
8007 range: Range<usize>,
8008 replace_newest: bool,
8009 auto_scroll: Option<Autoscroll>,
8010 cx: &mut ViewContext<Editor>,
8011 ) {
8012 this.unfold_ranges(&[range.clone()], false, true, cx);
8013 this.change_selections(auto_scroll, cx, |s| {
8014 if replace_newest {
8015 s.delete(s.newest_anchor().id);
8016 }
8017 s.insert_range(range.clone());
8018 });
8019 }
8020
8021 let buffer = &display_map.buffer_snapshot;
8022 let mut selections = self.selections.all::<usize>(cx);
8023 if let Some(mut select_next_state) = self.select_next_state.take() {
8024 let query = &select_next_state.query;
8025 if !select_next_state.done {
8026 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8027 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8028 let mut next_selected_range = None;
8029
8030 let bytes_after_last_selection =
8031 buffer.bytes_in_range(last_selection.end..buffer.len());
8032 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8033 let query_matches = query
8034 .stream_find_iter(bytes_after_last_selection)
8035 .map(|result| (last_selection.end, result))
8036 .chain(
8037 query
8038 .stream_find_iter(bytes_before_first_selection)
8039 .map(|result| (0, result)),
8040 );
8041
8042 for (start_offset, query_match) in query_matches {
8043 let query_match = query_match.unwrap(); // can only fail due to I/O
8044 let offset_range =
8045 start_offset + query_match.start()..start_offset + query_match.end();
8046 let display_range = offset_range.start.to_display_point(display_map)
8047 ..offset_range.end.to_display_point(display_map);
8048
8049 if !select_next_state.wordwise
8050 || (!movement::is_inside_word(display_map, display_range.start)
8051 && !movement::is_inside_word(display_map, display_range.end))
8052 {
8053 // TODO: This is n^2, because we might check all the selections
8054 if !selections
8055 .iter()
8056 .any(|selection| selection.range().overlaps(&offset_range))
8057 {
8058 next_selected_range = Some(offset_range);
8059 break;
8060 }
8061 }
8062 }
8063
8064 if let Some(next_selected_range) = next_selected_range {
8065 select_next_match_ranges(
8066 self,
8067 next_selected_range,
8068 replace_newest,
8069 autoscroll,
8070 cx,
8071 );
8072 } else {
8073 select_next_state.done = true;
8074 }
8075 }
8076
8077 self.select_next_state = Some(select_next_state);
8078 } else {
8079 let mut only_carets = true;
8080 let mut same_text_selected = true;
8081 let mut selected_text = None;
8082
8083 let mut selections_iter = selections.iter().peekable();
8084 while let Some(selection) = selections_iter.next() {
8085 if selection.start != selection.end {
8086 only_carets = false;
8087 }
8088
8089 if same_text_selected {
8090 if selected_text.is_none() {
8091 selected_text =
8092 Some(buffer.text_for_range(selection.range()).collect::<String>());
8093 }
8094
8095 if let Some(next_selection) = selections_iter.peek() {
8096 if next_selection.range().len() == selection.range().len() {
8097 let next_selected_text = buffer
8098 .text_for_range(next_selection.range())
8099 .collect::<String>();
8100 if Some(next_selected_text) != selected_text {
8101 same_text_selected = false;
8102 selected_text = None;
8103 }
8104 } else {
8105 same_text_selected = false;
8106 selected_text = None;
8107 }
8108 }
8109 }
8110 }
8111
8112 if only_carets {
8113 for selection in &mut selections {
8114 let word_range = movement::surrounding_word(
8115 display_map,
8116 selection.start.to_display_point(display_map),
8117 );
8118 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8119 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8120 selection.goal = SelectionGoal::None;
8121 selection.reversed = false;
8122 select_next_match_ranges(
8123 self,
8124 selection.start..selection.end,
8125 replace_newest,
8126 autoscroll,
8127 cx,
8128 );
8129 }
8130
8131 if selections.len() == 1 {
8132 let selection = selections
8133 .last()
8134 .expect("ensured that there's only one selection");
8135 let query = buffer
8136 .text_for_range(selection.start..selection.end)
8137 .collect::<String>();
8138 let is_empty = query.is_empty();
8139 let select_state = SelectNextState {
8140 query: AhoCorasick::new(&[query])?,
8141 wordwise: true,
8142 done: is_empty,
8143 };
8144 self.select_next_state = Some(select_state);
8145 } else {
8146 self.select_next_state = None;
8147 }
8148 } else if let Some(selected_text) = selected_text {
8149 self.select_next_state = Some(SelectNextState {
8150 query: AhoCorasick::new(&[selected_text])?,
8151 wordwise: false,
8152 done: false,
8153 });
8154 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8155 }
8156 }
8157 Ok(())
8158 }
8159
8160 pub fn select_all_matches(
8161 &mut self,
8162 _action: &SelectAllMatches,
8163 cx: &mut ViewContext<Self>,
8164 ) -> Result<()> {
8165 self.push_to_selection_history();
8166 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8167
8168 self.select_next_match_internal(&display_map, false, None, cx)?;
8169 let Some(select_next_state) = self.select_next_state.as_mut() else {
8170 return Ok(());
8171 };
8172 if select_next_state.done {
8173 return Ok(());
8174 }
8175
8176 let mut new_selections = self.selections.all::<usize>(cx);
8177
8178 let buffer = &display_map.buffer_snapshot;
8179 let query_matches = select_next_state
8180 .query
8181 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8182
8183 for query_match in query_matches {
8184 let query_match = query_match.unwrap(); // can only fail due to I/O
8185 let offset_range = query_match.start()..query_match.end();
8186 let display_range = offset_range.start.to_display_point(&display_map)
8187 ..offset_range.end.to_display_point(&display_map);
8188
8189 if !select_next_state.wordwise
8190 || (!movement::is_inside_word(&display_map, display_range.start)
8191 && !movement::is_inside_word(&display_map, display_range.end))
8192 {
8193 self.selections.change_with(cx, |selections| {
8194 new_selections.push(Selection {
8195 id: selections.new_selection_id(),
8196 start: offset_range.start,
8197 end: offset_range.end,
8198 reversed: false,
8199 goal: SelectionGoal::None,
8200 });
8201 });
8202 }
8203 }
8204
8205 new_selections.sort_by_key(|selection| selection.start);
8206 let mut ix = 0;
8207 while ix + 1 < new_selections.len() {
8208 let current_selection = &new_selections[ix];
8209 let next_selection = &new_selections[ix + 1];
8210 if current_selection.range().overlaps(&next_selection.range()) {
8211 if current_selection.id < next_selection.id {
8212 new_selections.remove(ix + 1);
8213 } else {
8214 new_selections.remove(ix);
8215 }
8216 } else {
8217 ix += 1;
8218 }
8219 }
8220
8221 select_next_state.done = true;
8222 self.unfold_ranges(
8223 &new_selections
8224 .iter()
8225 .map(|selection| selection.range())
8226 .collect::<Vec<_>>(),
8227 false,
8228 false,
8229 cx,
8230 );
8231 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8232 selections.select(new_selections)
8233 });
8234
8235 Ok(())
8236 }
8237
8238 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8239 self.push_to_selection_history();
8240 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8241 self.select_next_match_internal(
8242 &display_map,
8243 action.replace_newest,
8244 Some(Autoscroll::newest()),
8245 cx,
8246 )?;
8247 Ok(())
8248 }
8249
8250 pub fn select_previous(
8251 &mut self,
8252 action: &SelectPrevious,
8253 cx: &mut ViewContext<Self>,
8254 ) -> Result<()> {
8255 self.push_to_selection_history();
8256 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8257 let buffer = &display_map.buffer_snapshot;
8258 let mut selections = self.selections.all::<usize>(cx);
8259 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8260 let query = &select_prev_state.query;
8261 if !select_prev_state.done {
8262 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8263 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8264 let mut next_selected_range = None;
8265 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8266 let bytes_before_last_selection =
8267 buffer.reversed_bytes_in_range(0..last_selection.start);
8268 let bytes_after_first_selection =
8269 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8270 let query_matches = query
8271 .stream_find_iter(bytes_before_last_selection)
8272 .map(|result| (last_selection.start, result))
8273 .chain(
8274 query
8275 .stream_find_iter(bytes_after_first_selection)
8276 .map(|result| (buffer.len(), result)),
8277 );
8278 for (end_offset, query_match) in query_matches {
8279 let query_match = query_match.unwrap(); // can only fail due to I/O
8280 let offset_range =
8281 end_offset - query_match.end()..end_offset - query_match.start();
8282 let display_range = offset_range.start.to_display_point(&display_map)
8283 ..offset_range.end.to_display_point(&display_map);
8284
8285 if !select_prev_state.wordwise
8286 || (!movement::is_inside_word(&display_map, display_range.start)
8287 && !movement::is_inside_word(&display_map, display_range.end))
8288 {
8289 next_selected_range = Some(offset_range);
8290 break;
8291 }
8292 }
8293
8294 if let Some(next_selected_range) = next_selected_range {
8295 self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
8296 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8297 if action.replace_newest {
8298 s.delete(s.newest_anchor().id);
8299 }
8300 s.insert_range(next_selected_range);
8301 });
8302 } else {
8303 select_prev_state.done = true;
8304 }
8305 }
8306
8307 self.select_prev_state = Some(select_prev_state);
8308 } else {
8309 let mut only_carets = true;
8310 let mut same_text_selected = true;
8311 let mut selected_text = None;
8312
8313 let mut selections_iter = selections.iter().peekable();
8314 while let Some(selection) = selections_iter.next() {
8315 if selection.start != selection.end {
8316 only_carets = false;
8317 }
8318
8319 if same_text_selected {
8320 if selected_text.is_none() {
8321 selected_text =
8322 Some(buffer.text_for_range(selection.range()).collect::<String>());
8323 }
8324
8325 if let Some(next_selection) = selections_iter.peek() {
8326 if next_selection.range().len() == selection.range().len() {
8327 let next_selected_text = buffer
8328 .text_for_range(next_selection.range())
8329 .collect::<String>();
8330 if Some(next_selected_text) != selected_text {
8331 same_text_selected = false;
8332 selected_text = None;
8333 }
8334 } else {
8335 same_text_selected = false;
8336 selected_text = None;
8337 }
8338 }
8339 }
8340 }
8341
8342 if only_carets {
8343 for selection in &mut selections {
8344 let word_range = movement::surrounding_word(
8345 &display_map,
8346 selection.start.to_display_point(&display_map),
8347 );
8348 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8349 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8350 selection.goal = SelectionGoal::None;
8351 selection.reversed = false;
8352 }
8353 if selections.len() == 1 {
8354 let selection = selections
8355 .last()
8356 .expect("ensured that there's only one selection");
8357 let query = buffer
8358 .text_for_range(selection.start..selection.end)
8359 .collect::<String>();
8360 let is_empty = query.is_empty();
8361 let select_state = SelectNextState {
8362 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8363 wordwise: true,
8364 done: is_empty,
8365 };
8366 self.select_prev_state = Some(select_state);
8367 } else {
8368 self.select_prev_state = None;
8369 }
8370
8371 self.unfold_ranges(
8372 &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8373 false,
8374 true,
8375 cx,
8376 );
8377 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8378 s.select(selections);
8379 });
8380 } else if let Some(selected_text) = selected_text {
8381 self.select_prev_state = Some(SelectNextState {
8382 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8383 wordwise: false,
8384 done: false,
8385 });
8386 self.select_previous(action, cx)?;
8387 }
8388 }
8389 Ok(())
8390 }
8391
8392 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8393 if self.read_only(cx) {
8394 return;
8395 }
8396 let text_layout_details = &self.text_layout_details(cx);
8397 self.transact(cx, |this, cx| {
8398 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8399 let mut edits = Vec::new();
8400 let mut selection_edit_ranges = Vec::new();
8401 let mut last_toggled_row = None;
8402 let snapshot = this.buffer.read(cx).read(cx);
8403 let empty_str: Arc<str> = Arc::default();
8404 let mut suffixes_inserted = Vec::new();
8405 let ignore_indent = action.ignore_indent;
8406
8407 fn comment_prefix_range(
8408 snapshot: &MultiBufferSnapshot,
8409 row: MultiBufferRow,
8410 comment_prefix: &str,
8411 comment_prefix_whitespace: &str,
8412 ignore_indent: bool,
8413 ) -> Range<Point> {
8414 let indent_size = if ignore_indent {
8415 0
8416 } else {
8417 snapshot.indent_size_for_line(row).len
8418 };
8419
8420 let start = Point::new(row.0, indent_size);
8421
8422 let mut line_bytes = snapshot
8423 .bytes_in_range(start..snapshot.max_point())
8424 .flatten()
8425 .copied();
8426
8427 // If this line currently begins with the line comment prefix, then record
8428 // the range containing the prefix.
8429 if line_bytes
8430 .by_ref()
8431 .take(comment_prefix.len())
8432 .eq(comment_prefix.bytes())
8433 {
8434 // Include any whitespace that matches the comment prefix.
8435 let matching_whitespace_len = line_bytes
8436 .zip(comment_prefix_whitespace.bytes())
8437 .take_while(|(a, b)| a == b)
8438 .count() as u32;
8439 let end = Point::new(
8440 start.row,
8441 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8442 );
8443 start..end
8444 } else {
8445 start..start
8446 }
8447 }
8448
8449 fn comment_suffix_range(
8450 snapshot: &MultiBufferSnapshot,
8451 row: MultiBufferRow,
8452 comment_suffix: &str,
8453 comment_suffix_has_leading_space: bool,
8454 ) -> Range<Point> {
8455 let end = Point::new(row.0, snapshot.line_len(row));
8456 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8457
8458 let mut line_end_bytes = snapshot
8459 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8460 .flatten()
8461 .copied();
8462
8463 let leading_space_len = if suffix_start_column > 0
8464 && line_end_bytes.next() == Some(b' ')
8465 && comment_suffix_has_leading_space
8466 {
8467 1
8468 } else {
8469 0
8470 };
8471
8472 // If this line currently begins with the line comment prefix, then record
8473 // the range containing the prefix.
8474 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8475 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8476 start..end
8477 } else {
8478 end..end
8479 }
8480 }
8481
8482 // TODO: Handle selections that cross excerpts
8483 for selection in &mut selections {
8484 let start_column = snapshot
8485 .indent_size_for_line(MultiBufferRow(selection.start.row))
8486 .len;
8487 let language = if let Some(language) =
8488 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8489 {
8490 language
8491 } else {
8492 continue;
8493 };
8494
8495 selection_edit_ranges.clear();
8496
8497 // If multiple selections contain a given row, avoid processing that
8498 // row more than once.
8499 let mut start_row = MultiBufferRow(selection.start.row);
8500 if last_toggled_row == Some(start_row) {
8501 start_row = start_row.next_row();
8502 }
8503 let end_row =
8504 if selection.end.row > selection.start.row && selection.end.column == 0 {
8505 MultiBufferRow(selection.end.row - 1)
8506 } else {
8507 MultiBufferRow(selection.end.row)
8508 };
8509 last_toggled_row = Some(end_row);
8510
8511 if start_row > end_row {
8512 continue;
8513 }
8514
8515 // If the language has line comments, toggle those.
8516 let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
8517
8518 // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
8519 if ignore_indent {
8520 full_comment_prefixes = full_comment_prefixes
8521 .into_iter()
8522 .map(|s| Arc::from(s.trim_end()))
8523 .collect();
8524 }
8525
8526 if !full_comment_prefixes.is_empty() {
8527 let first_prefix = full_comment_prefixes
8528 .first()
8529 .expect("prefixes is non-empty");
8530 let prefix_trimmed_lengths = full_comment_prefixes
8531 .iter()
8532 .map(|p| p.trim_end_matches(' ').len())
8533 .collect::<SmallVec<[usize; 4]>>();
8534
8535 let mut all_selection_lines_are_comments = true;
8536
8537 for row in start_row.0..=end_row.0 {
8538 let row = MultiBufferRow(row);
8539 if start_row < end_row && snapshot.is_line_blank(row) {
8540 continue;
8541 }
8542
8543 let prefix_range = full_comment_prefixes
8544 .iter()
8545 .zip(prefix_trimmed_lengths.iter().copied())
8546 .map(|(prefix, trimmed_prefix_len)| {
8547 comment_prefix_range(
8548 snapshot.deref(),
8549 row,
8550 &prefix[..trimmed_prefix_len],
8551 &prefix[trimmed_prefix_len..],
8552 ignore_indent,
8553 )
8554 })
8555 .max_by_key(|range| range.end.column - range.start.column)
8556 .expect("prefixes is non-empty");
8557
8558 if prefix_range.is_empty() {
8559 all_selection_lines_are_comments = false;
8560 }
8561
8562 selection_edit_ranges.push(prefix_range);
8563 }
8564
8565 if all_selection_lines_are_comments {
8566 edits.extend(
8567 selection_edit_ranges
8568 .iter()
8569 .cloned()
8570 .map(|range| (range, empty_str.clone())),
8571 );
8572 } else {
8573 let min_column = selection_edit_ranges
8574 .iter()
8575 .map(|range| range.start.column)
8576 .min()
8577 .unwrap_or(0);
8578 edits.extend(selection_edit_ranges.iter().map(|range| {
8579 let position = Point::new(range.start.row, min_column);
8580 (position..position, first_prefix.clone())
8581 }));
8582 }
8583 } else if let Some((full_comment_prefix, comment_suffix)) =
8584 language.block_comment_delimiters()
8585 {
8586 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8587 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8588 let prefix_range = comment_prefix_range(
8589 snapshot.deref(),
8590 start_row,
8591 comment_prefix,
8592 comment_prefix_whitespace,
8593 ignore_indent,
8594 );
8595 let suffix_range = comment_suffix_range(
8596 snapshot.deref(),
8597 end_row,
8598 comment_suffix.trim_start_matches(' '),
8599 comment_suffix.starts_with(' '),
8600 );
8601
8602 if prefix_range.is_empty() || suffix_range.is_empty() {
8603 edits.push((
8604 prefix_range.start..prefix_range.start,
8605 full_comment_prefix.clone(),
8606 ));
8607 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8608 suffixes_inserted.push((end_row, comment_suffix.len()));
8609 } else {
8610 edits.push((prefix_range, empty_str.clone()));
8611 edits.push((suffix_range, empty_str.clone()));
8612 }
8613 } else {
8614 continue;
8615 }
8616 }
8617
8618 drop(snapshot);
8619 this.buffer.update(cx, |buffer, cx| {
8620 buffer.edit(edits, None, cx);
8621 });
8622
8623 // Adjust selections so that they end before any comment suffixes that
8624 // were inserted.
8625 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8626 let mut selections = this.selections.all::<Point>(cx);
8627 let snapshot = this.buffer.read(cx).read(cx);
8628 for selection in &mut selections {
8629 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8630 match row.cmp(&MultiBufferRow(selection.end.row)) {
8631 Ordering::Less => {
8632 suffixes_inserted.next();
8633 continue;
8634 }
8635 Ordering::Greater => break,
8636 Ordering::Equal => {
8637 if selection.end.column == snapshot.line_len(row) {
8638 if selection.is_empty() {
8639 selection.start.column -= suffix_len as u32;
8640 }
8641 selection.end.column -= suffix_len as u32;
8642 }
8643 break;
8644 }
8645 }
8646 }
8647 }
8648
8649 drop(snapshot);
8650 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8651
8652 let selections = this.selections.all::<Point>(cx);
8653 let selections_on_single_row = selections.windows(2).all(|selections| {
8654 selections[0].start.row == selections[1].start.row
8655 && selections[0].end.row == selections[1].end.row
8656 && selections[0].start.row == selections[0].end.row
8657 });
8658 let selections_selecting = selections
8659 .iter()
8660 .any(|selection| selection.start != selection.end);
8661 let advance_downwards = action.advance_downwards
8662 && selections_on_single_row
8663 && !selections_selecting
8664 && !matches!(this.mode, EditorMode::SingleLine { .. });
8665
8666 if advance_downwards {
8667 let snapshot = this.buffer.read(cx).snapshot(cx);
8668
8669 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8670 s.move_cursors_with(|display_snapshot, display_point, _| {
8671 let mut point = display_point.to_point(display_snapshot);
8672 point.row += 1;
8673 point = snapshot.clip_point(point, Bias::Left);
8674 let display_point = point.to_display_point(display_snapshot);
8675 let goal = SelectionGoal::HorizontalPosition(
8676 display_snapshot
8677 .x_for_display_point(display_point, text_layout_details)
8678 .into(),
8679 );
8680 (display_point, goal)
8681 })
8682 });
8683 }
8684 });
8685 }
8686
8687 pub fn select_enclosing_symbol(
8688 &mut self,
8689 _: &SelectEnclosingSymbol,
8690 cx: &mut ViewContext<Self>,
8691 ) {
8692 let buffer = self.buffer.read(cx).snapshot(cx);
8693 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8694
8695 fn update_selection(
8696 selection: &Selection<usize>,
8697 buffer_snap: &MultiBufferSnapshot,
8698 ) -> Option<Selection<usize>> {
8699 let cursor = selection.head();
8700 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8701 for symbol in symbols.iter().rev() {
8702 let start = symbol.range.start.to_offset(buffer_snap);
8703 let end = symbol.range.end.to_offset(buffer_snap);
8704 let new_range = start..end;
8705 if start < selection.start || end > selection.end {
8706 return Some(Selection {
8707 id: selection.id,
8708 start: new_range.start,
8709 end: new_range.end,
8710 goal: SelectionGoal::None,
8711 reversed: selection.reversed,
8712 });
8713 }
8714 }
8715 None
8716 }
8717
8718 let mut selected_larger_symbol = false;
8719 let new_selections = old_selections
8720 .iter()
8721 .map(|selection| match update_selection(selection, &buffer) {
8722 Some(new_selection) => {
8723 if new_selection.range() != selection.range() {
8724 selected_larger_symbol = true;
8725 }
8726 new_selection
8727 }
8728 None => selection.clone(),
8729 })
8730 .collect::<Vec<_>>();
8731
8732 if selected_larger_symbol {
8733 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8734 s.select(new_selections);
8735 });
8736 }
8737 }
8738
8739 pub fn select_larger_syntax_node(
8740 &mut self,
8741 _: &SelectLargerSyntaxNode,
8742 cx: &mut ViewContext<Self>,
8743 ) {
8744 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8745 let buffer = self.buffer.read(cx).snapshot(cx);
8746 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8747
8748 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8749 let mut selected_larger_node = false;
8750 let new_selections = old_selections
8751 .iter()
8752 .map(|selection| {
8753 let old_range = selection.start..selection.end;
8754 let mut new_range = old_range.clone();
8755 while let Some(containing_range) =
8756 buffer.range_for_syntax_ancestor(new_range.clone())
8757 {
8758 new_range = containing_range;
8759 if !display_map.intersects_fold(new_range.start)
8760 && !display_map.intersects_fold(new_range.end)
8761 {
8762 break;
8763 }
8764 }
8765
8766 selected_larger_node |= new_range != old_range;
8767 Selection {
8768 id: selection.id,
8769 start: new_range.start,
8770 end: new_range.end,
8771 goal: SelectionGoal::None,
8772 reversed: selection.reversed,
8773 }
8774 })
8775 .collect::<Vec<_>>();
8776
8777 if selected_larger_node {
8778 stack.push(old_selections);
8779 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8780 s.select(new_selections);
8781 });
8782 }
8783 self.select_larger_syntax_node_stack = stack;
8784 }
8785
8786 pub fn select_smaller_syntax_node(
8787 &mut self,
8788 _: &SelectSmallerSyntaxNode,
8789 cx: &mut ViewContext<Self>,
8790 ) {
8791 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8792 if let Some(selections) = stack.pop() {
8793 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8794 s.select(selections.to_vec());
8795 });
8796 }
8797 self.select_larger_syntax_node_stack = stack;
8798 }
8799
8800 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8801 if !EditorSettings::get_global(cx).gutter.runnables {
8802 self.clear_tasks();
8803 return Task::ready(());
8804 }
8805 let project = self.project.as_ref().map(Model::downgrade);
8806 cx.spawn(|this, mut cx| async move {
8807 cx.background_executor().timer(UPDATE_DEBOUNCE).await;
8808 let Some(project) = project.and_then(|p| p.upgrade()) else {
8809 return;
8810 };
8811 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8812 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8813 }) else {
8814 return;
8815 };
8816
8817 let hide_runnables = project
8818 .update(&mut cx, |project, cx| {
8819 // Do not display any test indicators in non-dev server remote projects.
8820 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8821 })
8822 .unwrap_or(true);
8823 if hide_runnables {
8824 return;
8825 }
8826 let new_rows =
8827 cx.background_executor()
8828 .spawn({
8829 let snapshot = display_snapshot.clone();
8830 async move {
8831 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8832 }
8833 })
8834 .await;
8835 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8836
8837 this.update(&mut cx, |this, _| {
8838 this.clear_tasks();
8839 for (key, value) in rows {
8840 this.insert_tasks(key, value);
8841 }
8842 })
8843 .ok();
8844 })
8845 }
8846 fn fetch_runnable_ranges(
8847 snapshot: &DisplaySnapshot,
8848 range: Range<Anchor>,
8849 ) -> Vec<language::RunnableRange> {
8850 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8851 }
8852
8853 fn runnable_rows(
8854 project: Model<Project>,
8855 snapshot: DisplaySnapshot,
8856 runnable_ranges: Vec<RunnableRange>,
8857 mut cx: AsyncWindowContext,
8858 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8859 runnable_ranges
8860 .into_iter()
8861 .filter_map(|mut runnable| {
8862 let tasks = cx
8863 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8864 .ok()?;
8865 if tasks.is_empty() {
8866 return None;
8867 }
8868
8869 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8870
8871 let row = snapshot
8872 .buffer_snapshot
8873 .buffer_line_for_row(MultiBufferRow(point.row))?
8874 .1
8875 .start
8876 .row;
8877
8878 let context_range =
8879 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8880 Some((
8881 (runnable.buffer_id, row),
8882 RunnableTasks {
8883 templates: tasks,
8884 offset: MultiBufferOffset(runnable.run_range.start),
8885 context_range,
8886 column: point.column,
8887 extra_variables: runnable.extra_captures,
8888 },
8889 ))
8890 })
8891 .collect()
8892 }
8893
8894 fn templates_with_tags(
8895 project: &Model<Project>,
8896 runnable: &mut Runnable,
8897 cx: &WindowContext<'_>,
8898 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8899 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8900 let (worktree_id, file) = project
8901 .buffer_for_id(runnable.buffer, cx)
8902 .and_then(|buffer| buffer.read(cx).file())
8903 .map(|file| (file.worktree_id(cx), file.clone()))
8904 .unzip();
8905
8906 (
8907 project.task_store().read(cx).task_inventory().cloned(),
8908 worktree_id,
8909 file,
8910 )
8911 });
8912
8913 let tags = mem::take(&mut runnable.tags);
8914 let mut tags: Vec<_> = tags
8915 .into_iter()
8916 .flat_map(|tag| {
8917 let tag = tag.0.clone();
8918 inventory
8919 .as_ref()
8920 .into_iter()
8921 .flat_map(|inventory| {
8922 inventory.read(cx).list_tasks(
8923 file.clone(),
8924 Some(runnable.language.clone()),
8925 worktree_id,
8926 cx,
8927 )
8928 })
8929 .filter(move |(_, template)| {
8930 template.tags.iter().any(|source_tag| source_tag == &tag)
8931 })
8932 })
8933 .sorted_by_key(|(kind, _)| kind.to_owned())
8934 .collect();
8935 if let Some((leading_tag_source, _)) = tags.first() {
8936 // Strongest source wins; if we have worktree tag binding, prefer that to
8937 // global and language bindings;
8938 // if we have a global binding, prefer that to language binding.
8939 let first_mismatch = tags
8940 .iter()
8941 .position(|(tag_source, _)| tag_source != leading_tag_source);
8942 if let Some(index) = first_mismatch {
8943 tags.truncate(index);
8944 }
8945 }
8946
8947 tags
8948 }
8949
8950 pub fn move_to_enclosing_bracket(
8951 &mut self,
8952 _: &MoveToEnclosingBracket,
8953 cx: &mut ViewContext<Self>,
8954 ) {
8955 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8956 s.move_offsets_with(|snapshot, selection| {
8957 let Some(enclosing_bracket_ranges) =
8958 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
8959 else {
8960 return;
8961 };
8962
8963 let mut best_length = usize::MAX;
8964 let mut best_inside = false;
8965 let mut best_in_bracket_range = false;
8966 let mut best_destination = None;
8967 for (open, close) in enclosing_bracket_ranges {
8968 let close = close.to_inclusive();
8969 let length = close.end() - open.start;
8970 let inside = selection.start >= open.end && selection.end <= *close.start();
8971 let in_bracket_range = open.to_inclusive().contains(&selection.head())
8972 || close.contains(&selection.head());
8973
8974 // If best is next to a bracket and current isn't, skip
8975 if !in_bracket_range && best_in_bracket_range {
8976 continue;
8977 }
8978
8979 // Prefer smaller lengths unless best is inside and current isn't
8980 if length > best_length && (best_inside || !inside) {
8981 continue;
8982 }
8983
8984 best_length = length;
8985 best_inside = inside;
8986 best_in_bracket_range = in_bracket_range;
8987 best_destination = Some(
8988 if close.contains(&selection.start) && close.contains(&selection.end) {
8989 if inside {
8990 open.end
8991 } else {
8992 open.start
8993 }
8994 } else if inside {
8995 *close.start()
8996 } else {
8997 *close.end()
8998 },
8999 );
9000 }
9001
9002 if let Some(destination) = best_destination {
9003 selection.collapse_to(destination, SelectionGoal::None);
9004 }
9005 })
9006 });
9007 }
9008
9009 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9010 self.end_selection(cx);
9011 self.selection_history.mode = SelectionHistoryMode::Undoing;
9012 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9013 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9014 self.select_next_state = entry.select_next_state;
9015 self.select_prev_state = entry.select_prev_state;
9016 self.add_selections_state = entry.add_selections_state;
9017 self.request_autoscroll(Autoscroll::newest(), cx);
9018 }
9019 self.selection_history.mode = SelectionHistoryMode::Normal;
9020 }
9021
9022 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9023 self.end_selection(cx);
9024 self.selection_history.mode = SelectionHistoryMode::Redoing;
9025 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9026 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9027 self.select_next_state = entry.select_next_state;
9028 self.select_prev_state = entry.select_prev_state;
9029 self.add_selections_state = entry.add_selections_state;
9030 self.request_autoscroll(Autoscroll::newest(), cx);
9031 }
9032 self.selection_history.mode = SelectionHistoryMode::Normal;
9033 }
9034
9035 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9036 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9037 }
9038
9039 pub fn expand_excerpts_down(
9040 &mut self,
9041 action: &ExpandExcerptsDown,
9042 cx: &mut ViewContext<Self>,
9043 ) {
9044 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9045 }
9046
9047 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9048 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9049 }
9050
9051 pub fn expand_excerpts_for_direction(
9052 &mut self,
9053 lines: u32,
9054 direction: ExpandExcerptDirection,
9055 cx: &mut ViewContext<Self>,
9056 ) {
9057 let selections = self.selections.disjoint_anchors();
9058
9059 let lines = if lines == 0 {
9060 EditorSettings::get_global(cx).expand_excerpt_lines
9061 } else {
9062 lines
9063 };
9064
9065 self.buffer.update(cx, |buffer, cx| {
9066 buffer.expand_excerpts(
9067 selections
9068 .iter()
9069 .map(|selection| selection.head().excerpt_id)
9070 .dedup(),
9071 lines,
9072 direction,
9073 cx,
9074 )
9075 })
9076 }
9077
9078 pub fn expand_excerpt(
9079 &mut self,
9080 excerpt: ExcerptId,
9081 direction: ExpandExcerptDirection,
9082 cx: &mut ViewContext<Self>,
9083 ) {
9084 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9085 self.buffer.update(cx, |buffer, cx| {
9086 buffer.expand_excerpts([excerpt], lines, direction, cx)
9087 })
9088 }
9089
9090 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9091 self.go_to_diagnostic_impl(Direction::Next, cx)
9092 }
9093
9094 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9095 self.go_to_diagnostic_impl(Direction::Prev, cx)
9096 }
9097
9098 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9099 let buffer = self.buffer.read(cx).snapshot(cx);
9100 let selection = self.selections.newest::<usize>(cx);
9101
9102 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9103 if direction == Direction::Next {
9104 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9105 let (group_id, jump_to) = popover.activation_info();
9106 if self.activate_diagnostics(group_id, cx) {
9107 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9108 let mut new_selection = s.newest_anchor().clone();
9109 new_selection.collapse_to(jump_to, SelectionGoal::None);
9110 s.select_anchors(vec![new_selection.clone()]);
9111 });
9112 }
9113 return;
9114 }
9115 }
9116
9117 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9118 active_diagnostics
9119 .primary_range
9120 .to_offset(&buffer)
9121 .to_inclusive()
9122 });
9123 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9124 if active_primary_range.contains(&selection.head()) {
9125 *active_primary_range.start()
9126 } else {
9127 selection.head()
9128 }
9129 } else {
9130 selection.head()
9131 };
9132 let snapshot = self.snapshot(cx);
9133 loop {
9134 let diagnostics = if direction == Direction::Prev {
9135 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9136 } else {
9137 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9138 }
9139 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9140 let group = diagnostics
9141 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9142 // be sorted in a stable way
9143 // skip until we are at current active diagnostic, if it exists
9144 .skip_while(|entry| {
9145 (match direction {
9146 Direction::Prev => entry.range.start >= search_start,
9147 Direction::Next => entry.range.start <= search_start,
9148 }) && self
9149 .active_diagnostics
9150 .as_ref()
9151 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9152 })
9153 .find_map(|entry| {
9154 if entry.diagnostic.is_primary
9155 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9156 && !entry.range.is_empty()
9157 // if we match with the active diagnostic, skip it
9158 && Some(entry.diagnostic.group_id)
9159 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9160 {
9161 Some((entry.range, entry.diagnostic.group_id))
9162 } else {
9163 None
9164 }
9165 });
9166
9167 if let Some((primary_range, group_id)) = group {
9168 if self.activate_diagnostics(group_id, cx) {
9169 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9170 s.select(vec![Selection {
9171 id: selection.id,
9172 start: primary_range.start,
9173 end: primary_range.start,
9174 reversed: false,
9175 goal: SelectionGoal::None,
9176 }]);
9177 });
9178 }
9179 break;
9180 } else {
9181 // Cycle around to the start of the buffer, potentially moving back to the start of
9182 // the currently active diagnostic.
9183 active_primary_range.take();
9184 if direction == Direction::Prev {
9185 if search_start == buffer.len() {
9186 break;
9187 } else {
9188 search_start = buffer.len();
9189 }
9190 } else if search_start == 0 {
9191 break;
9192 } else {
9193 search_start = 0;
9194 }
9195 }
9196 }
9197 }
9198
9199 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9200 let snapshot = self.snapshot(cx);
9201 let selection = self.selections.newest::<Point>(cx);
9202 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9203 }
9204
9205 fn go_to_hunk_after_position(
9206 &mut self,
9207 snapshot: &EditorSnapshot,
9208 position: Point,
9209 cx: &mut ViewContext<'_, Editor>,
9210 ) -> Option<MultiBufferDiffHunk> {
9211 for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
9212 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9213 snapshot,
9214 position,
9215 ix > 0,
9216 snapshot.diff_map.diff_hunks_in_range(
9217 position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
9218 &snapshot.buffer_snapshot,
9219 ),
9220 cx,
9221 ) {
9222 return Some(hunk);
9223 }
9224 }
9225 None
9226 }
9227
9228 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9229 let snapshot = self.snapshot(cx);
9230 let selection = self.selections.newest::<Point>(cx);
9231 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9232 }
9233
9234 fn go_to_hunk_before_position(
9235 &mut self,
9236 snapshot: &EditorSnapshot,
9237 position: Point,
9238 cx: &mut ViewContext<'_, Editor>,
9239 ) -> Option<MultiBufferDiffHunk> {
9240 for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
9241 .into_iter()
9242 .enumerate()
9243 {
9244 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9245 snapshot,
9246 position,
9247 ix > 0,
9248 snapshot
9249 .diff_map
9250 .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
9251 cx,
9252 ) {
9253 return Some(hunk);
9254 }
9255 }
9256 None
9257 }
9258
9259 fn go_to_next_hunk_in_direction(
9260 &mut self,
9261 snapshot: &DisplaySnapshot,
9262 initial_point: Point,
9263 is_wrapped: bool,
9264 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9265 cx: &mut ViewContext<Editor>,
9266 ) -> Option<MultiBufferDiffHunk> {
9267 let display_point = initial_point.to_display_point(snapshot);
9268 let mut hunks = hunks
9269 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9270 .filter(|(display_hunk, _)| {
9271 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9272 })
9273 .dedup();
9274
9275 if let Some((display_hunk, hunk)) = hunks.next() {
9276 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9277 let row = display_hunk.start_display_row();
9278 let point = DisplayPoint::new(row, 0);
9279 s.select_display_ranges([point..point]);
9280 });
9281
9282 Some(hunk)
9283 } else {
9284 None
9285 }
9286 }
9287
9288 pub fn go_to_definition(
9289 &mut self,
9290 _: &GoToDefinition,
9291 cx: &mut ViewContext<Self>,
9292 ) -> Task<Result<Navigated>> {
9293 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9294 cx.spawn(|editor, mut cx| async move {
9295 if definition.await? == Navigated::Yes {
9296 return Ok(Navigated::Yes);
9297 }
9298 match editor.update(&mut cx, |editor, cx| {
9299 editor.find_all_references(&FindAllReferences, cx)
9300 })? {
9301 Some(references) => references.await,
9302 None => Ok(Navigated::No),
9303 }
9304 })
9305 }
9306
9307 pub fn go_to_declaration(
9308 &mut self,
9309 _: &GoToDeclaration,
9310 cx: &mut ViewContext<Self>,
9311 ) -> Task<Result<Navigated>> {
9312 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9313 }
9314
9315 pub fn go_to_declaration_split(
9316 &mut self,
9317 _: &GoToDeclaration,
9318 cx: &mut ViewContext<Self>,
9319 ) -> Task<Result<Navigated>> {
9320 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9321 }
9322
9323 pub fn go_to_implementation(
9324 &mut self,
9325 _: &GoToImplementation,
9326 cx: &mut ViewContext<Self>,
9327 ) -> Task<Result<Navigated>> {
9328 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9329 }
9330
9331 pub fn go_to_implementation_split(
9332 &mut self,
9333 _: &GoToImplementationSplit,
9334 cx: &mut ViewContext<Self>,
9335 ) -> Task<Result<Navigated>> {
9336 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9337 }
9338
9339 pub fn go_to_type_definition(
9340 &mut self,
9341 _: &GoToTypeDefinition,
9342 cx: &mut ViewContext<Self>,
9343 ) -> Task<Result<Navigated>> {
9344 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9345 }
9346
9347 pub fn go_to_definition_split(
9348 &mut self,
9349 _: &GoToDefinitionSplit,
9350 cx: &mut ViewContext<Self>,
9351 ) -> Task<Result<Navigated>> {
9352 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9353 }
9354
9355 pub fn go_to_type_definition_split(
9356 &mut self,
9357 _: &GoToTypeDefinitionSplit,
9358 cx: &mut ViewContext<Self>,
9359 ) -> Task<Result<Navigated>> {
9360 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9361 }
9362
9363 fn go_to_definition_of_kind(
9364 &mut self,
9365 kind: GotoDefinitionKind,
9366 split: bool,
9367 cx: &mut ViewContext<Self>,
9368 ) -> Task<Result<Navigated>> {
9369 let Some(provider) = self.semantics_provider.clone() else {
9370 return Task::ready(Ok(Navigated::No));
9371 };
9372 let head = self.selections.newest::<usize>(cx).head();
9373 let buffer = self.buffer.read(cx);
9374 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9375 text_anchor
9376 } else {
9377 return Task::ready(Ok(Navigated::No));
9378 };
9379
9380 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9381 return Task::ready(Ok(Navigated::No));
9382 };
9383
9384 cx.spawn(|editor, mut cx| async move {
9385 let definitions = definitions.await?;
9386 let navigated = editor
9387 .update(&mut cx, |editor, cx| {
9388 editor.navigate_to_hover_links(
9389 Some(kind),
9390 definitions
9391 .into_iter()
9392 .filter(|location| {
9393 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9394 })
9395 .map(HoverLink::Text)
9396 .collect::<Vec<_>>(),
9397 split,
9398 cx,
9399 )
9400 })?
9401 .await?;
9402 anyhow::Ok(navigated)
9403 })
9404 }
9405
9406 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9407 let selection = self.selections.newest_anchor();
9408 let head = selection.head();
9409 let tail = selection.tail();
9410
9411 let Some((buffer, start_position)) =
9412 self.buffer.read(cx).text_anchor_for_position(head, cx)
9413 else {
9414 return;
9415 };
9416
9417 let end_position = if head != tail {
9418 let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
9419 return;
9420 };
9421 Some(pos)
9422 } else {
9423 None
9424 };
9425
9426 let url_finder = cx.spawn(|editor, mut cx| async move {
9427 let url = if let Some(end_pos) = end_position {
9428 find_url_from_range(&buffer, start_position..end_pos, cx.clone())
9429 } else {
9430 find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
9431 };
9432
9433 if let Some(url) = url {
9434 editor.update(&mut cx, |_, cx| {
9435 cx.open_url(&url);
9436 })
9437 } else {
9438 Ok(())
9439 }
9440 });
9441
9442 url_finder.detach();
9443 }
9444
9445 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9446 let Some(workspace) = self.workspace() else {
9447 return;
9448 };
9449
9450 let position = self.selections.newest_anchor().head();
9451
9452 let Some((buffer, buffer_position)) =
9453 self.buffer.read(cx).text_anchor_for_position(position, cx)
9454 else {
9455 return;
9456 };
9457
9458 let project = self.project.clone();
9459
9460 cx.spawn(|_, mut cx| async move {
9461 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9462
9463 if let Some((_, path)) = result {
9464 workspace
9465 .update(&mut cx, |workspace, cx| {
9466 workspace.open_resolved_path(path, cx)
9467 })?
9468 .await?;
9469 }
9470 anyhow::Ok(())
9471 })
9472 .detach();
9473 }
9474
9475 pub(crate) fn navigate_to_hover_links(
9476 &mut self,
9477 kind: Option<GotoDefinitionKind>,
9478 mut definitions: Vec<HoverLink>,
9479 split: bool,
9480 cx: &mut ViewContext<Editor>,
9481 ) -> Task<Result<Navigated>> {
9482 // If there is one definition, just open it directly
9483 if definitions.len() == 1 {
9484 let definition = definitions.pop().unwrap();
9485
9486 enum TargetTaskResult {
9487 Location(Option<Location>),
9488 AlreadyNavigated,
9489 }
9490
9491 let target_task = match definition {
9492 HoverLink::Text(link) => {
9493 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9494 }
9495 HoverLink::InlayHint(lsp_location, server_id) => {
9496 let computation = self.compute_target_location(lsp_location, server_id, cx);
9497 cx.background_executor().spawn(async move {
9498 let location = computation.await?;
9499 Ok(TargetTaskResult::Location(location))
9500 })
9501 }
9502 HoverLink::Url(url) => {
9503 cx.open_url(&url);
9504 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9505 }
9506 HoverLink::File(path) => {
9507 if let Some(workspace) = self.workspace() {
9508 cx.spawn(|_, mut cx| async move {
9509 workspace
9510 .update(&mut cx, |workspace, cx| {
9511 workspace.open_resolved_path(path, cx)
9512 })?
9513 .await
9514 .map(|_| TargetTaskResult::AlreadyNavigated)
9515 })
9516 } else {
9517 Task::ready(Ok(TargetTaskResult::Location(None)))
9518 }
9519 }
9520 };
9521 cx.spawn(|editor, mut cx| async move {
9522 let target = match target_task.await.context("target resolution task")? {
9523 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9524 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9525 TargetTaskResult::Location(Some(target)) => target,
9526 };
9527
9528 editor.update(&mut cx, |editor, cx| {
9529 let Some(workspace) = editor.workspace() else {
9530 return Navigated::No;
9531 };
9532 let pane = workspace.read(cx).active_pane().clone();
9533
9534 let range = target.range.to_offset(target.buffer.read(cx));
9535 let range = editor.range_for_match(&range);
9536
9537 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9538 let buffer = target.buffer.read(cx);
9539 let range = check_multiline_range(buffer, range);
9540 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9541 s.select_ranges([range]);
9542 });
9543 } else {
9544 cx.window_context().defer(move |cx| {
9545 let target_editor: View<Self> =
9546 workspace.update(cx, |workspace, cx| {
9547 let pane = if split {
9548 workspace.adjacent_pane(cx)
9549 } else {
9550 workspace.active_pane().clone()
9551 };
9552
9553 workspace.open_project_item(
9554 pane,
9555 target.buffer.clone(),
9556 true,
9557 true,
9558 cx,
9559 )
9560 });
9561 target_editor.update(cx, |target_editor, cx| {
9562 // When selecting a definition in a different buffer, disable the nav history
9563 // to avoid creating a history entry at the previous cursor location.
9564 pane.update(cx, |pane, _| pane.disable_history());
9565 let buffer = target.buffer.read(cx);
9566 let range = check_multiline_range(buffer, range);
9567 target_editor.change_selections(
9568 Some(Autoscroll::focused()),
9569 cx,
9570 |s| {
9571 s.select_ranges([range]);
9572 },
9573 );
9574 pane.update(cx, |pane, _| pane.enable_history());
9575 });
9576 });
9577 }
9578 Navigated::Yes
9579 })
9580 })
9581 } else if !definitions.is_empty() {
9582 cx.spawn(|editor, mut cx| async move {
9583 let (title, location_tasks, workspace) = editor
9584 .update(&mut cx, |editor, cx| {
9585 let tab_kind = match kind {
9586 Some(GotoDefinitionKind::Implementation) => "Implementations",
9587 _ => "Definitions",
9588 };
9589 let title = definitions
9590 .iter()
9591 .find_map(|definition| match definition {
9592 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9593 let buffer = origin.buffer.read(cx);
9594 format!(
9595 "{} for {}",
9596 tab_kind,
9597 buffer
9598 .text_for_range(origin.range.clone())
9599 .collect::<String>()
9600 )
9601 }),
9602 HoverLink::InlayHint(_, _) => None,
9603 HoverLink::Url(_) => None,
9604 HoverLink::File(_) => None,
9605 })
9606 .unwrap_or(tab_kind.to_string());
9607 let location_tasks = definitions
9608 .into_iter()
9609 .map(|definition| match definition {
9610 HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
9611 HoverLink::InlayHint(lsp_location, server_id) => {
9612 editor.compute_target_location(lsp_location, server_id, cx)
9613 }
9614 HoverLink::Url(_) => Task::ready(Ok(None)),
9615 HoverLink::File(_) => Task::ready(Ok(None)),
9616 })
9617 .collect::<Vec<_>>();
9618 (title, location_tasks, editor.workspace().clone())
9619 })
9620 .context("location tasks preparation")?;
9621
9622 let locations = future::join_all(location_tasks)
9623 .await
9624 .into_iter()
9625 .filter_map(|location| location.transpose())
9626 .collect::<Result<_>>()
9627 .context("location tasks")?;
9628
9629 let Some(workspace) = workspace else {
9630 return Ok(Navigated::No);
9631 };
9632 let opened = workspace
9633 .update(&mut cx, |workspace, cx| {
9634 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9635 })
9636 .ok();
9637
9638 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9639 })
9640 } else {
9641 Task::ready(Ok(Navigated::No))
9642 }
9643 }
9644
9645 fn compute_target_location(
9646 &self,
9647 lsp_location: lsp::Location,
9648 server_id: LanguageServerId,
9649 cx: &mut ViewContext<Self>,
9650 ) -> Task<anyhow::Result<Option<Location>>> {
9651 let Some(project) = self.project.clone() else {
9652 return Task::ready(Ok(None));
9653 };
9654
9655 cx.spawn(move |editor, mut cx| async move {
9656 let location_task = editor.update(&mut cx, |_, cx| {
9657 project.update(cx, |project, cx| {
9658 let language_server_name = project
9659 .language_server_statuses(cx)
9660 .find(|(id, _)| server_id == *id)
9661 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
9662 language_server_name.map(|language_server_name| {
9663 project.open_local_buffer_via_lsp(
9664 lsp_location.uri.clone(),
9665 server_id,
9666 language_server_name,
9667 cx,
9668 )
9669 })
9670 })
9671 })?;
9672 let location = match location_task {
9673 Some(task) => Some({
9674 let target_buffer_handle = task.await.context("open local buffer")?;
9675 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9676 let target_start = target_buffer
9677 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9678 let target_end = target_buffer
9679 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9680 target_buffer.anchor_after(target_start)
9681 ..target_buffer.anchor_before(target_end)
9682 })?;
9683 Location {
9684 buffer: target_buffer_handle,
9685 range,
9686 }
9687 }),
9688 None => None,
9689 };
9690 Ok(location)
9691 })
9692 }
9693
9694 pub fn find_all_references(
9695 &mut self,
9696 _: &FindAllReferences,
9697 cx: &mut ViewContext<Self>,
9698 ) -> Option<Task<Result<Navigated>>> {
9699 let selection = self.selections.newest::<usize>(cx);
9700 let multi_buffer = self.buffer.read(cx);
9701 let head = selection.head();
9702
9703 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9704 let head_anchor = multi_buffer_snapshot.anchor_at(
9705 head,
9706 if head < selection.tail() {
9707 Bias::Right
9708 } else {
9709 Bias::Left
9710 },
9711 );
9712
9713 match self
9714 .find_all_references_task_sources
9715 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9716 {
9717 Ok(_) => {
9718 log::info!(
9719 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9720 );
9721 return None;
9722 }
9723 Err(i) => {
9724 self.find_all_references_task_sources.insert(i, head_anchor);
9725 }
9726 }
9727
9728 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9729 let workspace = self.workspace()?;
9730 let project = workspace.read(cx).project().clone();
9731 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9732 Some(cx.spawn(|editor, mut cx| async move {
9733 let _cleanup = defer({
9734 let mut cx = cx.clone();
9735 move || {
9736 let _ = editor.update(&mut cx, |editor, _| {
9737 if let Ok(i) =
9738 editor
9739 .find_all_references_task_sources
9740 .binary_search_by(|anchor| {
9741 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9742 })
9743 {
9744 editor.find_all_references_task_sources.remove(i);
9745 }
9746 });
9747 }
9748 });
9749
9750 let locations = references.await?;
9751 if locations.is_empty() {
9752 return anyhow::Ok(Navigated::No);
9753 }
9754
9755 workspace.update(&mut cx, |workspace, cx| {
9756 let title = locations
9757 .first()
9758 .as_ref()
9759 .map(|location| {
9760 let buffer = location.buffer.read(cx);
9761 format!(
9762 "References to `{}`",
9763 buffer
9764 .text_for_range(location.range.clone())
9765 .collect::<String>()
9766 )
9767 })
9768 .unwrap();
9769 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9770 Navigated::Yes
9771 })
9772 }))
9773 }
9774
9775 /// Opens a multibuffer with the given project locations in it
9776 pub fn open_locations_in_multibuffer(
9777 workspace: &mut Workspace,
9778 mut locations: Vec<Location>,
9779 title: String,
9780 split: bool,
9781 cx: &mut ViewContext<Workspace>,
9782 ) {
9783 // If there are multiple definitions, open them in a multibuffer
9784 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9785 let mut locations = locations.into_iter().peekable();
9786 let mut ranges_to_highlight = Vec::new();
9787 let capability = workspace.project().read(cx).capability();
9788
9789 let excerpt_buffer = cx.new_model(|cx| {
9790 let mut multibuffer = MultiBuffer::new(capability);
9791 while let Some(location) = locations.next() {
9792 let buffer = location.buffer.read(cx);
9793 let mut ranges_for_buffer = Vec::new();
9794 let range = location.range.to_offset(buffer);
9795 ranges_for_buffer.push(range.clone());
9796
9797 while let Some(next_location) = locations.peek() {
9798 if next_location.buffer == location.buffer {
9799 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9800 locations.next();
9801 } else {
9802 break;
9803 }
9804 }
9805
9806 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9807 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9808 location.buffer.clone(),
9809 ranges_for_buffer,
9810 DEFAULT_MULTIBUFFER_CONTEXT,
9811 cx,
9812 ))
9813 }
9814
9815 multibuffer.with_title(title)
9816 });
9817
9818 let editor = cx.new_view(|cx| {
9819 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9820 });
9821 editor.update(cx, |editor, cx| {
9822 if let Some(first_range) = ranges_to_highlight.first() {
9823 editor.change_selections(None, cx, |selections| {
9824 selections.clear_disjoint();
9825 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9826 });
9827 }
9828 editor.highlight_background::<Self>(
9829 &ranges_to_highlight,
9830 |theme| theme.editor_highlighted_line_background,
9831 cx,
9832 );
9833 editor.register_buffers_with_language_servers(cx);
9834 });
9835
9836 let item = Box::new(editor);
9837 let item_id = item.item_id();
9838
9839 if split {
9840 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9841 } else {
9842 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9843 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9844 pane.close_current_preview_item(cx)
9845 } else {
9846 None
9847 }
9848 });
9849 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9850 }
9851 workspace.active_pane().update(cx, |pane, cx| {
9852 pane.set_preview_item_id(Some(item_id), cx);
9853 });
9854 }
9855
9856 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9857 use language::ToOffset as _;
9858
9859 let provider = self.semantics_provider.clone()?;
9860 let selection = self.selections.newest_anchor().clone();
9861 let (cursor_buffer, cursor_buffer_position) = self
9862 .buffer
9863 .read(cx)
9864 .text_anchor_for_position(selection.head(), cx)?;
9865 let (tail_buffer, cursor_buffer_position_end) = self
9866 .buffer
9867 .read(cx)
9868 .text_anchor_for_position(selection.tail(), cx)?;
9869 if tail_buffer != cursor_buffer {
9870 return None;
9871 }
9872
9873 let snapshot = cursor_buffer.read(cx).snapshot();
9874 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9875 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9876 let prepare_rename = provider
9877 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
9878 .unwrap_or_else(|| Task::ready(Ok(None)));
9879 drop(snapshot);
9880
9881 Some(cx.spawn(|this, mut cx| async move {
9882 let rename_range = if let Some(range) = prepare_rename.await? {
9883 Some(range)
9884 } else {
9885 this.update(&mut cx, |this, cx| {
9886 let buffer = this.buffer.read(cx).snapshot(cx);
9887 let mut buffer_highlights = this
9888 .document_highlights_for_position(selection.head(), &buffer)
9889 .filter(|highlight| {
9890 highlight.start.excerpt_id == selection.head().excerpt_id
9891 && highlight.end.excerpt_id == selection.head().excerpt_id
9892 });
9893 buffer_highlights
9894 .next()
9895 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9896 })?
9897 };
9898 if let Some(rename_range) = rename_range {
9899 this.update(&mut cx, |this, cx| {
9900 let snapshot = cursor_buffer.read(cx).snapshot();
9901 let rename_buffer_range = rename_range.to_offset(&snapshot);
9902 let cursor_offset_in_rename_range =
9903 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9904 let cursor_offset_in_rename_range_end =
9905 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9906
9907 this.take_rename(false, cx);
9908 let buffer = this.buffer.read(cx).read(cx);
9909 let cursor_offset = selection.head().to_offset(&buffer);
9910 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9911 let rename_end = rename_start + rename_buffer_range.len();
9912 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9913 let mut old_highlight_id = None;
9914 let old_name: Arc<str> = buffer
9915 .chunks(rename_start..rename_end, true)
9916 .map(|chunk| {
9917 if old_highlight_id.is_none() {
9918 old_highlight_id = chunk.syntax_highlight_id;
9919 }
9920 chunk.text
9921 })
9922 .collect::<String>()
9923 .into();
9924
9925 drop(buffer);
9926
9927 // Position the selection in the rename editor so that it matches the current selection.
9928 this.show_local_selections = false;
9929 let rename_editor = cx.new_view(|cx| {
9930 let mut editor = Editor::single_line(cx);
9931 editor.buffer.update(cx, |buffer, cx| {
9932 buffer.edit([(0..0, old_name.clone())], None, cx)
9933 });
9934 let rename_selection_range = match cursor_offset_in_rename_range
9935 .cmp(&cursor_offset_in_rename_range_end)
9936 {
9937 Ordering::Equal => {
9938 editor.select_all(&SelectAll, cx);
9939 return editor;
9940 }
9941 Ordering::Less => {
9942 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9943 }
9944 Ordering::Greater => {
9945 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9946 }
9947 };
9948 if rename_selection_range.end > old_name.len() {
9949 editor.select_all(&SelectAll, cx);
9950 } else {
9951 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9952 s.select_ranges([rename_selection_range]);
9953 });
9954 }
9955 editor
9956 });
9957 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
9958 if e == &EditorEvent::Focused {
9959 cx.emit(EditorEvent::FocusedIn)
9960 }
9961 })
9962 .detach();
9963
9964 let write_highlights =
9965 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
9966 let read_highlights =
9967 this.clear_background_highlights::<DocumentHighlightRead>(cx);
9968 let ranges = write_highlights
9969 .iter()
9970 .flat_map(|(_, ranges)| ranges.iter())
9971 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
9972 .cloned()
9973 .collect();
9974
9975 this.highlight_text::<Rename>(
9976 ranges,
9977 HighlightStyle {
9978 fade_out: Some(0.6),
9979 ..Default::default()
9980 },
9981 cx,
9982 );
9983 let rename_focus_handle = rename_editor.focus_handle(cx);
9984 cx.focus(&rename_focus_handle);
9985 let block_id = this.insert_blocks(
9986 [BlockProperties {
9987 style: BlockStyle::Flex,
9988 placement: BlockPlacement::Below(range.start),
9989 height: 1,
9990 render: Arc::new({
9991 let rename_editor = rename_editor.clone();
9992 move |cx: &mut BlockContext| {
9993 let mut text_style = cx.editor_style.text.clone();
9994 if let Some(highlight_style) = old_highlight_id
9995 .and_then(|h| h.style(&cx.editor_style.syntax))
9996 {
9997 text_style = text_style.highlight(highlight_style);
9998 }
9999 div()
10000 .block_mouse_down()
10001 .pl(cx.anchor_x)
10002 .child(EditorElement::new(
10003 &rename_editor,
10004 EditorStyle {
10005 background: cx.theme().system().transparent,
10006 local_player: cx.editor_style.local_player,
10007 text: text_style,
10008 scrollbar_width: cx.editor_style.scrollbar_width,
10009 syntax: cx.editor_style.syntax.clone(),
10010 status: cx.editor_style.status.clone(),
10011 inlay_hints_style: HighlightStyle {
10012 font_weight: Some(FontWeight::BOLD),
10013 ..make_inlay_hints_style(cx)
10014 },
10015 inline_completion_styles: make_suggestion_styles(
10016 cx,
10017 ),
10018 ..EditorStyle::default()
10019 },
10020 ))
10021 .into_any_element()
10022 }
10023 }),
10024 priority: 0,
10025 }],
10026 Some(Autoscroll::fit()),
10027 cx,
10028 )[0];
10029 this.pending_rename = Some(RenameState {
10030 range,
10031 old_name,
10032 editor: rename_editor,
10033 block_id,
10034 });
10035 })?;
10036 }
10037
10038 Ok(())
10039 }))
10040 }
10041
10042 pub fn confirm_rename(
10043 &mut self,
10044 _: &ConfirmRename,
10045 cx: &mut ViewContext<Self>,
10046 ) -> Option<Task<Result<()>>> {
10047 let rename = self.take_rename(false, cx)?;
10048 let workspace = self.workspace()?.downgrade();
10049 let (buffer, start) = self
10050 .buffer
10051 .read(cx)
10052 .text_anchor_for_position(rename.range.start, cx)?;
10053 let (end_buffer, _) = self
10054 .buffer
10055 .read(cx)
10056 .text_anchor_for_position(rename.range.end, cx)?;
10057 if buffer != end_buffer {
10058 return None;
10059 }
10060
10061 let old_name = rename.old_name;
10062 let new_name = rename.editor.read(cx).text(cx);
10063
10064 let rename = self.semantics_provider.as_ref()?.perform_rename(
10065 &buffer,
10066 start,
10067 new_name.clone(),
10068 cx,
10069 )?;
10070
10071 Some(cx.spawn(|editor, mut cx| async move {
10072 let project_transaction = rename.await?;
10073 Self::open_project_transaction(
10074 &editor,
10075 workspace,
10076 project_transaction,
10077 format!("Rename: {} → {}", old_name, new_name),
10078 cx.clone(),
10079 )
10080 .await?;
10081
10082 editor.update(&mut cx, |editor, cx| {
10083 editor.refresh_document_highlights(cx);
10084 })?;
10085 Ok(())
10086 }))
10087 }
10088
10089 fn take_rename(
10090 &mut self,
10091 moving_cursor: bool,
10092 cx: &mut ViewContext<Self>,
10093 ) -> Option<RenameState> {
10094 let rename = self.pending_rename.take()?;
10095 if rename.editor.focus_handle(cx).is_focused(cx) {
10096 cx.focus(&self.focus_handle);
10097 }
10098
10099 self.remove_blocks(
10100 [rename.block_id].into_iter().collect(),
10101 Some(Autoscroll::fit()),
10102 cx,
10103 );
10104 self.clear_highlights::<Rename>(cx);
10105 self.show_local_selections = true;
10106
10107 if moving_cursor {
10108 let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10109 editor.selections.newest::<usize>(cx).head()
10110 });
10111
10112 // Update the selection to match the position of the selection inside
10113 // the rename editor.
10114 let snapshot = self.buffer.read(cx).read(cx);
10115 let rename_range = rename.range.to_offset(&snapshot);
10116 let cursor_in_editor = snapshot
10117 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10118 .min(rename_range.end);
10119 drop(snapshot);
10120
10121 self.change_selections(None, cx, |s| {
10122 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10123 });
10124 } else {
10125 self.refresh_document_highlights(cx);
10126 }
10127
10128 Some(rename)
10129 }
10130
10131 pub fn pending_rename(&self) -> Option<&RenameState> {
10132 self.pending_rename.as_ref()
10133 }
10134
10135 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10136 let project = match &self.project {
10137 Some(project) => project.clone(),
10138 None => return None,
10139 };
10140
10141 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10142 }
10143
10144 fn format_selections(
10145 &mut self,
10146 _: &FormatSelections,
10147 cx: &mut ViewContext<Self>,
10148 ) -> Option<Task<Result<()>>> {
10149 let project = match &self.project {
10150 Some(project) => project.clone(),
10151 None => return None,
10152 };
10153
10154 let selections = self
10155 .selections
10156 .all_adjusted(cx)
10157 .into_iter()
10158 .filter(|s| !s.is_empty())
10159 .collect_vec();
10160
10161 Some(self.perform_format(
10162 project,
10163 FormatTrigger::Manual,
10164 FormatTarget::Ranges(selections),
10165 cx,
10166 ))
10167 }
10168
10169 fn perform_format(
10170 &mut self,
10171 project: Model<Project>,
10172 trigger: FormatTrigger,
10173 target: FormatTarget,
10174 cx: &mut ViewContext<Self>,
10175 ) -> Task<Result<()>> {
10176 let buffer = self.buffer().clone();
10177 let mut buffers = buffer.read(cx).all_buffers();
10178 if trigger == FormatTrigger::Save {
10179 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10180 }
10181
10182 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10183 let format = project.update(cx, |project, cx| {
10184 project.format(buffers, true, trigger, target, cx)
10185 });
10186
10187 cx.spawn(|_, mut cx| async move {
10188 let transaction = futures::select_biased! {
10189 () = timeout => {
10190 log::warn!("timed out waiting for formatting");
10191 None
10192 }
10193 transaction = format.log_err().fuse() => transaction,
10194 };
10195
10196 buffer
10197 .update(&mut cx, |buffer, cx| {
10198 if let Some(transaction) = transaction {
10199 if !buffer.is_singleton() {
10200 buffer.push_transaction(&transaction.0, cx);
10201 }
10202 }
10203
10204 cx.notify();
10205 })
10206 .ok();
10207
10208 Ok(())
10209 })
10210 }
10211
10212 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10213 if let Some(project) = self.project.clone() {
10214 self.buffer.update(cx, |multi_buffer, cx| {
10215 project.update(cx, |project, cx| {
10216 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10217 });
10218 })
10219 }
10220 }
10221
10222 fn cancel_language_server_work(
10223 &mut self,
10224 _: &actions::CancelLanguageServerWork,
10225 cx: &mut ViewContext<Self>,
10226 ) {
10227 if let Some(project) = self.project.clone() {
10228 self.buffer.update(cx, |multi_buffer, cx| {
10229 project.update(cx, |project, cx| {
10230 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10231 });
10232 })
10233 }
10234 }
10235
10236 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10237 cx.show_character_palette();
10238 }
10239
10240 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10241 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10242 let buffer = self.buffer.read(cx).snapshot(cx);
10243 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10244 let is_valid = buffer
10245 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10246 .any(|entry| {
10247 entry.diagnostic.is_primary
10248 && !entry.range.is_empty()
10249 && entry.range.start == primary_range_start
10250 && entry.diagnostic.message == active_diagnostics.primary_message
10251 });
10252
10253 if is_valid != active_diagnostics.is_valid {
10254 active_diagnostics.is_valid = is_valid;
10255 let mut new_styles = HashMap::default();
10256 for (block_id, diagnostic) in &active_diagnostics.blocks {
10257 new_styles.insert(
10258 *block_id,
10259 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10260 );
10261 }
10262 self.display_map.update(cx, |display_map, _cx| {
10263 display_map.replace_blocks(new_styles)
10264 });
10265 }
10266 }
10267 }
10268
10269 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10270 self.dismiss_diagnostics(cx);
10271 let snapshot = self.snapshot(cx);
10272 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10273 let buffer = self.buffer.read(cx).snapshot(cx);
10274
10275 let mut primary_range = None;
10276 let mut primary_message = None;
10277 let mut group_end = Point::zero();
10278 let diagnostic_group = buffer
10279 .diagnostic_group::<MultiBufferPoint>(group_id)
10280 .filter_map(|entry| {
10281 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10282 && (entry.range.start.row == entry.range.end.row
10283 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10284 {
10285 return None;
10286 }
10287 if entry.range.end > group_end {
10288 group_end = entry.range.end;
10289 }
10290 if entry.diagnostic.is_primary {
10291 primary_range = Some(entry.range.clone());
10292 primary_message = Some(entry.diagnostic.message.clone());
10293 }
10294 Some(entry)
10295 })
10296 .collect::<Vec<_>>();
10297 let primary_range = primary_range?;
10298 let primary_message = primary_message?;
10299 let primary_range =
10300 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10301
10302 let blocks = display_map
10303 .insert_blocks(
10304 diagnostic_group.iter().map(|entry| {
10305 let diagnostic = entry.diagnostic.clone();
10306 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10307 BlockProperties {
10308 style: BlockStyle::Fixed,
10309 placement: BlockPlacement::Below(
10310 buffer.anchor_after(entry.range.start),
10311 ),
10312 height: message_height,
10313 render: diagnostic_block_renderer(diagnostic, None, true, true),
10314 priority: 0,
10315 }
10316 }),
10317 cx,
10318 )
10319 .into_iter()
10320 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10321 .collect();
10322
10323 Some(ActiveDiagnosticGroup {
10324 primary_range,
10325 primary_message,
10326 group_id,
10327 blocks,
10328 is_valid: true,
10329 })
10330 });
10331 self.active_diagnostics.is_some()
10332 }
10333
10334 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10335 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10336 self.display_map.update(cx, |display_map, cx| {
10337 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10338 });
10339 cx.notify();
10340 }
10341 }
10342
10343 pub fn set_selections_from_remote(
10344 &mut self,
10345 selections: Vec<Selection<Anchor>>,
10346 pending_selection: Option<Selection<Anchor>>,
10347 cx: &mut ViewContext<Self>,
10348 ) {
10349 let old_cursor_position = self.selections.newest_anchor().head();
10350 self.selections.change_with(cx, |s| {
10351 s.select_anchors(selections);
10352 if let Some(pending_selection) = pending_selection {
10353 s.set_pending(pending_selection, SelectMode::Character);
10354 } else {
10355 s.clear_pending();
10356 }
10357 });
10358 self.selections_did_change(false, &old_cursor_position, true, cx);
10359 }
10360
10361 fn push_to_selection_history(&mut self) {
10362 self.selection_history.push(SelectionHistoryEntry {
10363 selections: self.selections.disjoint_anchors(),
10364 select_next_state: self.select_next_state.clone(),
10365 select_prev_state: self.select_prev_state.clone(),
10366 add_selections_state: self.add_selections_state.clone(),
10367 });
10368 }
10369
10370 pub fn transact(
10371 &mut self,
10372 cx: &mut ViewContext<Self>,
10373 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10374 ) -> Option<TransactionId> {
10375 self.start_transaction_at(Instant::now(), cx);
10376 update(self, cx);
10377 self.end_transaction_at(Instant::now(), cx)
10378 }
10379
10380 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10381 self.end_selection(cx);
10382 if let Some(tx_id) = self
10383 .buffer
10384 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10385 {
10386 self.selection_history
10387 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10388 cx.emit(EditorEvent::TransactionBegun {
10389 transaction_id: tx_id,
10390 })
10391 }
10392 }
10393
10394 fn end_transaction_at(
10395 &mut self,
10396 now: Instant,
10397 cx: &mut ViewContext<Self>,
10398 ) -> Option<TransactionId> {
10399 if let Some(transaction_id) = self
10400 .buffer
10401 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10402 {
10403 if let Some((_, end_selections)) =
10404 self.selection_history.transaction_mut(transaction_id)
10405 {
10406 *end_selections = Some(self.selections.disjoint_anchors());
10407 } else {
10408 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10409 }
10410
10411 cx.emit(EditorEvent::Edited { transaction_id });
10412 Some(transaction_id)
10413 } else {
10414 None
10415 }
10416 }
10417
10418 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10419 if self.is_singleton(cx) {
10420 let selection = self.selections.newest::<Point>(cx);
10421
10422 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10423 let range = if selection.is_empty() {
10424 let point = selection.head().to_display_point(&display_map);
10425 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10426 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10427 .to_point(&display_map);
10428 start..end
10429 } else {
10430 selection.range()
10431 };
10432 if display_map.folds_in_range(range).next().is_some() {
10433 self.unfold_lines(&Default::default(), cx)
10434 } else {
10435 self.fold(&Default::default(), cx)
10436 }
10437 } else {
10438 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10439 let mut toggled_buffers = HashSet::default();
10440 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10441 self.selections
10442 .disjoint_anchors()
10443 .into_iter()
10444 .map(|selection| selection.range()),
10445 ) {
10446 let buffer_id = buffer_snapshot.remote_id();
10447 if toggled_buffers.insert(buffer_id) {
10448 if self.buffer_folded(buffer_id, cx) {
10449 self.unfold_buffer(buffer_id, cx);
10450 } else {
10451 self.fold_buffer(buffer_id, cx);
10452 }
10453 }
10454 }
10455 }
10456 }
10457
10458 pub fn toggle_fold_recursive(
10459 &mut self,
10460 _: &actions::ToggleFoldRecursive,
10461 cx: &mut ViewContext<Self>,
10462 ) {
10463 let selection = self.selections.newest::<Point>(cx);
10464
10465 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10466 let range = if selection.is_empty() {
10467 let point = selection.head().to_display_point(&display_map);
10468 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10469 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10470 .to_point(&display_map);
10471 start..end
10472 } else {
10473 selection.range()
10474 };
10475 if display_map.folds_in_range(range).next().is_some() {
10476 self.unfold_recursive(&Default::default(), cx)
10477 } else {
10478 self.fold_recursive(&Default::default(), cx)
10479 }
10480 }
10481
10482 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10483 if self.is_singleton(cx) {
10484 let mut to_fold = Vec::new();
10485 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10486 let selections = self.selections.all_adjusted(cx);
10487
10488 for selection in selections {
10489 let range = selection.range().sorted();
10490 let buffer_start_row = range.start.row;
10491
10492 if range.start.row != range.end.row {
10493 let mut found = false;
10494 let mut row = range.start.row;
10495 while row <= range.end.row {
10496 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10497 {
10498 found = true;
10499 row = crease.range().end.row + 1;
10500 to_fold.push(crease);
10501 } else {
10502 row += 1
10503 }
10504 }
10505 if found {
10506 continue;
10507 }
10508 }
10509
10510 for row in (0..=range.start.row).rev() {
10511 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10512 if crease.range().end.row >= buffer_start_row {
10513 to_fold.push(crease);
10514 if row <= range.start.row {
10515 break;
10516 }
10517 }
10518 }
10519 }
10520 }
10521
10522 self.fold_creases(to_fold, true, cx);
10523 } else {
10524 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10525 let mut folded_buffers = HashSet::default();
10526 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10527 self.selections
10528 .disjoint_anchors()
10529 .into_iter()
10530 .map(|selection| selection.range()),
10531 ) {
10532 let buffer_id = buffer_snapshot.remote_id();
10533 if folded_buffers.insert(buffer_id) {
10534 self.fold_buffer(buffer_id, cx);
10535 }
10536 }
10537 }
10538 }
10539
10540 fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10541 if !self.buffer.read(cx).is_singleton() {
10542 return;
10543 }
10544
10545 let fold_at_level = fold_at.level;
10546 let snapshot = self.buffer.read(cx).snapshot(cx);
10547 let mut to_fold = Vec::new();
10548 let mut stack = vec![(0, snapshot.max_row().0, 1)];
10549
10550 while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10551 while start_row < end_row {
10552 match self
10553 .snapshot(cx)
10554 .crease_for_buffer_row(MultiBufferRow(start_row))
10555 {
10556 Some(crease) => {
10557 let nested_start_row = crease.range().start.row + 1;
10558 let nested_end_row = crease.range().end.row;
10559
10560 if current_level < fold_at_level {
10561 stack.push((nested_start_row, nested_end_row, current_level + 1));
10562 } else if current_level == fold_at_level {
10563 to_fold.push(crease);
10564 }
10565
10566 start_row = nested_end_row + 1;
10567 }
10568 None => start_row += 1,
10569 }
10570 }
10571 }
10572
10573 self.fold_creases(to_fold, true, cx);
10574 }
10575
10576 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10577 if self.buffer.read(cx).is_singleton() {
10578 let mut fold_ranges = Vec::new();
10579 let snapshot = self.buffer.read(cx).snapshot(cx);
10580
10581 for row in 0..snapshot.max_row().0 {
10582 if let Some(foldable_range) =
10583 self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10584 {
10585 fold_ranges.push(foldable_range);
10586 }
10587 }
10588
10589 self.fold_creases(fold_ranges, true, cx);
10590 } else {
10591 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10592 editor
10593 .update(&mut cx, |editor, cx| {
10594 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10595 editor.fold_buffer(buffer_id, cx);
10596 }
10597 })
10598 .ok();
10599 });
10600 }
10601 }
10602
10603 pub fn fold_function_bodies(
10604 &mut self,
10605 _: &actions::FoldFunctionBodies,
10606 cx: &mut ViewContext<Self>,
10607 ) {
10608 let snapshot = self.buffer.read(cx).snapshot(cx);
10609 let Some((_, _, buffer)) = snapshot.as_singleton() else {
10610 return;
10611 };
10612 let creases = buffer
10613 .function_body_fold_ranges(0..buffer.len())
10614 .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10615 .collect();
10616
10617 self.fold_creases(creases, true, cx);
10618 }
10619
10620 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10621 let mut to_fold = Vec::new();
10622 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10623 let selections = self.selections.all_adjusted(cx);
10624
10625 for selection in selections {
10626 let range = selection.range().sorted();
10627 let buffer_start_row = range.start.row;
10628
10629 if range.start.row != range.end.row {
10630 let mut found = false;
10631 for row in range.start.row..=range.end.row {
10632 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10633 found = true;
10634 to_fold.push(crease);
10635 }
10636 }
10637 if found {
10638 continue;
10639 }
10640 }
10641
10642 for row in (0..=range.start.row).rev() {
10643 if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10644 if crease.range().end.row >= buffer_start_row {
10645 to_fold.push(crease);
10646 } else {
10647 break;
10648 }
10649 }
10650 }
10651 }
10652
10653 self.fold_creases(to_fold, true, cx);
10654 }
10655
10656 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10657 let buffer_row = fold_at.buffer_row;
10658 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10659
10660 if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10661 let autoscroll = self
10662 .selections
10663 .all::<Point>(cx)
10664 .iter()
10665 .any(|selection| crease.range().overlaps(&selection.range()));
10666
10667 self.fold_creases(vec![crease], autoscroll, cx);
10668 }
10669 }
10670
10671 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10672 if self.is_singleton(cx) {
10673 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10674 let buffer = &display_map.buffer_snapshot;
10675 let selections = self.selections.all::<Point>(cx);
10676 let ranges = selections
10677 .iter()
10678 .map(|s| {
10679 let range = s.display_range(&display_map).sorted();
10680 let mut start = range.start.to_point(&display_map);
10681 let mut end = range.end.to_point(&display_map);
10682 start.column = 0;
10683 end.column = buffer.line_len(MultiBufferRow(end.row));
10684 start..end
10685 })
10686 .collect::<Vec<_>>();
10687
10688 self.unfold_ranges(&ranges, true, true, cx);
10689 } else {
10690 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10691 let mut unfolded_buffers = HashSet::default();
10692 for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10693 self.selections
10694 .disjoint_anchors()
10695 .into_iter()
10696 .map(|selection| selection.range()),
10697 ) {
10698 let buffer_id = buffer_snapshot.remote_id();
10699 if unfolded_buffers.insert(buffer_id) {
10700 self.unfold_buffer(buffer_id, cx);
10701 }
10702 }
10703 }
10704 }
10705
10706 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10707 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10708 let selections = self.selections.all::<Point>(cx);
10709 let ranges = selections
10710 .iter()
10711 .map(|s| {
10712 let mut range = s.display_range(&display_map).sorted();
10713 *range.start.column_mut() = 0;
10714 *range.end.column_mut() = display_map.line_len(range.end.row());
10715 let start = range.start.to_point(&display_map);
10716 let end = range.end.to_point(&display_map);
10717 start..end
10718 })
10719 .collect::<Vec<_>>();
10720
10721 self.unfold_ranges(&ranges, true, true, cx);
10722 }
10723
10724 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10725 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10726
10727 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10728 ..Point::new(
10729 unfold_at.buffer_row.0,
10730 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10731 );
10732
10733 let autoscroll = self
10734 .selections
10735 .all::<Point>(cx)
10736 .iter()
10737 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10738
10739 self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10740 }
10741
10742 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10743 if self.buffer.read(cx).is_singleton() {
10744 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10745 self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10746 } else {
10747 self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10748 editor
10749 .update(&mut cx, |editor, cx| {
10750 for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10751 editor.unfold_buffer(buffer_id, cx);
10752 }
10753 })
10754 .ok();
10755 });
10756 }
10757 }
10758
10759 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10760 let selections = self.selections.all::<Point>(cx);
10761 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10762 let line_mode = self.selections.line_mode;
10763 let ranges = selections
10764 .into_iter()
10765 .map(|s| {
10766 if line_mode {
10767 let start = Point::new(s.start.row, 0);
10768 let end = Point::new(
10769 s.end.row,
10770 display_map
10771 .buffer_snapshot
10772 .line_len(MultiBufferRow(s.end.row)),
10773 );
10774 Crease::simple(start..end, display_map.fold_placeholder.clone())
10775 } else {
10776 Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10777 }
10778 })
10779 .collect::<Vec<_>>();
10780 self.fold_creases(ranges, true, cx);
10781 }
10782
10783 pub fn fold_creases<T: ToOffset + Clone>(
10784 &mut self,
10785 creases: Vec<Crease<T>>,
10786 auto_scroll: bool,
10787 cx: &mut ViewContext<Self>,
10788 ) {
10789 if creases.is_empty() {
10790 return;
10791 }
10792
10793 let mut buffers_affected = HashSet::default();
10794 let multi_buffer = self.buffer().read(cx);
10795 for crease in &creases {
10796 if let Some((_, buffer, _)) =
10797 multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10798 {
10799 buffers_affected.insert(buffer.read(cx).remote_id());
10800 };
10801 }
10802
10803 self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10804
10805 if auto_scroll {
10806 self.request_autoscroll(Autoscroll::fit(), cx);
10807 }
10808
10809 for buffer_id in buffers_affected {
10810 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10811 }
10812
10813 cx.notify();
10814
10815 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10816 // Clear diagnostics block when folding a range that contains it.
10817 let snapshot = self.snapshot(cx);
10818 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10819 drop(snapshot);
10820 self.active_diagnostics = Some(active_diagnostics);
10821 self.dismiss_diagnostics(cx);
10822 } else {
10823 self.active_diagnostics = Some(active_diagnostics);
10824 }
10825 }
10826
10827 self.scrollbar_marker_state.dirty = true;
10828 }
10829
10830 /// Removes any folds whose ranges intersect any of the given ranges.
10831 pub fn unfold_ranges<T: ToOffset + Clone>(
10832 &mut self,
10833 ranges: &[Range<T>],
10834 inclusive: bool,
10835 auto_scroll: bool,
10836 cx: &mut ViewContext<Self>,
10837 ) {
10838 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10839 map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10840 });
10841 }
10842
10843 pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10844 if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10845 return;
10846 }
10847 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10848 return;
10849 };
10850 let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10851 self.display_map
10852 .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10853 cx.emit(EditorEvent::BufferFoldToggled {
10854 ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
10855 folded: true,
10856 });
10857 cx.notify();
10858 }
10859
10860 pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10861 if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
10862 return;
10863 }
10864 let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10865 return;
10866 };
10867 let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10868 self.display_map.update(cx, |display_map, cx| {
10869 display_map.unfold_buffer(buffer_id, cx);
10870 });
10871 cx.emit(EditorEvent::BufferFoldToggled {
10872 ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
10873 folded: false,
10874 });
10875 cx.notify();
10876 }
10877
10878 pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
10879 self.display_map.read(cx).buffer_folded(buffer)
10880 }
10881
10882 /// Removes any folds with the given ranges.
10883 pub fn remove_folds_with_type<T: ToOffset + Clone>(
10884 &mut self,
10885 ranges: &[Range<T>],
10886 type_id: TypeId,
10887 auto_scroll: bool,
10888 cx: &mut ViewContext<Self>,
10889 ) {
10890 self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10891 map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
10892 });
10893 }
10894
10895 fn remove_folds_with<T: ToOffset + Clone>(
10896 &mut self,
10897 ranges: &[Range<T>],
10898 auto_scroll: bool,
10899 cx: &mut ViewContext<Self>,
10900 update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
10901 ) {
10902 if ranges.is_empty() {
10903 return;
10904 }
10905
10906 let mut buffers_affected = HashSet::default();
10907 let multi_buffer = self.buffer().read(cx);
10908 for range in ranges {
10909 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10910 buffers_affected.insert(buffer.read(cx).remote_id());
10911 };
10912 }
10913
10914 self.display_map.update(cx, update);
10915
10916 if auto_scroll {
10917 self.request_autoscroll(Autoscroll::fit(), cx);
10918 }
10919
10920 for buffer_id in buffers_affected {
10921 Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10922 }
10923
10924 cx.notify();
10925 self.scrollbar_marker_state.dirty = true;
10926 self.active_indent_guides_state.dirty = true;
10927 }
10928
10929 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10930 self.display_map.read(cx).fold_placeholder.clone()
10931 }
10932
10933 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10934 if hovered != self.gutter_hovered {
10935 self.gutter_hovered = hovered;
10936 cx.notify();
10937 }
10938 }
10939
10940 pub fn insert_blocks(
10941 &mut self,
10942 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10943 autoscroll: Option<Autoscroll>,
10944 cx: &mut ViewContext<Self>,
10945 ) -> Vec<CustomBlockId> {
10946 let blocks = self
10947 .display_map
10948 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10949 if let Some(autoscroll) = autoscroll {
10950 self.request_autoscroll(autoscroll, cx);
10951 }
10952 cx.notify();
10953 blocks
10954 }
10955
10956 pub fn resize_blocks(
10957 &mut self,
10958 heights: HashMap<CustomBlockId, u32>,
10959 autoscroll: Option<Autoscroll>,
10960 cx: &mut ViewContext<Self>,
10961 ) {
10962 self.display_map
10963 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10964 if let Some(autoscroll) = autoscroll {
10965 self.request_autoscroll(autoscroll, cx);
10966 }
10967 cx.notify();
10968 }
10969
10970 pub fn replace_blocks(
10971 &mut self,
10972 renderers: HashMap<CustomBlockId, RenderBlock>,
10973 autoscroll: Option<Autoscroll>,
10974 cx: &mut ViewContext<Self>,
10975 ) {
10976 self.display_map
10977 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10978 if let Some(autoscroll) = autoscroll {
10979 self.request_autoscroll(autoscroll, cx);
10980 }
10981 cx.notify();
10982 }
10983
10984 pub fn remove_blocks(
10985 &mut self,
10986 block_ids: HashSet<CustomBlockId>,
10987 autoscroll: Option<Autoscroll>,
10988 cx: &mut ViewContext<Self>,
10989 ) {
10990 self.display_map.update(cx, |display_map, cx| {
10991 display_map.remove_blocks(block_ids, cx)
10992 });
10993 if let Some(autoscroll) = autoscroll {
10994 self.request_autoscroll(autoscroll, cx);
10995 }
10996 cx.notify();
10997 }
10998
10999 pub fn row_for_block(
11000 &self,
11001 block_id: CustomBlockId,
11002 cx: &mut ViewContext<Self>,
11003 ) -> Option<DisplayRow> {
11004 self.display_map
11005 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11006 }
11007
11008 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11009 self.focused_block = Some(focused_block);
11010 }
11011
11012 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11013 self.focused_block.take()
11014 }
11015
11016 pub fn insert_creases(
11017 &mut self,
11018 creases: impl IntoIterator<Item = Crease<Anchor>>,
11019 cx: &mut ViewContext<Self>,
11020 ) -> Vec<CreaseId> {
11021 self.display_map
11022 .update(cx, |map, cx| map.insert_creases(creases, cx))
11023 }
11024
11025 pub fn remove_creases(
11026 &mut self,
11027 ids: impl IntoIterator<Item = CreaseId>,
11028 cx: &mut ViewContext<Self>,
11029 ) {
11030 self.display_map
11031 .update(cx, |map, cx| map.remove_creases(ids, cx));
11032 }
11033
11034 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11035 self.display_map
11036 .update(cx, |map, cx| map.snapshot(cx))
11037 .longest_row()
11038 }
11039
11040 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11041 self.display_map
11042 .update(cx, |map, cx| map.snapshot(cx))
11043 .max_point()
11044 }
11045
11046 pub fn text(&self, cx: &AppContext) -> String {
11047 self.buffer.read(cx).read(cx).text()
11048 }
11049
11050 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11051 let text = self.text(cx);
11052 let text = text.trim();
11053
11054 if text.is_empty() {
11055 return None;
11056 }
11057
11058 Some(text.to_string())
11059 }
11060
11061 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11062 self.transact(cx, |this, cx| {
11063 this.buffer
11064 .read(cx)
11065 .as_singleton()
11066 .expect("you can only call set_text on editors for singleton buffers")
11067 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11068 });
11069 }
11070
11071 pub fn display_text(&self, cx: &mut AppContext) -> String {
11072 self.display_map
11073 .update(cx, |map, cx| map.snapshot(cx))
11074 .text()
11075 }
11076
11077 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11078 let mut wrap_guides = smallvec::smallvec![];
11079
11080 if self.show_wrap_guides == Some(false) {
11081 return wrap_guides;
11082 }
11083
11084 let settings = self.buffer.read(cx).settings_at(0, cx);
11085 if settings.show_wrap_guides {
11086 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11087 wrap_guides.push((soft_wrap as usize, true));
11088 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11089 wrap_guides.push((soft_wrap as usize, true));
11090 }
11091 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11092 }
11093
11094 wrap_guides
11095 }
11096
11097 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11098 let settings = self.buffer.read(cx).settings_at(0, cx);
11099 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11100 match mode {
11101 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11102 SoftWrap::None
11103 }
11104 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11105 language_settings::SoftWrap::PreferredLineLength => {
11106 SoftWrap::Column(settings.preferred_line_length)
11107 }
11108 language_settings::SoftWrap::Bounded => {
11109 SoftWrap::Bounded(settings.preferred_line_length)
11110 }
11111 }
11112 }
11113
11114 pub fn set_soft_wrap_mode(
11115 &mut self,
11116 mode: language_settings::SoftWrap,
11117 cx: &mut ViewContext<Self>,
11118 ) {
11119 self.soft_wrap_mode_override = Some(mode);
11120 cx.notify();
11121 }
11122
11123 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11124 self.text_style_refinement = Some(style);
11125 }
11126
11127 /// called by the Element so we know what style we were most recently rendered with.
11128 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11129 let rem_size = cx.rem_size();
11130 self.display_map.update(cx, |map, cx| {
11131 map.set_font(
11132 style.text.font(),
11133 style.text.font_size.to_pixels(rem_size),
11134 cx,
11135 )
11136 });
11137 self.style = Some(style);
11138 }
11139
11140 pub fn style(&self) -> Option<&EditorStyle> {
11141 self.style.as_ref()
11142 }
11143
11144 // Called by the element. This method is not designed to be called outside of the editor
11145 // element's layout code because it does not notify when rewrapping is computed synchronously.
11146 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11147 self.display_map
11148 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11149 }
11150
11151 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11152 if self.soft_wrap_mode_override.is_some() {
11153 self.soft_wrap_mode_override.take();
11154 } else {
11155 let soft_wrap = match self.soft_wrap_mode(cx) {
11156 SoftWrap::GitDiff => return,
11157 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11158 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11159 language_settings::SoftWrap::None
11160 }
11161 };
11162 self.soft_wrap_mode_override = Some(soft_wrap);
11163 }
11164 cx.notify();
11165 }
11166
11167 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11168 let Some(workspace) = self.workspace() else {
11169 return;
11170 };
11171 let fs = workspace.read(cx).app_state().fs.clone();
11172 let current_show = TabBarSettings::get_global(cx).show;
11173 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11174 setting.show = Some(!current_show);
11175 });
11176 }
11177
11178 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11179 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11180 self.buffer
11181 .read(cx)
11182 .settings_at(0, cx)
11183 .indent_guides
11184 .enabled
11185 });
11186 self.show_indent_guides = Some(!currently_enabled);
11187 cx.notify();
11188 }
11189
11190 fn should_show_indent_guides(&self) -> Option<bool> {
11191 self.show_indent_guides
11192 }
11193
11194 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11195 let mut editor_settings = EditorSettings::get_global(cx).clone();
11196 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11197 EditorSettings::override_global(editor_settings, cx);
11198 }
11199
11200 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11201 self.use_relative_line_numbers
11202 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11203 }
11204
11205 pub fn toggle_relative_line_numbers(
11206 &mut self,
11207 _: &ToggleRelativeLineNumbers,
11208 cx: &mut ViewContext<Self>,
11209 ) {
11210 let is_relative = self.should_use_relative_line_numbers(cx);
11211 self.set_relative_line_number(Some(!is_relative), cx)
11212 }
11213
11214 pub fn set_relative_line_number(
11215 &mut self,
11216 is_relative: Option<bool>,
11217 cx: &mut ViewContext<Self>,
11218 ) {
11219 self.use_relative_line_numbers = is_relative;
11220 cx.notify();
11221 }
11222
11223 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11224 self.show_gutter = show_gutter;
11225 cx.notify();
11226 }
11227
11228 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11229 self.show_line_numbers = Some(show_line_numbers);
11230 cx.notify();
11231 }
11232
11233 pub fn set_show_git_diff_gutter(
11234 &mut self,
11235 show_git_diff_gutter: bool,
11236 cx: &mut ViewContext<Self>,
11237 ) {
11238 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11239 cx.notify();
11240 }
11241
11242 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11243 self.show_code_actions = Some(show_code_actions);
11244 cx.notify();
11245 }
11246
11247 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11248 self.show_runnables = Some(show_runnables);
11249 cx.notify();
11250 }
11251
11252 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11253 if self.display_map.read(cx).masked != masked {
11254 self.display_map.update(cx, |map, _| map.masked = masked);
11255 }
11256 cx.notify()
11257 }
11258
11259 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11260 self.show_wrap_guides = Some(show_wrap_guides);
11261 cx.notify();
11262 }
11263
11264 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11265 self.show_indent_guides = Some(show_indent_guides);
11266 cx.notify();
11267 }
11268
11269 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11270 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11271 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11272 if let Some(dir) = file.abs_path(cx).parent() {
11273 return Some(dir.to_owned());
11274 }
11275 }
11276
11277 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11278 return Some(project_path.path.to_path_buf());
11279 }
11280 }
11281
11282 None
11283 }
11284
11285 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11286 self.active_excerpt(cx)?
11287 .1
11288 .read(cx)
11289 .file()
11290 .and_then(|f| f.as_local())
11291 }
11292
11293 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11294 if let Some(target) = self.target_file(cx) {
11295 cx.reveal_path(&target.abs_path(cx));
11296 }
11297 }
11298
11299 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11300 if let Some(file) = self.target_file(cx) {
11301 if let Some(path) = file.abs_path(cx).to_str() {
11302 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11303 }
11304 }
11305 }
11306
11307 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11308 if let Some(file) = self.target_file(cx) {
11309 if let Some(path) = file.path().to_str() {
11310 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11311 }
11312 }
11313 }
11314
11315 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11316 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11317
11318 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11319 self.start_git_blame(true, cx);
11320 }
11321
11322 cx.notify();
11323 }
11324
11325 pub fn toggle_git_blame_inline(
11326 &mut self,
11327 _: &ToggleGitBlameInline,
11328 cx: &mut ViewContext<Self>,
11329 ) {
11330 self.toggle_git_blame_inline_internal(true, cx);
11331 cx.notify();
11332 }
11333
11334 pub fn git_blame_inline_enabled(&self) -> bool {
11335 self.git_blame_inline_enabled
11336 }
11337
11338 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11339 self.show_selection_menu = self
11340 .show_selection_menu
11341 .map(|show_selections_menu| !show_selections_menu)
11342 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11343
11344 cx.notify();
11345 }
11346
11347 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11348 self.show_selection_menu
11349 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11350 }
11351
11352 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11353 if let Some(project) = self.project.as_ref() {
11354 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11355 return;
11356 };
11357
11358 if buffer.read(cx).file().is_none() {
11359 return;
11360 }
11361
11362 let focused = self.focus_handle(cx).contains_focused(cx);
11363
11364 let project = project.clone();
11365 let blame =
11366 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11367 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11368 self.blame = Some(blame);
11369 }
11370 }
11371
11372 fn toggle_git_blame_inline_internal(
11373 &mut self,
11374 user_triggered: bool,
11375 cx: &mut ViewContext<Self>,
11376 ) {
11377 if self.git_blame_inline_enabled {
11378 self.git_blame_inline_enabled = false;
11379 self.show_git_blame_inline = false;
11380 self.show_git_blame_inline_delay_task.take();
11381 } else {
11382 self.git_blame_inline_enabled = true;
11383 self.start_git_blame_inline(user_triggered, cx);
11384 }
11385
11386 cx.notify();
11387 }
11388
11389 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11390 self.start_git_blame(user_triggered, cx);
11391
11392 if ProjectSettings::get_global(cx)
11393 .git
11394 .inline_blame_delay()
11395 .is_some()
11396 {
11397 self.start_inline_blame_timer(cx);
11398 } else {
11399 self.show_git_blame_inline = true
11400 }
11401 }
11402
11403 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11404 self.blame.as_ref()
11405 }
11406
11407 pub fn show_git_blame_gutter(&self) -> bool {
11408 self.show_git_blame_gutter
11409 }
11410
11411 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11412 self.show_git_blame_gutter && self.has_blame_entries(cx)
11413 }
11414
11415 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11416 self.show_git_blame_inline
11417 && self.focus_handle.is_focused(cx)
11418 && !self.newest_selection_head_on_empty_line(cx)
11419 && self.has_blame_entries(cx)
11420 }
11421
11422 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11423 self.blame()
11424 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11425 }
11426
11427 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11428 let cursor_anchor = self.selections.newest_anchor().head();
11429
11430 let snapshot = self.buffer.read(cx).snapshot(cx);
11431 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11432
11433 snapshot.line_len(buffer_row) == 0
11434 }
11435
11436 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11437 let buffer_and_selection = maybe!({
11438 let selection = self.selections.newest::<Point>(cx);
11439 let selection_range = selection.range();
11440
11441 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11442 (buffer, selection_range.start.row..selection_range.end.row)
11443 } else {
11444 let buffer_ranges = self
11445 .buffer()
11446 .read(cx)
11447 .range_to_buffer_ranges(selection_range, cx);
11448
11449 let (buffer, range, _) = if selection.reversed {
11450 buffer_ranges.first()
11451 } else {
11452 buffer_ranges.last()
11453 }?;
11454
11455 let snapshot = buffer.read(cx).snapshot();
11456 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11457 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11458 (buffer.clone(), selection)
11459 };
11460
11461 Some((buffer, selection))
11462 });
11463
11464 let Some((buffer, selection)) = buffer_and_selection else {
11465 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11466 };
11467
11468 let Some(project) = self.project.as_ref() else {
11469 return Task::ready(Err(anyhow!("editor does not have project")));
11470 };
11471
11472 project.update(cx, |project, cx| {
11473 project.get_permalink_to_line(&buffer, selection, cx)
11474 })
11475 }
11476
11477 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11478 let permalink_task = self.get_permalink_to_line(cx);
11479 let workspace = self.workspace();
11480
11481 cx.spawn(|_, mut cx| async move {
11482 match permalink_task.await {
11483 Ok(permalink) => {
11484 cx.update(|cx| {
11485 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11486 })
11487 .ok();
11488 }
11489 Err(err) => {
11490 let message = format!("Failed to copy permalink: {err}");
11491
11492 Err::<(), anyhow::Error>(err).log_err();
11493
11494 if let Some(workspace) = workspace {
11495 workspace
11496 .update(&mut cx, |workspace, cx| {
11497 struct CopyPermalinkToLine;
11498
11499 workspace.show_toast(
11500 Toast::new(
11501 NotificationId::unique::<CopyPermalinkToLine>(),
11502 message,
11503 ),
11504 cx,
11505 )
11506 })
11507 .ok();
11508 }
11509 }
11510 }
11511 })
11512 .detach();
11513 }
11514
11515 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11516 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11517 if let Some(file) = self.target_file(cx) {
11518 if let Some(path) = file.path().to_str() {
11519 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11520 }
11521 }
11522 }
11523
11524 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11525 let permalink_task = self.get_permalink_to_line(cx);
11526 let workspace = self.workspace();
11527
11528 cx.spawn(|_, mut cx| async move {
11529 match permalink_task.await {
11530 Ok(permalink) => {
11531 cx.update(|cx| {
11532 cx.open_url(permalink.as_ref());
11533 })
11534 .ok();
11535 }
11536 Err(err) => {
11537 let message = format!("Failed to open permalink: {err}");
11538
11539 Err::<(), anyhow::Error>(err).log_err();
11540
11541 if let Some(workspace) = workspace {
11542 workspace
11543 .update(&mut cx, |workspace, cx| {
11544 struct OpenPermalinkToLine;
11545
11546 workspace.show_toast(
11547 Toast::new(
11548 NotificationId::unique::<OpenPermalinkToLine>(),
11549 message,
11550 ),
11551 cx,
11552 )
11553 })
11554 .ok();
11555 }
11556 }
11557 }
11558 })
11559 .detach();
11560 }
11561
11562 pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11563 self.insert_uuid(UuidVersion::V4, cx);
11564 }
11565
11566 pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11567 self.insert_uuid(UuidVersion::V7, cx);
11568 }
11569
11570 fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11571 self.transact(cx, |this, cx| {
11572 let edits = this
11573 .selections
11574 .all::<Point>(cx)
11575 .into_iter()
11576 .map(|selection| {
11577 let uuid = match version {
11578 UuidVersion::V4 => uuid::Uuid::new_v4(),
11579 UuidVersion::V7 => uuid::Uuid::now_v7(),
11580 };
11581
11582 (selection.range(), uuid.to_string())
11583 });
11584 this.edit(edits, cx);
11585 this.refresh_inline_completion(true, false, cx);
11586 });
11587 }
11588
11589 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11590 /// last highlight added will be used.
11591 ///
11592 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11593 pub fn highlight_rows<T: 'static>(
11594 &mut self,
11595 range: Range<Anchor>,
11596 color: Hsla,
11597 should_autoscroll: bool,
11598 cx: &mut ViewContext<Self>,
11599 ) {
11600 let snapshot = self.buffer().read(cx).snapshot(cx);
11601 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11602 let ix = row_highlights.binary_search_by(|highlight| {
11603 Ordering::Equal
11604 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11605 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11606 });
11607
11608 if let Err(mut ix) = ix {
11609 let index = post_inc(&mut self.highlight_order);
11610
11611 // If this range intersects with the preceding highlight, then merge it with
11612 // the preceding highlight. Otherwise insert a new highlight.
11613 let mut merged = false;
11614 if ix > 0 {
11615 let prev_highlight = &mut row_highlights[ix - 1];
11616 if prev_highlight
11617 .range
11618 .end
11619 .cmp(&range.start, &snapshot)
11620 .is_ge()
11621 {
11622 ix -= 1;
11623 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11624 prev_highlight.range.end = range.end;
11625 }
11626 merged = true;
11627 prev_highlight.index = index;
11628 prev_highlight.color = color;
11629 prev_highlight.should_autoscroll = should_autoscroll;
11630 }
11631 }
11632
11633 if !merged {
11634 row_highlights.insert(
11635 ix,
11636 RowHighlight {
11637 range: range.clone(),
11638 index,
11639 color,
11640 should_autoscroll,
11641 },
11642 );
11643 }
11644
11645 // If any of the following highlights intersect with this one, merge them.
11646 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11647 let highlight = &row_highlights[ix];
11648 if next_highlight
11649 .range
11650 .start
11651 .cmp(&highlight.range.end, &snapshot)
11652 .is_le()
11653 {
11654 if next_highlight
11655 .range
11656 .end
11657 .cmp(&highlight.range.end, &snapshot)
11658 .is_gt()
11659 {
11660 row_highlights[ix].range.end = next_highlight.range.end;
11661 }
11662 row_highlights.remove(ix + 1);
11663 } else {
11664 break;
11665 }
11666 }
11667 }
11668 }
11669
11670 /// Remove any highlighted row ranges of the given type that intersect the
11671 /// given ranges.
11672 pub fn remove_highlighted_rows<T: 'static>(
11673 &mut self,
11674 ranges_to_remove: Vec<Range<Anchor>>,
11675 cx: &mut ViewContext<Self>,
11676 ) {
11677 let snapshot = self.buffer().read(cx).snapshot(cx);
11678 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11679 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11680 row_highlights.retain(|highlight| {
11681 while let Some(range_to_remove) = ranges_to_remove.peek() {
11682 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11683 Ordering::Less | Ordering::Equal => {
11684 ranges_to_remove.next();
11685 }
11686 Ordering::Greater => {
11687 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11688 Ordering::Less | Ordering::Equal => {
11689 return false;
11690 }
11691 Ordering::Greater => break,
11692 }
11693 }
11694 }
11695 }
11696
11697 true
11698 })
11699 }
11700
11701 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11702 pub fn clear_row_highlights<T: 'static>(&mut self) {
11703 self.highlighted_rows.remove(&TypeId::of::<T>());
11704 }
11705
11706 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11707 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11708 self.highlighted_rows
11709 .get(&TypeId::of::<T>())
11710 .map_or(&[] as &[_], |vec| vec.as_slice())
11711 .iter()
11712 .map(|highlight| (highlight.range.clone(), highlight.color))
11713 }
11714
11715 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11716 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11717 /// Allows to ignore certain kinds of highlights.
11718 pub fn highlighted_display_rows(
11719 &mut self,
11720 cx: &mut WindowContext,
11721 ) -> BTreeMap<DisplayRow, Hsla> {
11722 let snapshot = self.snapshot(cx);
11723 let mut used_highlight_orders = HashMap::default();
11724 self.highlighted_rows
11725 .iter()
11726 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11727 .fold(
11728 BTreeMap::<DisplayRow, Hsla>::new(),
11729 |mut unique_rows, highlight| {
11730 let start = highlight.range.start.to_display_point(&snapshot);
11731 let end = highlight.range.end.to_display_point(&snapshot);
11732 let start_row = start.row().0;
11733 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11734 && end.column() == 0
11735 {
11736 end.row().0.saturating_sub(1)
11737 } else {
11738 end.row().0
11739 };
11740 for row in start_row..=end_row {
11741 let used_index =
11742 used_highlight_orders.entry(row).or_insert(highlight.index);
11743 if highlight.index >= *used_index {
11744 *used_index = highlight.index;
11745 unique_rows.insert(DisplayRow(row), highlight.color);
11746 }
11747 }
11748 unique_rows
11749 },
11750 )
11751 }
11752
11753 pub fn highlighted_display_row_for_autoscroll(
11754 &self,
11755 snapshot: &DisplaySnapshot,
11756 ) -> Option<DisplayRow> {
11757 self.highlighted_rows
11758 .values()
11759 .flat_map(|highlighted_rows| highlighted_rows.iter())
11760 .filter_map(|highlight| {
11761 if highlight.should_autoscroll {
11762 Some(highlight.range.start.to_display_point(snapshot).row())
11763 } else {
11764 None
11765 }
11766 })
11767 .min()
11768 }
11769
11770 pub fn set_search_within_ranges(
11771 &mut self,
11772 ranges: &[Range<Anchor>],
11773 cx: &mut ViewContext<Self>,
11774 ) {
11775 self.highlight_background::<SearchWithinRange>(
11776 ranges,
11777 |colors| colors.editor_document_highlight_read_background,
11778 cx,
11779 )
11780 }
11781
11782 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11783 self.breadcrumb_header = Some(new_header);
11784 }
11785
11786 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11787 self.clear_background_highlights::<SearchWithinRange>(cx);
11788 }
11789
11790 pub fn highlight_background<T: 'static>(
11791 &mut self,
11792 ranges: &[Range<Anchor>],
11793 color_fetcher: fn(&ThemeColors) -> Hsla,
11794 cx: &mut ViewContext<Self>,
11795 ) {
11796 self.background_highlights
11797 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11798 self.scrollbar_marker_state.dirty = true;
11799 cx.notify();
11800 }
11801
11802 pub fn clear_background_highlights<T: 'static>(
11803 &mut self,
11804 cx: &mut ViewContext<Self>,
11805 ) -> Option<BackgroundHighlight> {
11806 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11807 if !text_highlights.1.is_empty() {
11808 self.scrollbar_marker_state.dirty = true;
11809 cx.notify();
11810 }
11811 Some(text_highlights)
11812 }
11813
11814 pub fn highlight_gutter<T: 'static>(
11815 &mut self,
11816 ranges: &[Range<Anchor>],
11817 color_fetcher: fn(&AppContext) -> Hsla,
11818 cx: &mut ViewContext<Self>,
11819 ) {
11820 self.gutter_highlights
11821 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11822 cx.notify();
11823 }
11824
11825 pub fn clear_gutter_highlights<T: 'static>(
11826 &mut self,
11827 cx: &mut ViewContext<Self>,
11828 ) -> Option<GutterHighlight> {
11829 cx.notify();
11830 self.gutter_highlights.remove(&TypeId::of::<T>())
11831 }
11832
11833 #[cfg(feature = "test-support")]
11834 pub fn all_text_background_highlights(
11835 &mut self,
11836 cx: &mut ViewContext<Self>,
11837 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11838 let snapshot = self.snapshot(cx);
11839 let buffer = &snapshot.buffer_snapshot;
11840 let start = buffer.anchor_before(0);
11841 let end = buffer.anchor_after(buffer.len());
11842 let theme = cx.theme().colors();
11843 self.background_highlights_in_range(start..end, &snapshot, theme)
11844 }
11845
11846 #[cfg(feature = "test-support")]
11847 pub fn search_background_highlights(
11848 &mut self,
11849 cx: &mut ViewContext<Self>,
11850 ) -> Vec<Range<Point>> {
11851 let snapshot = self.buffer().read(cx).snapshot(cx);
11852
11853 let highlights = self
11854 .background_highlights
11855 .get(&TypeId::of::<items::BufferSearchHighlights>());
11856
11857 if let Some((_color, ranges)) = highlights {
11858 ranges
11859 .iter()
11860 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11861 .collect_vec()
11862 } else {
11863 vec![]
11864 }
11865 }
11866
11867 fn document_highlights_for_position<'a>(
11868 &'a self,
11869 position: Anchor,
11870 buffer: &'a MultiBufferSnapshot,
11871 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11872 let read_highlights = self
11873 .background_highlights
11874 .get(&TypeId::of::<DocumentHighlightRead>())
11875 .map(|h| &h.1);
11876 let write_highlights = self
11877 .background_highlights
11878 .get(&TypeId::of::<DocumentHighlightWrite>())
11879 .map(|h| &h.1);
11880 let left_position = position.bias_left(buffer);
11881 let right_position = position.bias_right(buffer);
11882 read_highlights
11883 .into_iter()
11884 .chain(write_highlights)
11885 .flat_map(move |ranges| {
11886 let start_ix = match ranges.binary_search_by(|probe| {
11887 let cmp = probe.end.cmp(&left_position, buffer);
11888 if cmp.is_ge() {
11889 Ordering::Greater
11890 } else {
11891 Ordering::Less
11892 }
11893 }) {
11894 Ok(i) | Err(i) => i,
11895 };
11896
11897 ranges[start_ix..]
11898 .iter()
11899 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11900 })
11901 }
11902
11903 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11904 self.background_highlights
11905 .get(&TypeId::of::<T>())
11906 .map_or(false, |(_, highlights)| !highlights.is_empty())
11907 }
11908
11909 pub fn background_highlights_in_range(
11910 &self,
11911 search_range: Range<Anchor>,
11912 display_snapshot: &DisplaySnapshot,
11913 theme: &ThemeColors,
11914 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11915 let mut results = Vec::new();
11916 for (color_fetcher, ranges) in self.background_highlights.values() {
11917 let color = color_fetcher(theme);
11918 let start_ix = match ranges.binary_search_by(|probe| {
11919 let cmp = probe
11920 .end
11921 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11922 if cmp.is_gt() {
11923 Ordering::Greater
11924 } else {
11925 Ordering::Less
11926 }
11927 }) {
11928 Ok(i) | Err(i) => i,
11929 };
11930 for range in &ranges[start_ix..] {
11931 if range
11932 .start
11933 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11934 .is_ge()
11935 {
11936 break;
11937 }
11938
11939 let start = range.start.to_display_point(display_snapshot);
11940 let end = range.end.to_display_point(display_snapshot);
11941 results.push((start..end, color))
11942 }
11943 }
11944 results
11945 }
11946
11947 pub fn background_highlight_row_ranges<T: 'static>(
11948 &self,
11949 search_range: Range<Anchor>,
11950 display_snapshot: &DisplaySnapshot,
11951 count: usize,
11952 ) -> Vec<RangeInclusive<DisplayPoint>> {
11953 let mut results = Vec::new();
11954 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11955 return vec![];
11956 };
11957
11958 let start_ix = match ranges.binary_search_by(|probe| {
11959 let cmp = probe
11960 .end
11961 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11962 if cmp.is_gt() {
11963 Ordering::Greater
11964 } else {
11965 Ordering::Less
11966 }
11967 }) {
11968 Ok(i) | Err(i) => i,
11969 };
11970 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11971 if let (Some(start_display), Some(end_display)) = (start, end) {
11972 results.push(
11973 start_display.to_display_point(display_snapshot)
11974 ..=end_display.to_display_point(display_snapshot),
11975 );
11976 }
11977 };
11978 let mut start_row: Option<Point> = None;
11979 let mut end_row: Option<Point> = None;
11980 if ranges.len() > count {
11981 return Vec::new();
11982 }
11983 for range in &ranges[start_ix..] {
11984 if range
11985 .start
11986 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11987 .is_ge()
11988 {
11989 break;
11990 }
11991 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11992 if let Some(current_row) = &end_row {
11993 if end.row == current_row.row {
11994 continue;
11995 }
11996 }
11997 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11998 if start_row.is_none() {
11999 assert_eq!(end_row, None);
12000 start_row = Some(start);
12001 end_row = Some(end);
12002 continue;
12003 }
12004 if let Some(current_end) = end_row.as_mut() {
12005 if start.row > current_end.row + 1 {
12006 push_region(start_row, end_row);
12007 start_row = Some(start);
12008 end_row = Some(end);
12009 } else {
12010 // Merge two hunks.
12011 *current_end = end;
12012 }
12013 } else {
12014 unreachable!();
12015 }
12016 }
12017 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12018 push_region(start_row, end_row);
12019 results
12020 }
12021
12022 pub fn gutter_highlights_in_range(
12023 &self,
12024 search_range: Range<Anchor>,
12025 display_snapshot: &DisplaySnapshot,
12026 cx: &AppContext,
12027 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12028 let mut results = Vec::new();
12029 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12030 let color = color_fetcher(cx);
12031 let start_ix = match ranges.binary_search_by(|probe| {
12032 let cmp = probe
12033 .end
12034 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12035 if cmp.is_gt() {
12036 Ordering::Greater
12037 } else {
12038 Ordering::Less
12039 }
12040 }) {
12041 Ok(i) | Err(i) => i,
12042 };
12043 for range in &ranges[start_ix..] {
12044 if range
12045 .start
12046 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12047 .is_ge()
12048 {
12049 break;
12050 }
12051
12052 let start = range.start.to_display_point(display_snapshot);
12053 let end = range.end.to_display_point(display_snapshot);
12054 results.push((start..end, color))
12055 }
12056 }
12057 results
12058 }
12059
12060 /// Get the text ranges corresponding to the redaction query
12061 pub fn redacted_ranges(
12062 &self,
12063 search_range: Range<Anchor>,
12064 display_snapshot: &DisplaySnapshot,
12065 cx: &WindowContext,
12066 ) -> Vec<Range<DisplayPoint>> {
12067 display_snapshot
12068 .buffer_snapshot
12069 .redacted_ranges(search_range, |file| {
12070 if let Some(file) = file {
12071 file.is_private()
12072 && EditorSettings::get(
12073 Some(SettingsLocation {
12074 worktree_id: file.worktree_id(cx),
12075 path: file.path().as_ref(),
12076 }),
12077 cx,
12078 )
12079 .redact_private_values
12080 } else {
12081 false
12082 }
12083 })
12084 .map(|range| {
12085 range.start.to_display_point(display_snapshot)
12086 ..range.end.to_display_point(display_snapshot)
12087 })
12088 .collect()
12089 }
12090
12091 pub fn highlight_text<T: 'static>(
12092 &mut self,
12093 ranges: Vec<Range<Anchor>>,
12094 style: HighlightStyle,
12095 cx: &mut ViewContext<Self>,
12096 ) {
12097 self.display_map.update(cx, |map, _| {
12098 map.highlight_text(TypeId::of::<T>(), ranges, style)
12099 });
12100 cx.notify();
12101 }
12102
12103 pub(crate) fn highlight_inlays<T: 'static>(
12104 &mut self,
12105 highlights: Vec<InlayHighlight>,
12106 style: HighlightStyle,
12107 cx: &mut ViewContext<Self>,
12108 ) {
12109 self.display_map.update(cx, |map, _| {
12110 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12111 });
12112 cx.notify();
12113 }
12114
12115 pub fn text_highlights<'a, T: 'static>(
12116 &'a self,
12117 cx: &'a AppContext,
12118 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12119 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12120 }
12121
12122 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12123 let cleared = self
12124 .display_map
12125 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12126 if cleared {
12127 cx.notify();
12128 }
12129 }
12130
12131 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12132 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12133 && self.focus_handle.is_focused(cx)
12134 }
12135
12136 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12137 self.show_cursor_when_unfocused = is_enabled;
12138 cx.notify();
12139 }
12140
12141 pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12142 self.project
12143 .as_ref()
12144 .map(|project| project.read(cx).lsp_store())
12145 }
12146
12147 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12148 cx.notify();
12149 }
12150
12151 fn on_buffer_event(
12152 &mut self,
12153 multibuffer: Model<MultiBuffer>,
12154 event: &multi_buffer::Event,
12155 cx: &mut ViewContext<Self>,
12156 ) {
12157 match event {
12158 multi_buffer::Event::Edited {
12159 singleton_buffer_edited,
12160 edited_buffer: buffer_edited,
12161 } => {
12162 self.scrollbar_marker_state.dirty = true;
12163 self.active_indent_guides_state.dirty = true;
12164 self.refresh_active_diagnostics(cx);
12165 self.refresh_code_actions(cx);
12166 if self.has_active_inline_completion() {
12167 self.update_visible_inline_completion(cx);
12168 }
12169 if let Some(buffer) = buffer_edited {
12170 let buffer_id = buffer.read(cx).remote_id();
12171 if !self.registered_buffers.contains_key(&buffer_id) {
12172 if let Some(lsp_store) = self.lsp_store(cx) {
12173 lsp_store.update(cx, |lsp_store, cx| {
12174 self.registered_buffers.insert(
12175 buffer_id,
12176 lsp_store.register_buffer_with_language_servers(&buffer, cx),
12177 );
12178 })
12179 }
12180 }
12181 }
12182 cx.emit(EditorEvent::BufferEdited);
12183 cx.emit(SearchEvent::MatchesInvalidated);
12184 if *singleton_buffer_edited {
12185 if let Some(project) = &self.project {
12186 let project = project.read(cx);
12187 #[allow(clippy::mutable_key_type)]
12188 let languages_affected = multibuffer
12189 .read(cx)
12190 .all_buffers()
12191 .into_iter()
12192 .filter_map(|buffer| {
12193 let buffer = buffer.read(cx);
12194 let language = buffer.language()?;
12195 if project.is_local()
12196 && project
12197 .language_servers_for_local_buffer(buffer, cx)
12198 .count()
12199 == 0
12200 {
12201 None
12202 } else {
12203 Some(language)
12204 }
12205 })
12206 .cloned()
12207 .collect::<HashSet<_>>();
12208 if !languages_affected.is_empty() {
12209 self.refresh_inlay_hints(
12210 InlayHintRefreshReason::BufferEdited(languages_affected),
12211 cx,
12212 );
12213 }
12214 }
12215 }
12216
12217 let Some(project) = &self.project else { return };
12218 let (telemetry, is_via_ssh) = {
12219 let project = project.read(cx);
12220 let telemetry = project.client().telemetry().clone();
12221 let is_via_ssh = project.is_via_ssh();
12222 (telemetry, is_via_ssh)
12223 };
12224 refresh_linked_ranges(self, cx);
12225 telemetry.log_edit_event("editor", is_via_ssh);
12226 }
12227 multi_buffer::Event::ExcerptsAdded {
12228 buffer,
12229 predecessor,
12230 excerpts,
12231 } => {
12232 self.tasks_update_task = Some(self.refresh_runnables(cx));
12233 let buffer_id = buffer.read(cx).remote_id();
12234 if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12235 if let Some(project) = &self.project {
12236 get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12237 }
12238 }
12239 cx.emit(EditorEvent::ExcerptsAdded {
12240 buffer: buffer.clone(),
12241 predecessor: *predecessor,
12242 excerpts: excerpts.clone(),
12243 });
12244 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12245 }
12246 multi_buffer::Event::ExcerptsRemoved { ids } => {
12247 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12248 let buffer = self.buffer.read(cx);
12249 self.registered_buffers
12250 .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12251 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12252 }
12253 multi_buffer::Event::ExcerptsEdited { ids } => {
12254 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12255 }
12256 multi_buffer::Event::ExcerptsExpanded { ids } => {
12257 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12258 }
12259 multi_buffer::Event::Reparsed(buffer_id) => {
12260 self.tasks_update_task = Some(self.refresh_runnables(cx));
12261
12262 cx.emit(EditorEvent::Reparsed(*buffer_id));
12263 }
12264 multi_buffer::Event::LanguageChanged(buffer_id) => {
12265 linked_editing_ranges::refresh_linked_ranges(self, cx);
12266 cx.emit(EditorEvent::Reparsed(*buffer_id));
12267 cx.notify();
12268 }
12269 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12270 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12271 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12272 cx.emit(EditorEvent::TitleChanged)
12273 }
12274 // multi_buffer::Event::DiffBaseChanged => {
12275 // self.scrollbar_marker_state.dirty = true;
12276 // cx.emit(EditorEvent::DiffBaseChanged);
12277 // cx.notify();
12278 // }
12279 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12280 multi_buffer::Event::DiagnosticsUpdated => {
12281 self.refresh_active_diagnostics(cx);
12282 self.scrollbar_marker_state.dirty = true;
12283 cx.notify();
12284 }
12285 _ => {}
12286 };
12287 }
12288
12289 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12290 cx.notify();
12291 }
12292
12293 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12294 self.tasks_update_task = Some(self.refresh_runnables(cx));
12295 self.refresh_inline_completion(true, false, cx);
12296 self.refresh_inlay_hints(
12297 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12298 self.selections.newest_anchor().head(),
12299 &self.buffer.read(cx).snapshot(cx),
12300 cx,
12301 )),
12302 cx,
12303 );
12304
12305 let old_cursor_shape = self.cursor_shape;
12306
12307 {
12308 let editor_settings = EditorSettings::get_global(cx);
12309 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12310 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12311 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12312 }
12313
12314 if old_cursor_shape != self.cursor_shape {
12315 cx.emit(EditorEvent::CursorShapeChanged);
12316 }
12317
12318 let project_settings = ProjectSettings::get_global(cx);
12319 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12320
12321 if self.mode == EditorMode::Full {
12322 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12323 if self.git_blame_inline_enabled != inline_blame_enabled {
12324 self.toggle_git_blame_inline_internal(false, cx);
12325 }
12326 }
12327
12328 cx.notify();
12329 }
12330
12331 pub fn set_searchable(&mut self, searchable: bool) {
12332 self.searchable = searchable;
12333 }
12334
12335 pub fn searchable(&self) -> bool {
12336 self.searchable
12337 }
12338
12339 fn open_proposed_changes_editor(
12340 &mut self,
12341 _: &OpenProposedChangesEditor,
12342 cx: &mut ViewContext<Self>,
12343 ) {
12344 let Some(workspace) = self.workspace() else {
12345 cx.propagate();
12346 return;
12347 };
12348
12349 let selections = self.selections.all::<usize>(cx);
12350 let buffer = self.buffer.read(cx);
12351 let mut new_selections_by_buffer = HashMap::default();
12352 for selection in selections {
12353 for (buffer, range, _) in
12354 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12355 {
12356 let mut range = range.to_point(buffer.read(cx));
12357 range.start.column = 0;
12358 range.end.column = buffer.read(cx).line_len(range.end.row);
12359 new_selections_by_buffer
12360 .entry(buffer)
12361 .or_insert(Vec::new())
12362 .push(range)
12363 }
12364 }
12365
12366 let proposed_changes_buffers = new_selections_by_buffer
12367 .into_iter()
12368 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12369 .collect::<Vec<_>>();
12370 let proposed_changes_editor = cx.new_view(|cx| {
12371 ProposedChangesEditor::new(
12372 "Proposed changes",
12373 proposed_changes_buffers,
12374 self.project.clone(),
12375 cx,
12376 )
12377 });
12378
12379 cx.window_context().defer(move |cx| {
12380 workspace.update(cx, |workspace, cx| {
12381 workspace.active_pane().update(cx, |pane, cx| {
12382 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12383 });
12384 });
12385 });
12386 }
12387
12388 pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12389 self.open_excerpts_common(None, true, cx)
12390 }
12391
12392 pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12393 self.open_excerpts_common(None, false, cx)
12394 }
12395
12396 fn open_excerpts_common(
12397 &mut self,
12398 jump_data: Option<JumpData>,
12399 split: bool,
12400 cx: &mut ViewContext<Self>,
12401 ) {
12402 let Some(workspace) = self.workspace() else {
12403 cx.propagate();
12404 return;
12405 };
12406
12407 if self.buffer.read(cx).is_singleton() {
12408 cx.propagate();
12409 return;
12410 }
12411
12412 let mut new_selections_by_buffer = HashMap::default();
12413 match &jump_data {
12414 Some(jump_data) => {
12415 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12416 if let Some(buffer) = multi_buffer_snapshot
12417 .buffer_id_for_excerpt(jump_data.excerpt_id)
12418 .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12419 {
12420 let buffer_snapshot = buffer.read(cx).snapshot();
12421 let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12422 language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12423 } else {
12424 buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12425 };
12426 let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12427 new_selections_by_buffer.insert(
12428 buffer,
12429 (
12430 vec![jump_to_offset..jump_to_offset],
12431 Some(jump_data.line_offset_from_top),
12432 ),
12433 );
12434 }
12435 }
12436 None => {
12437 let selections = self.selections.all::<usize>(cx);
12438 let buffer = self.buffer.read(cx);
12439 for selection in selections {
12440 for (mut buffer_handle, mut range, _) in
12441 buffer.range_to_buffer_ranges(selection.range(), cx)
12442 {
12443 // When editing branch buffers, jump to the corresponding location
12444 // in their base buffer.
12445 let buffer = buffer_handle.read(cx);
12446 if let Some(base_buffer) = buffer.base_buffer() {
12447 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12448 buffer_handle = base_buffer;
12449 }
12450
12451 if selection.reversed {
12452 mem::swap(&mut range.start, &mut range.end);
12453 }
12454 new_selections_by_buffer
12455 .entry(buffer_handle)
12456 .or_insert((Vec::new(), None))
12457 .0
12458 .push(range)
12459 }
12460 }
12461 }
12462 }
12463
12464 if new_selections_by_buffer.is_empty() {
12465 return;
12466 }
12467
12468 // We defer the pane interaction because we ourselves are a workspace item
12469 // and activating a new item causes the pane to call a method on us reentrantly,
12470 // which panics if we're on the stack.
12471 cx.window_context().defer(move |cx| {
12472 workspace.update(cx, |workspace, cx| {
12473 let pane = if split {
12474 workspace.adjacent_pane(cx)
12475 } else {
12476 workspace.active_pane().clone()
12477 };
12478
12479 for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12480 let editor = buffer
12481 .read(cx)
12482 .file()
12483 .is_none()
12484 .then(|| {
12485 // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
12486 // so `workspace.open_project_item` will never find them, always opening a new editor.
12487 // Instead, we try to activate the existing editor in the pane first.
12488 let (editor, pane_item_index) =
12489 pane.read(cx).items().enumerate().find_map(|(i, item)| {
12490 let editor = item.downcast::<Editor>()?;
12491 let singleton_buffer =
12492 editor.read(cx).buffer().read(cx).as_singleton()?;
12493 if singleton_buffer == buffer {
12494 Some((editor, i))
12495 } else {
12496 None
12497 }
12498 })?;
12499 pane.update(cx, |pane, cx| {
12500 pane.activate_item(pane_item_index, true, true, cx)
12501 });
12502 Some(editor)
12503 })
12504 .flatten()
12505 .unwrap_or_else(|| {
12506 workspace.open_project_item::<Self>(
12507 pane.clone(),
12508 buffer,
12509 true,
12510 true,
12511 cx,
12512 )
12513 });
12514
12515 editor.update(cx, |editor, cx| {
12516 let autoscroll = match scroll_offset {
12517 Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12518 None => Autoscroll::newest(),
12519 };
12520 let nav_history = editor.nav_history.take();
12521 editor.change_selections(Some(autoscroll), cx, |s| {
12522 s.select_ranges(ranges);
12523 });
12524 editor.nav_history = nav_history;
12525 });
12526 }
12527 })
12528 });
12529 }
12530
12531 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12532 let snapshot = self.buffer.read(cx).read(cx);
12533 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12534 Some(
12535 ranges
12536 .iter()
12537 .map(move |range| {
12538 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12539 })
12540 .collect(),
12541 )
12542 }
12543
12544 fn selection_replacement_ranges(
12545 &self,
12546 range: Range<OffsetUtf16>,
12547 cx: &mut AppContext,
12548 ) -> Vec<Range<OffsetUtf16>> {
12549 let selections = self.selections.all::<OffsetUtf16>(cx);
12550 let newest_selection = selections
12551 .iter()
12552 .max_by_key(|selection| selection.id)
12553 .unwrap();
12554 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12555 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12556 let snapshot = self.buffer.read(cx).read(cx);
12557 selections
12558 .into_iter()
12559 .map(|mut selection| {
12560 selection.start.0 =
12561 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12562 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12563 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12564 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12565 })
12566 .collect()
12567 }
12568
12569 fn report_editor_event(
12570 &self,
12571 event_type: &'static str,
12572 file_extension: Option<String>,
12573 cx: &AppContext,
12574 ) {
12575 if cfg!(any(test, feature = "test-support")) {
12576 return;
12577 }
12578
12579 let Some(project) = &self.project else { return };
12580
12581 // If None, we are in a file without an extension
12582 let file = self
12583 .buffer
12584 .read(cx)
12585 .as_singleton()
12586 .and_then(|b| b.read(cx).file());
12587 let file_extension = file_extension.or(file
12588 .as_ref()
12589 .and_then(|file| Path::new(file.file_name(cx)).extension())
12590 .and_then(|e| e.to_str())
12591 .map(|a| a.to_string()));
12592
12593 let vim_mode = cx
12594 .global::<SettingsStore>()
12595 .raw_user_settings()
12596 .get("vim_mode")
12597 == Some(&serde_json::Value::Bool(true));
12598
12599 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12600 == language::language_settings::InlineCompletionProvider::Copilot;
12601 let copilot_enabled_for_language = self
12602 .buffer
12603 .read(cx)
12604 .settings_at(0, cx)
12605 .show_inline_completions;
12606
12607 let project = project.read(cx);
12608 telemetry::event!(
12609 event_type,
12610 file_extension,
12611 vim_mode,
12612 copilot_enabled,
12613 copilot_enabled_for_language,
12614 is_via_ssh = project.is_via_ssh(),
12615 );
12616 }
12617
12618 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12619 /// with each line being an array of {text, highlight} objects.
12620 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12621 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12622 return;
12623 };
12624
12625 #[derive(Serialize)]
12626 struct Chunk<'a> {
12627 text: String,
12628 highlight: Option<&'a str>,
12629 }
12630
12631 let snapshot = buffer.read(cx).snapshot();
12632 let range = self
12633 .selected_text_range(false, cx)
12634 .and_then(|selection| {
12635 if selection.range.is_empty() {
12636 None
12637 } else {
12638 Some(selection.range)
12639 }
12640 })
12641 .unwrap_or_else(|| 0..snapshot.len());
12642
12643 let chunks = snapshot.chunks(range, true);
12644 let mut lines = Vec::new();
12645 let mut line: VecDeque<Chunk> = VecDeque::new();
12646
12647 let Some(style) = self.style.as_ref() else {
12648 return;
12649 };
12650
12651 for chunk in chunks {
12652 let highlight = chunk
12653 .syntax_highlight_id
12654 .and_then(|id| id.name(&style.syntax));
12655 let mut chunk_lines = chunk.text.split('\n').peekable();
12656 while let Some(text) = chunk_lines.next() {
12657 let mut merged_with_last_token = false;
12658 if let Some(last_token) = line.back_mut() {
12659 if last_token.highlight == highlight {
12660 last_token.text.push_str(text);
12661 merged_with_last_token = true;
12662 }
12663 }
12664
12665 if !merged_with_last_token {
12666 line.push_back(Chunk {
12667 text: text.into(),
12668 highlight,
12669 });
12670 }
12671
12672 if chunk_lines.peek().is_some() {
12673 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12674 line.pop_front();
12675 }
12676 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12677 line.pop_back();
12678 }
12679
12680 lines.push(mem::take(&mut line));
12681 }
12682 }
12683 }
12684
12685 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12686 return;
12687 };
12688 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12689 }
12690
12691 pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12692 self.request_autoscroll(Autoscroll::newest(), cx);
12693 let position = self.selections.newest_display(cx).start;
12694 mouse_context_menu::deploy_context_menu(self, None, position, cx);
12695 }
12696
12697 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12698 &self.inlay_hint_cache
12699 }
12700
12701 pub fn replay_insert_event(
12702 &mut self,
12703 text: &str,
12704 relative_utf16_range: Option<Range<isize>>,
12705 cx: &mut ViewContext<Self>,
12706 ) {
12707 if !self.input_enabled {
12708 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12709 return;
12710 }
12711 if let Some(relative_utf16_range) = relative_utf16_range {
12712 let selections = self.selections.all::<OffsetUtf16>(cx);
12713 self.change_selections(None, cx, |s| {
12714 let new_ranges = selections.into_iter().map(|range| {
12715 let start = OffsetUtf16(
12716 range
12717 .head()
12718 .0
12719 .saturating_add_signed(relative_utf16_range.start),
12720 );
12721 let end = OffsetUtf16(
12722 range
12723 .head()
12724 .0
12725 .saturating_add_signed(relative_utf16_range.end),
12726 );
12727 start..end
12728 });
12729 s.select_ranges(new_ranges);
12730 });
12731 }
12732
12733 self.handle_input(text, cx);
12734 }
12735
12736 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12737 let Some(provider) = self.semantics_provider.as_ref() else {
12738 return false;
12739 };
12740
12741 let mut supports = false;
12742 self.buffer().read(cx).for_each_buffer(|buffer| {
12743 supports |= provider.supports_inlay_hints(buffer, cx);
12744 });
12745 supports
12746 }
12747
12748 pub fn focus(&self, cx: &mut WindowContext) {
12749 cx.focus(&self.focus_handle)
12750 }
12751
12752 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12753 self.focus_handle.is_focused(cx)
12754 }
12755
12756 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12757 cx.emit(EditorEvent::Focused);
12758
12759 if let Some(descendant) = self
12760 .last_focused_descendant
12761 .take()
12762 .and_then(|descendant| descendant.upgrade())
12763 {
12764 cx.focus(&descendant);
12765 } else {
12766 if let Some(blame) = self.blame.as_ref() {
12767 blame.update(cx, GitBlame::focus)
12768 }
12769
12770 self.blink_manager.update(cx, BlinkManager::enable);
12771 self.show_cursor_names(cx);
12772 self.buffer.update(cx, |buffer, cx| {
12773 buffer.finalize_last_transaction(cx);
12774 if self.leader_peer_id.is_none() {
12775 buffer.set_active_selections(
12776 &self.selections.disjoint_anchors(),
12777 self.selections.line_mode,
12778 self.cursor_shape,
12779 cx,
12780 );
12781 }
12782 });
12783 }
12784 }
12785
12786 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12787 cx.emit(EditorEvent::FocusedIn)
12788 }
12789
12790 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12791 if event.blurred != self.focus_handle {
12792 self.last_focused_descendant = Some(event.blurred);
12793 }
12794 }
12795
12796 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12797 self.blink_manager.update(cx, BlinkManager::disable);
12798 self.buffer
12799 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12800
12801 if let Some(blame) = self.blame.as_ref() {
12802 blame.update(cx, GitBlame::blur)
12803 }
12804 if !self.hover_state.focused(cx) {
12805 hide_hover(self, cx);
12806 }
12807
12808 self.hide_context_menu(cx);
12809 cx.emit(EditorEvent::Blurred);
12810 cx.notify();
12811 }
12812
12813 pub fn register_action<A: Action>(
12814 &mut self,
12815 listener: impl Fn(&A, &mut WindowContext) + 'static,
12816 ) -> Subscription {
12817 let id = self.next_editor_action_id.post_inc();
12818 let listener = Arc::new(listener);
12819 self.editor_actions.borrow_mut().insert(
12820 id,
12821 Box::new(move |cx| {
12822 let cx = cx.window_context();
12823 let listener = listener.clone();
12824 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12825 let action = action.downcast_ref().unwrap();
12826 if phase == DispatchPhase::Bubble {
12827 listener(action, cx)
12828 }
12829 })
12830 }),
12831 );
12832
12833 let editor_actions = self.editor_actions.clone();
12834 Subscription::new(move || {
12835 editor_actions.borrow_mut().remove(&id);
12836 })
12837 }
12838
12839 pub fn file_header_size(&self) -> u32 {
12840 FILE_HEADER_HEIGHT
12841 }
12842
12843 pub fn revert(
12844 &mut self,
12845 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12846 cx: &mut ViewContext<Self>,
12847 ) {
12848 self.buffer().update(cx, |multi_buffer, cx| {
12849 for (buffer_id, changes) in revert_changes {
12850 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12851 buffer.update(cx, |buffer, cx| {
12852 buffer.edit(
12853 changes.into_iter().map(|(range, text)| {
12854 (range, text.to_string().map(Arc::<str>::from))
12855 }),
12856 None,
12857 cx,
12858 );
12859 });
12860 }
12861 }
12862 });
12863 self.change_selections(None, cx, |selections| selections.refresh());
12864 }
12865
12866 pub fn to_pixel_point(
12867 &mut self,
12868 source: multi_buffer::Anchor,
12869 editor_snapshot: &EditorSnapshot,
12870 cx: &mut ViewContext<Self>,
12871 ) -> Option<gpui::Point<Pixels>> {
12872 let source_point = source.to_display_point(editor_snapshot);
12873 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12874 }
12875
12876 pub fn display_to_pixel_point(
12877 &self,
12878 source: DisplayPoint,
12879 editor_snapshot: &EditorSnapshot,
12880 cx: &WindowContext,
12881 ) -> Option<gpui::Point<Pixels>> {
12882 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12883 let text_layout_details = self.text_layout_details(cx);
12884 let scroll_top = text_layout_details
12885 .scroll_anchor
12886 .scroll_position(editor_snapshot)
12887 .y;
12888
12889 if source.row().as_f32() < scroll_top.floor() {
12890 return None;
12891 }
12892 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12893 let source_y = line_height * (source.row().as_f32() - scroll_top);
12894 Some(gpui::Point::new(source_x, source_y))
12895 }
12896
12897 pub fn has_active_completions_menu(&self) -> bool {
12898 self.context_menu.borrow().as_ref().map_or(false, |menu| {
12899 menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
12900 })
12901 }
12902
12903 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12904 self.addons
12905 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12906 }
12907
12908 pub fn unregister_addon<T: Addon>(&mut self) {
12909 self.addons.remove(&std::any::TypeId::of::<T>());
12910 }
12911
12912 pub fn addon<T: Addon>(&self) -> Option<&T> {
12913 let type_id = std::any::TypeId::of::<T>();
12914 self.addons
12915 .get(&type_id)
12916 .and_then(|item| item.to_any().downcast_ref::<T>())
12917 }
12918
12919 fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
12920 let text_layout_details = self.text_layout_details(cx);
12921 let style = &text_layout_details.editor_style;
12922 let font_id = cx.text_system().resolve_font(&style.text.font());
12923 let font_size = style.text.font_size.to_pixels(cx.rem_size());
12924 let line_height = style.text.line_height_in_pixels(cx.rem_size());
12925
12926 let em_width = cx
12927 .text_system()
12928 .typographic_bounds(font_id, font_size, 'm')
12929 .unwrap()
12930 .size
12931 .width;
12932
12933 gpui::Point::new(em_width, line_height)
12934 }
12935}
12936
12937fn get_unstaged_changes_for_buffers(
12938 project: &Model<Project>,
12939 buffers: impl IntoIterator<Item = Model<Buffer>>,
12940 cx: &mut ViewContext<Editor>,
12941) {
12942 let mut tasks = Vec::new();
12943 project.update(cx, |project, cx| {
12944 for buffer in buffers {
12945 tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
12946 }
12947 });
12948 cx.spawn(|this, mut cx| async move {
12949 let change_sets = futures::future::join_all(tasks).await;
12950 this.update(&mut cx, |this, cx| {
12951 for change_set in change_sets {
12952 if let Some(change_set) = change_set.log_err() {
12953 this.diff_map.add_change_set(change_set, cx);
12954 }
12955 }
12956 })
12957 .ok();
12958 })
12959 .detach();
12960}
12961
12962fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
12963 let tab_size = tab_size.get() as usize;
12964 let mut width = offset;
12965
12966 for ch in text.chars() {
12967 width += if ch == '\t' {
12968 tab_size - (width % tab_size)
12969 } else {
12970 1
12971 };
12972 }
12973
12974 width - offset
12975}
12976
12977#[cfg(test)]
12978mod tests {
12979 use super::*;
12980
12981 #[test]
12982 fn test_string_size_with_expanded_tabs() {
12983 let nz = |val| NonZeroU32::new(val).unwrap();
12984 assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
12985 assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
12986 assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
12987 assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
12988 assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
12989 assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
12990 assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
12991 assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
12992 }
12993}
12994
12995/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
12996struct WordBreakingTokenizer<'a> {
12997 input: &'a str,
12998}
12999
13000impl<'a> WordBreakingTokenizer<'a> {
13001 fn new(input: &'a str) -> Self {
13002 Self { input }
13003 }
13004}
13005
13006fn is_char_ideographic(ch: char) -> bool {
13007 use unicode_script::Script::*;
13008 use unicode_script::UnicodeScript;
13009 matches!(ch.script(), Han | Tangut | Yi)
13010}
13011
13012fn is_grapheme_ideographic(text: &str) -> bool {
13013 text.chars().any(is_char_ideographic)
13014}
13015
13016fn is_grapheme_whitespace(text: &str) -> bool {
13017 text.chars().any(|x| x.is_whitespace())
13018}
13019
13020fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13021 text.chars().next().map_or(false, |ch| {
13022 matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13023 })
13024}
13025
13026#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13027struct WordBreakToken<'a> {
13028 token: &'a str,
13029 grapheme_len: usize,
13030 is_whitespace: bool,
13031}
13032
13033impl<'a> Iterator for WordBreakingTokenizer<'a> {
13034 /// Yields a span, the count of graphemes in the token, and whether it was
13035 /// whitespace. Note that it also breaks at word boundaries.
13036 type Item = WordBreakToken<'a>;
13037
13038 fn next(&mut self) -> Option<Self::Item> {
13039 use unicode_segmentation::UnicodeSegmentation;
13040 if self.input.is_empty() {
13041 return None;
13042 }
13043
13044 let mut iter = self.input.graphemes(true).peekable();
13045 let mut offset = 0;
13046 let mut graphemes = 0;
13047 if let Some(first_grapheme) = iter.next() {
13048 let is_whitespace = is_grapheme_whitespace(first_grapheme);
13049 offset += first_grapheme.len();
13050 graphemes += 1;
13051 if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13052 if let Some(grapheme) = iter.peek().copied() {
13053 if should_stay_with_preceding_ideograph(grapheme) {
13054 offset += grapheme.len();
13055 graphemes += 1;
13056 }
13057 }
13058 } else {
13059 let mut words = self.input[offset..].split_word_bound_indices().peekable();
13060 let mut next_word_bound = words.peek().copied();
13061 if next_word_bound.map_or(false, |(i, _)| i == 0) {
13062 next_word_bound = words.next();
13063 }
13064 while let Some(grapheme) = iter.peek().copied() {
13065 if next_word_bound.map_or(false, |(i, _)| i == offset) {
13066 break;
13067 };
13068 if is_grapheme_whitespace(grapheme) != is_whitespace {
13069 break;
13070 };
13071 offset += grapheme.len();
13072 graphemes += 1;
13073 iter.next();
13074 }
13075 }
13076 let token = &self.input[..offset];
13077 self.input = &self.input[offset..];
13078 if is_whitespace {
13079 Some(WordBreakToken {
13080 token: " ",
13081 grapheme_len: 1,
13082 is_whitespace: true,
13083 })
13084 } else {
13085 Some(WordBreakToken {
13086 token,
13087 grapheme_len: graphemes,
13088 is_whitespace: false,
13089 })
13090 }
13091 } else {
13092 None
13093 }
13094 }
13095}
13096
13097#[test]
13098fn test_word_breaking_tokenizer() {
13099 let tests: &[(&str, &[(&str, usize, bool)])] = &[
13100 ("", &[]),
13101 (" ", &[(" ", 1, true)]),
13102 ("Ʒ", &[("Ʒ", 1, false)]),
13103 ("Ǽ", &[("Ǽ", 1, false)]),
13104 ("⋑", &[("⋑", 1, false)]),
13105 ("⋑⋑", &[("⋑⋑", 2, false)]),
13106 (
13107 "原理,进而",
13108 &[
13109 ("原", 1, false),
13110 ("理,", 2, false),
13111 ("进", 1, false),
13112 ("而", 1, false),
13113 ],
13114 ),
13115 (
13116 "hello world",
13117 &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13118 ),
13119 (
13120 "hello, world",
13121 &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13122 ),
13123 (
13124 " hello world",
13125 &[
13126 (" ", 1, true),
13127 ("hello", 5, false),
13128 (" ", 1, true),
13129 ("world", 5, false),
13130 ],
13131 ),
13132 (
13133 "这是什么 \n 钢笔",
13134 &[
13135 ("这", 1, false),
13136 ("是", 1, false),
13137 ("什", 1, false),
13138 ("么", 1, false),
13139 (" ", 1, true),
13140 ("钢", 1, false),
13141 ("笔", 1, false),
13142 ],
13143 ),
13144 (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13145 ];
13146
13147 for (input, result) in tests {
13148 assert_eq!(
13149 WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13150 result
13151 .iter()
13152 .copied()
13153 .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13154 token,
13155 grapheme_len,
13156 is_whitespace,
13157 })
13158 .collect::<Vec<_>>()
13159 );
13160 }
13161}
13162
13163fn wrap_with_prefix(
13164 line_prefix: String,
13165 unwrapped_text: String,
13166 wrap_column: usize,
13167 tab_size: NonZeroU32,
13168) -> String {
13169 let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13170 let mut wrapped_text = String::new();
13171 let mut current_line = line_prefix.clone();
13172
13173 let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13174 let mut current_line_len = line_prefix_len;
13175 for WordBreakToken {
13176 token,
13177 grapheme_len,
13178 is_whitespace,
13179 } in tokenizer
13180 {
13181 if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13182 wrapped_text.push_str(current_line.trim_end());
13183 wrapped_text.push('\n');
13184 current_line.truncate(line_prefix.len());
13185 current_line_len = line_prefix_len;
13186 if !is_whitespace {
13187 current_line.push_str(token);
13188 current_line_len += grapheme_len;
13189 }
13190 } else if !is_whitespace {
13191 current_line.push_str(token);
13192 current_line_len += grapheme_len;
13193 } else if current_line_len != line_prefix_len {
13194 current_line.push(' ');
13195 current_line_len += 1;
13196 }
13197 }
13198
13199 if !current_line.is_empty() {
13200 wrapped_text.push_str(¤t_line);
13201 }
13202 wrapped_text
13203}
13204
13205#[test]
13206fn test_wrap_with_prefix() {
13207 assert_eq!(
13208 wrap_with_prefix(
13209 "# ".to_string(),
13210 "abcdefg".to_string(),
13211 4,
13212 NonZeroU32::new(4).unwrap()
13213 ),
13214 "# abcdefg"
13215 );
13216 assert_eq!(
13217 wrap_with_prefix(
13218 "".to_string(),
13219 "\thello world".to_string(),
13220 8,
13221 NonZeroU32::new(4).unwrap()
13222 ),
13223 "hello\nworld"
13224 );
13225 assert_eq!(
13226 wrap_with_prefix(
13227 "// ".to_string(),
13228 "xx \nyy zz aa bb cc".to_string(),
13229 12,
13230 NonZeroU32::new(4).unwrap()
13231 ),
13232 "// xx yy zz\n// aa bb cc"
13233 );
13234 assert_eq!(
13235 wrap_with_prefix(
13236 String::new(),
13237 "这是什么 \n 钢笔".to_string(),
13238 3,
13239 NonZeroU32::new(4).unwrap()
13240 ),
13241 "这是什\n么 钢\n笔"
13242 );
13243}
13244
13245fn hunks_for_selections(
13246 snapshot: &EditorSnapshot,
13247 selections: &[Selection<Point>],
13248) -> Vec<MultiBufferDiffHunk> {
13249 hunks_for_ranges(
13250 selections.iter().map(|selection| selection.range()),
13251 snapshot,
13252 )
13253}
13254
13255pub fn hunks_for_ranges(
13256 ranges: impl Iterator<Item = Range<Point>>,
13257 snapshot: &EditorSnapshot,
13258) -> Vec<MultiBufferDiffHunk> {
13259 let mut hunks = Vec::new();
13260 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13261 HashMap::default();
13262 for query_range in ranges {
13263 let query_rows =
13264 MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13265 for hunk in snapshot.diff_map.diff_hunks_in_range(
13266 Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13267 &snapshot.buffer_snapshot,
13268 ) {
13269 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13270 // when the caret is just above or just below the deleted hunk.
13271 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13272 let related_to_selection = if allow_adjacent {
13273 hunk.row_range.overlaps(&query_rows)
13274 || hunk.row_range.start == query_rows.end
13275 || hunk.row_range.end == query_rows.start
13276 } else {
13277 hunk.row_range.overlaps(&query_rows)
13278 };
13279 if related_to_selection {
13280 if !processed_buffer_rows
13281 .entry(hunk.buffer_id)
13282 .or_default()
13283 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13284 {
13285 continue;
13286 }
13287 hunks.push(hunk);
13288 }
13289 }
13290 }
13291
13292 hunks
13293}
13294
13295pub trait CollaborationHub {
13296 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13297 fn user_participant_indices<'a>(
13298 &self,
13299 cx: &'a AppContext,
13300 ) -> &'a HashMap<u64, ParticipantIndex>;
13301 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13302}
13303
13304impl CollaborationHub for Model<Project> {
13305 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13306 self.read(cx).collaborators()
13307 }
13308
13309 fn user_participant_indices<'a>(
13310 &self,
13311 cx: &'a AppContext,
13312 ) -> &'a HashMap<u64, ParticipantIndex> {
13313 self.read(cx).user_store().read(cx).participant_indices()
13314 }
13315
13316 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13317 let this = self.read(cx);
13318 let user_ids = this.collaborators().values().map(|c| c.user_id);
13319 this.user_store().read_with(cx, |user_store, cx| {
13320 user_store.participant_names(user_ids, cx)
13321 })
13322 }
13323}
13324
13325pub trait SemanticsProvider {
13326 fn hover(
13327 &self,
13328 buffer: &Model<Buffer>,
13329 position: text::Anchor,
13330 cx: &mut AppContext,
13331 ) -> Option<Task<Vec<project::Hover>>>;
13332
13333 fn inlay_hints(
13334 &self,
13335 buffer_handle: Model<Buffer>,
13336 range: Range<text::Anchor>,
13337 cx: &mut AppContext,
13338 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13339
13340 fn resolve_inlay_hint(
13341 &self,
13342 hint: InlayHint,
13343 buffer_handle: Model<Buffer>,
13344 server_id: LanguageServerId,
13345 cx: &mut AppContext,
13346 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13347
13348 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13349
13350 fn document_highlights(
13351 &self,
13352 buffer: &Model<Buffer>,
13353 position: text::Anchor,
13354 cx: &mut AppContext,
13355 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13356
13357 fn definitions(
13358 &self,
13359 buffer: &Model<Buffer>,
13360 position: text::Anchor,
13361 kind: GotoDefinitionKind,
13362 cx: &mut AppContext,
13363 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13364
13365 fn range_for_rename(
13366 &self,
13367 buffer: &Model<Buffer>,
13368 position: text::Anchor,
13369 cx: &mut AppContext,
13370 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13371
13372 fn perform_rename(
13373 &self,
13374 buffer: &Model<Buffer>,
13375 position: text::Anchor,
13376 new_name: String,
13377 cx: &mut AppContext,
13378 ) -> Option<Task<Result<ProjectTransaction>>>;
13379}
13380
13381pub trait CompletionProvider {
13382 fn completions(
13383 &self,
13384 buffer: &Model<Buffer>,
13385 buffer_position: text::Anchor,
13386 trigger: CompletionContext,
13387 cx: &mut ViewContext<Editor>,
13388 ) -> Task<Result<Vec<Completion>>>;
13389
13390 fn resolve_completions(
13391 &self,
13392 buffer: Model<Buffer>,
13393 completion_indices: Vec<usize>,
13394 completions: Rc<RefCell<Box<[Completion]>>>,
13395 cx: &mut ViewContext<Editor>,
13396 ) -> Task<Result<bool>>;
13397
13398 fn apply_additional_edits_for_completion(
13399 &self,
13400 buffer: Model<Buffer>,
13401 completion: Completion,
13402 push_to_history: bool,
13403 cx: &mut ViewContext<Editor>,
13404 ) -> Task<Result<Option<language::Transaction>>>;
13405
13406 fn is_completion_trigger(
13407 &self,
13408 buffer: &Model<Buffer>,
13409 position: language::Anchor,
13410 text: &str,
13411 trigger_in_words: bool,
13412 cx: &mut ViewContext<Editor>,
13413 ) -> bool;
13414
13415 fn sort_completions(&self) -> bool {
13416 true
13417 }
13418}
13419
13420pub trait CodeActionProvider {
13421 fn code_actions(
13422 &self,
13423 buffer: &Model<Buffer>,
13424 range: Range<text::Anchor>,
13425 cx: &mut WindowContext,
13426 ) -> Task<Result<Vec<CodeAction>>>;
13427
13428 fn apply_code_action(
13429 &self,
13430 buffer_handle: Model<Buffer>,
13431 action: CodeAction,
13432 excerpt_id: ExcerptId,
13433 push_to_history: bool,
13434 cx: &mut WindowContext,
13435 ) -> Task<Result<ProjectTransaction>>;
13436}
13437
13438impl CodeActionProvider for Model<Project> {
13439 fn code_actions(
13440 &self,
13441 buffer: &Model<Buffer>,
13442 range: Range<text::Anchor>,
13443 cx: &mut WindowContext,
13444 ) -> Task<Result<Vec<CodeAction>>> {
13445 self.update(cx, |project, cx| {
13446 project.code_actions(buffer, range, None, cx)
13447 })
13448 }
13449
13450 fn apply_code_action(
13451 &self,
13452 buffer_handle: Model<Buffer>,
13453 action: CodeAction,
13454 _excerpt_id: ExcerptId,
13455 push_to_history: bool,
13456 cx: &mut WindowContext,
13457 ) -> Task<Result<ProjectTransaction>> {
13458 self.update(cx, |project, cx| {
13459 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13460 })
13461 }
13462}
13463
13464fn snippet_completions(
13465 project: &Project,
13466 buffer: &Model<Buffer>,
13467 buffer_position: text::Anchor,
13468 cx: &mut AppContext,
13469) -> Task<Result<Vec<Completion>>> {
13470 let language = buffer.read(cx).language_at(buffer_position);
13471 let language_name = language.as_ref().map(|language| language.lsp_id());
13472 let snippet_store = project.snippets().read(cx);
13473 let snippets = snippet_store.snippets_for(language_name, cx);
13474
13475 if snippets.is_empty() {
13476 return Task::ready(Ok(vec![]));
13477 }
13478 let snapshot = buffer.read(cx).text_snapshot();
13479 let chars: String = snapshot
13480 .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13481 .collect();
13482
13483 let scope = language.map(|language| language.default_scope());
13484 let executor = cx.background_executor().clone();
13485
13486 cx.background_executor().spawn(async move {
13487 let classifier = CharClassifier::new(scope).for_completion(true);
13488 let mut last_word = chars
13489 .chars()
13490 .take_while(|c| classifier.is_word(*c))
13491 .collect::<String>();
13492 last_word = last_word.chars().rev().collect();
13493
13494 if last_word.is_empty() {
13495 return Ok(vec![]);
13496 }
13497
13498 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13499 let to_lsp = |point: &text::Anchor| {
13500 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13501 point_to_lsp(end)
13502 };
13503 let lsp_end = to_lsp(&buffer_position);
13504
13505 let candidates = snippets
13506 .iter()
13507 .enumerate()
13508 .flat_map(|(ix, snippet)| {
13509 snippet
13510 .prefix
13511 .iter()
13512 .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13513 })
13514 .collect::<Vec<StringMatchCandidate>>();
13515
13516 let mut matches = fuzzy::match_strings(
13517 &candidates,
13518 &last_word,
13519 last_word.chars().any(|c| c.is_uppercase()),
13520 100,
13521 &Default::default(),
13522 executor,
13523 )
13524 .await;
13525
13526 // Remove all candidates where the query's start does not match the start of any word in the candidate
13527 if let Some(query_start) = last_word.chars().next() {
13528 matches.retain(|string_match| {
13529 split_words(&string_match.string).any(|word| {
13530 // Check that the first codepoint of the word as lowercase matches the first
13531 // codepoint of the query as lowercase
13532 word.chars()
13533 .flat_map(|codepoint| codepoint.to_lowercase())
13534 .zip(query_start.to_lowercase())
13535 .all(|(word_cp, query_cp)| word_cp == query_cp)
13536 })
13537 });
13538 }
13539
13540 let matched_strings = matches
13541 .into_iter()
13542 .map(|m| m.string)
13543 .collect::<HashSet<_>>();
13544
13545 let result: Vec<Completion> = snippets
13546 .into_iter()
13547 .filter_map(|snippet| {
13548 let matching_prefix = snippet
13549 .prefix
13550 .iter()
13551 .find(|prefix| matched_strings.contains(*prefix))?;
13552 let start = as_offset - last_word.len();
13553 let start = snapshot.anchor_before(start);
13554 let range = start..buffer_position;
13555 let lsp_start = to_lsp(&start);
13556 let lsp_range = lsp::Range {
13557 start: lsp_start,
13558 end: lsp_end,
13559 };
13560 Some(Completion {
13561 old_range: range,
13562 new_text: snippet.body.clone(),
13563 label: CodeLabel {
13564 text: matching_prefix.clone(),
13565 runs: vec![],
13566 filter_range: 0..matching_prefix.len(),
13567 },
13568 server_id: LanguageServerId(usize::MAX),
13569 documentation: snippet.description.clone().map(Documentation::SingleLine),
13570 lsp_completion: lsp::CompletionItem {
13571 label: snippet.prefix.first().unwrap().clone(),
13572 kind: Some(CompletionItemKind::SNIPPET),
13573 label_details: snippet.description.as_ref().map(|description| {
13574 lsp::CompletionItemLabelDetails {
13575 detail: Some(description.clone()),
13576 description: None,
13577 }
13578 }),
13579 insert_text_format: Some(InsertTextFormat::SNIPPET),
13580 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13581 lsp::InsertReplaceEdit {
13582 new_text: snippet.body.clone(),
13583 insert: lsp_range,
13584 replace: lsp_range,
13585 },
13586 )),
13587 filter_text: Some(snippet.body.clone()),
13588 sort_text: Some(char::MAX.to_string()),
13589 ..Default::default()
13590 },
13591 confirm: None,
13592 })
13593 })
13594 .collect();
13595
13596 Ok(result)
13597 })
13598}
13599
13600impl CompletionProvider for Model<Project> {
13601 fn completions(
13602 &self,
13603 buffer: &Model<Buffer>,
13604 buffer_position: text::Anchor,
13605 options: CompletionContext,
13606 cx: &mut ViewContext<Editor>,
13607 ) -> Task<Result<Vec<Completion>>> {
13608 self.update(cx, |project, cx| {
13609 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13610 let project_completions = project.completions(buffer, buffer_position, options, cx);
13611 cx.background_executor().spawn(async move {
13612 let mut completions = project_completions.await?;
13613 let snippets_completions = snippets.await?;
13614 completions.extend(snippets_completions);
13615 Ok(completions)
13616 })
13617 })
13618 }
13619
13620 fn resolve_completions(
13621 &self,
13622 buffer: Model<Buffer>,
13623 completion_indices: Vec<usize>,
13624 completions: Rc<RefCell<Box<[Completion]>>>,
13625 cx: &mut ViewContext<Editor>,
13626 ) -> Task<Result<bool>> {
13627 self.update(cx, |project, cx| {
13628 project.resolve_completions(buffer, completion_indices, completions, cx)
13629 })
13630 }
13631
13632 fn apply_additional_edits_for_completion(
13633 &self,
13634 buffer: Model<Buffer>,
13635 completion: Completion,
13636 push_to_history: bool,
13637 cx: &mut ViewContext<Editor>,
13638 ) -> Task<Result<Option<language::Transaction>>> {
13639 self.update(cx, |project, cx| {
13640 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13641 })
13642 }
13643
13644 fn is_completion_trigger(
13645 &self,
13646 buffer: &Model<Buffer>,
13647 position: language::Anchor,
13648 text: &str,
13649 trigger_in_words: bool,
13650 cx: &mut ViewContext<Editor>,
13651 ) -> bool {
13652 let mut chars = text.chars();
13653 let char = if let Some(char) = chars.next() {
13654 char
13655 } else {
13656 return false;
13657 };
13658 if chars.next().is_some() {
13659 return false;
13660 }
13661
13662 let buffer = buffer.read(cx);
13663 let snapshot = buffer.snapshot();
13664 if !snapshot.settings_at(position, cx).show_completions_on_input {
13665 return false;
13666 }
13667 let classifier = snapshot.char_classifier_at(position).for_completion(true);
13668 if trigger_in_words && classifier.is_word(char) {
13669 return true;
13670 }
13671
13672 buffer.completion_triggers().contains(text)
13673 }
13674}
13675
13676impl SemanticsProvider for Model<Project> {
13677 fn hover(
13678 &self,
13679 buffer: &Model<Buffer>,
13680 position: text::Anchor,
13681 cx: &mut AppContext,
13682 ) -> Option<Task<Vec<project::Hover>>> {
13683 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13684 }
13685
13686 fn document_highlights(
13687 &self,
13688 buffer: &Model<Buffer>,
13689 position: text::Anchor,
13690 cx: &mut AppContext,
13691 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13692 Some(self.update(cx, |project, cx| {
13693 project.document_highlights(buffer, position, cx)
13694 }))
13695 }
13696
13697 fn definitions(
13698 &self,
13699 buffer: &Model<Buffer>,
13700 position: text::Anchor,
13701 kind: GotoDefinitionKind,
13702 cx: &mut AppContext,
13703 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13704 Some(self.update(cx, |project, cx| match kind {
13705 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13706 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13707 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13708 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13709 }))
13710 }
13711
13712 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13713 // TODO: make this work for remote projects
13714 self.read(cx)
13715 .language_servers_for_local_buffer(buffer.read(cx), cx)
13716 .any(
13717 |(_, server)| match server.capabilities().inlay_hint_provider {
13718 Some(lsp::OneOf::Left(enabled)) => enabled,
13719 Some(lsp::OneOf::Right(_)) => true,
13720 None => false,
13721 },
13722 )
13723 }
13724
13725 fn inlay_hints(
13726 &self,
13727 buffer_handle: Model<Buffer>,
13728 range: Range<text::Anchor>,
13729 cx: &mut AppContext,
13730 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13731 Some(self.update(cx, |project, cx| {
13732 project.inlay_hints(buffer_handle, range, cx)
13733 }))
13734 }
13735
13736 fn resolve_inlay_hint(
13737 &self,
13738 hint: InlayHint,
13739 buffer_handle: Model<Buffer>,
13740 server_id: LanguageServerId,
13741 cx: &mut AppContext,
13742 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13743 Some(self.update(cx, |project, cx| {
13744 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13745 }))
13746 }
13747
13748 fn range_for_rename(
13749 &self,
13750 buffer: &Model<Buffer>,
13751 position: text::Anchor,
13752 cx: &mut AppContext,
13753 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13754 Some(self.update(cx, |project, cx| {
13755 project.prepare_rename(buffer.clone(), position, cx)
13756 }))
13757 }
13758
13759 fn perform_rename(
13760 &self,
13761 buffer: &Model<Buffer>,
13762 position: text::Anchor,
13763 new_name: String,
13764 cx: &mut AppContext,
13765 ) -> Option<Task<Result<ProjectTransaction>>> {
13766 Some(self.update(cx, |project, cx| {
13767 project.perform_rename(buffer.clone(), position, new_name, cx)
13768 }))
13769 }
13770}
13771
13772fn inlay_hint_settings(
13773 location: Anchor,
13774 snapshot: &MultiBufferSnapshot,
13775 cx: &mut ViewContext<'_, Editor>,
13776) -> InlayHintSettings {
13777 let file = snapshot.file_at(location);
13778 let language = snapshot.language_at(location).map(|l| l.name());
13779 language_settings(language, file, cx).inlay_hints
13780}
13781
13782fn consume_contiguous_rows(
13783 contiguous_row_selections: &mut Vec<Selection<Point>>,
13784 selection: &Selection<Point>,
13785 display_map: &DisplaySnapshot,
13786 selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13787) -> (MultiBufferRow, MultiBufferRow) {
13788 contiguous_row_selections.push(selection.clone());
13789 let start_row = MultiBufferRow(selection.start.row);
13790 let mut end_row = ending_row(selection, display_map);
13791
13792 while let Some(next_selection) = selections.peek() {
13793 if next_selection.start.row <= end_row.0 {
13794 end_row = ending_row(next_selection, display_map);
13795 contiguous_row_selections.push(selections.next().unwrap().clone());
13796 } else {
13797 break;
13798 }
13799 }
13800 (start_row, end_row)
13801}
13802
13803fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13804 if next_selection.end.column > 0 || next_selection.is_empty() {
13805 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13806 } else {
13807 MultiBufferRow(next_selection.end.row)
13808 }
13809}
13810
13811impl EditorSnapshot {
13812 pub fn remote_selections_in_range<'a>(
13813 &'a self,
13814 range: &'a Range<Anchor>,
13815 collaboration_hub: &dyn CollaborationHub,
13816 cx: &'a AppContext,
13817 ) -> impl 'a + Iterator<Item = RemoteSelection> {
13818 let participant_names = collaboration_hub.user_names(cx);
13819 let participant_indices = collaboration_hub.user_participant_indices(cx);
13820 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13821 let collaborators_by_replica_id = collaborators_by_peer_id
13822 .iter()
13823 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13824 .collect::<HashMap<_, _>>();
13825 self.buffer_snapshot
13826 .selections_in_range(range, false)
13827 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13828 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13829 let participant_index = participant_indices.get(&collaborator.user_id).copied();
13830 let user_name = participant_names.get(&collaborator.user_id).cloned();
13831 Some(RemoteSelection {
13832 replica_id,
13833 selection,
13834 cursor_shape,
13835 line_mode,
13836 participant_index,
13837 peer_id: collaborator.peer_id,
13838 user_name,
13839 })
13840 })
13841 }
13842
13843 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13844 self.display_snapshot.buffer_snapshot.language_at(position)
13845 }
13846
13847 pub fn is_focused(&self) -> bool {
13848 self.is_focused
13849 }
13850
13851 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13852 self.placeholder_text.as_ref()
13853 }
13854
13855 pub fn scroll_position(&self) -> gpui::Point<f32> {
13856 self.scroll_anchor.scroll_position(&self.display_snapshot)
13857 }
13858
13859 fn gutter_dimensions(
13860 &self,
13861 font_id: FontId,
13862 font_size: Pixels,
13863 em_width: Pixels,
13864 em_advance: Pixels,
13865 max_line_number_width: Pixels,
13866 cx: &AppContext,
13867 ) -> GutterDimensions {
13868 if !self.show_gutter {
13869 return GutterDimensions::default();
13870 }
13871 let descent = cx.text_system().descent(font_id, font_size);
13872
13873 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13874 matches!(
13875 ProjectSettings::get_global(cx).git.git_gutter,
13876 Some(GitGutterSetting::TrackedFiles)
13877 )
13878 });
13879 let gutter_settings = EditorSettings::get_global(cx).gutter;
13880 let show_line_numbers = self
13881 .show_line_numbers
13882 .unwrap_or(gutter_settings.line_numbers);
13883 let line_gutter_width = if show_line_numbers {
13884 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13885 let min_width_for_number_on_gutter = em_advance * 4.0;
13886 max_line_number_width.max(min_width_for_number_on_gutter)
13887 } else {
13888 0.0.into()
13889 };
13890
13891 let show_code_actions = self
13892 .show_code_actions
13893 .unwrap_or(gutter_settings.code_actions);
13894
13895 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13896
13897 let git_blame_entries_width =
13898 self.git_blame_gutter_max_author_length
13899 .map(|max_author_length| {
13900 // Length of the author name, but also space for the commit hash,
13901 // the spacing and the timestamp.
13902 let max_char_count = max_author_length
13903 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13904 + 7 // length of commit sha
13905 + 14 // length of max relative timestamp ("60 minutes ago")
13906 + 4; // gaps and margins
13907
13908 em_advance * max_char_count
13909 });
13910
13911 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13912 left_padding += if show_code_actions || show_runnables {
13913 em_width * 3.0
13914 } else if show_git_gutter && show_line_numbers {
13915 em_width * 2.0
13916 } else if show_git_gutter || show_line_numbers {
13917 em_width
13918 } else {
13919 px(0.)
13920 };
13921
13922 let right_padding = if gutter_settings.folds && show_line_numbers {
13923 em_width * 4.0
13924 } else if gutter_settings.folds {
13925 em_width * 3.0
13926 } else if show_line_numbers {
13927 em_width
13928 } else {
13929 px(0.)
13930 };
13931
13932 GutterDimensions {
13933 left_padding,
13934 right_padding,
13935 width: line_gutter_width + left_padding + right_padding,
13936 margin: -descent,
13937 git_blame_entries_width,
13938 }
13939 }
13940
13941 pub fn render_crease_toggle(
13942 &self,
13943 buffer_row: MultiBufferRow,
13944 row_contains_cursor: bool,
13945 editor: View<Editor>,
13946 cx: &mut WindowContext,
13947 ) -> Option<AnyElement> {
13948 let folded = self.is_line_folded(buffer_row);
13949 let mut is_foldable = false;
13950
13951 if let Some(crease) = self
13952 .crease_snapshot
13953 .query_row(buffer_row, &self.buffer_snapshot)
13954 {
13955 is_foldable = true;
13956 match crease {
13957 Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
13958 if let Some(render_toggle) = render_toggle {
13959 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13960 if folded {
13961 editor.update(cx, |editor, cx| {
13962 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13963 });
13964 } else {
13965 editor.update(cx, |editor, cx| {
13966 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13967 });
13968 }
13969 });
13970 return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
13971 }
13972 }
13973 }
13974 }
13975
13976 is_foldable |= self.starts_indent(buffer_row);
13977
13978 if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
13979 Some(
13980 Disclosure::new(("gutter_crease", buffer_row.0), !folded)
13981 .toggle_state(folded)
13982 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13983 if folded {
13984 this.unfold_at(&UnfoldAt { buffer_row }, cx);
13985 } else {
13986 this.fold_at(&FoldAt { buffer_row }, cx);
13987 }
13988 }))
13989 .into_any_element(),
13990 )
13991 } else {
13992 None
13993 }
13994 }
13995
13996 pub fn render_crease_trailer(
13997 &self,
13998 buffer_row: MultiBufferRow,
13999 cx: &mut WindowContext,
14000 ) -> Option<AnyElement> {
14001 let folded = self.is_line_folded(buffer_row);
14002 if let Crease::Inline { render_trailer, .. } = self
14003 .crease_snapshot
14004 .query_row(buffer_row, &self.buffer_snapshot)?
14005 {
14006 let render_trailer = render_trailer.as_ref()?;
14007 Some(render_trailer(buffer_row, folded, cx))
14008 } else {
14009 None
14010 }
14011 }
14012}
14013
14014impl Deref for EditorSnapshot {
14015 type Target = DisplaySnapshot;
14016
14017 fn deref(&self) -> &Self::Target {
14018 &self.display_snapshot
14019 }
14020}
14021
14022#[derive(Clone, Debug, PartialEq, Eq)]
14023pub enum EditorEvent {
14024 InputIgnored {
14025 text: Arc<str>,
14026 },
14027 InputHandled {
14028 utf16_range_to_replace: Option<Range<isize>>,
14029 text: Arc<str>,
14030 },
14031 ExcerptsAdded {
14032 buffer: Model<Buffer>,
14033 predecessor: ExcerptId,
14034 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14035 },
14036 ExcerptsRemoved {
14037 ids: Vec<ExcerptId>,
14038 },
14039 BufferFoldToggled {
14040 ids: Vec<ExcerptId>,
14041 folded: bool,
14042 },
14043 ExcerptsEdited {
14044 ids: Vec<ExcerptId>,
14045 },
14046 ExcerptsExpanded {
14047 ids: Vec<ExcerptId>,
14048 },
14049 BufferEdited,
14050 Edited {
14051 transaction_id: clock::Lamport,
14052 },
14053 Reparsed(BufferId),
14054 Focused,
14055 FocusedIn,
14056 Blurred,
14057 DirtyChanged,
14058 Saved,
14059 TitleChanged,
14060 DiffBaseChanged,
14061 SelectionsChanged {
14062 local: bool,
14063 },
14064 ScrollPositionChanged {
14065 local: bool,
14066 autoscroll: bool,
14067 },
14068 Closed,
14069 TransactionUndone {
14070 transaction_id: clock::Lamport,
14071 },
14072 TransactionBegun {
14073 transaction_id: clock::Lamport,
14074 },
14075 Reloaded,
14076 CursorShapeChanged,
14077}
14078
14079impl EventEmitter<EditorEvent> for Editor {}
14080
14081impl FocusableView for Editor {
14082 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14083 self.focus_handle.clone()
14084 }
14085}
14086
14087impl Render for Editor {
14088 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14089 let settings = ThemeSettings::get_global(cx);
14090
14091 let mut text_style = match self.mode {
14092 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14093 color: cx.theme().colors().editor_foreground,
14094 font_family: settings.ui_font.family.clone(),
14095 font_features: settings.ui_font.features.clone(),
14096 font_fallbacks: settings.ui_font.fallbacks.clone(),
14097 font_size: rems(0.875).into(),
14098 font_weight: settings.ui_font.weight,
14099 line_height: relative(settings.buffer_line_height.value()),
14100 ..Default::default()
14101 },
14102 EditorMode::Full => TextStyle {
14103 color: cx.theme().colors().editor_foreground,
14104 font_family: settings.buffer_font.family.clone(),
14105 font_features: settings.buffer_font.features.clone(),
14106 font_fallbacks: settings.buffer_font.fallbacks.clone(),
14107 font_size: settings.buffer_font_size(cx).into(),
14108 font_weight: settings.buffer_font.weight,
14109 line_height: relative(settings.buffer_line_height.value()),
14110 ..Default::default()
14111 },
14112 };
14113 if let Some(text_style_refinement) = &self.text_style_refinement {
14114 text_style.refine(text_style_refinement)
14115 }
14116
14117 let background = match self.mode {
14118 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14119 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14120 EditorMode::Full => cx.theme().colors().editor_background,
14121 };
14122
14123 EditorElement::new(
14124 cx.view(),
14125 EditorStyle {
14126 background,
14127 local_player: cx.theme().players().local(),
14128 text: text_style,
14129 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14130 syntax: cx.theme().syntax().clone(),
14131 status: cx.theme().status().clone(),
14132 inlay_hints_style: make_inlay_hints_style(cx),
14133 inline_completion_styles: make_suggestion_styles(cx),
14134 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14135 },
14136 )
14137 }
14138}
14139
14140impl ViewInputHandler for Editor {
14141 fn text_for_range(
14142 &mut self,
14143 range_utf16: Range<usize>,
14144 adjusted_range: &mut Option<Range<usize>>,
14145 cx: &mut ViewContext<Self>,
14146 ) -> Option<String> {
14147 let snapshot = self.buffer.read(cx).read(cx);
14148 let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14149 let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14150 if (start.0..end.0) != range_utf16 {
14151 adjusted_range.replace(start.0..end.0);
14152 }
14153 Some(snapshot.text_for_range(start..end).collect())
14154 }
14155
14156 fn selected_text_range(
14157 &mut self,
14158 ignore_disabled_input: bool,
14159 cx: &mut ViewContext<Self>,
14160 ) -> Option<UTF16Selection> {
14161 // Prevent the IME menu from appearing when holding down an alphabetic key
14162 // while input is disabled.
14163 if !ignore_disabled_input && !self.input_enabled {
14164 return None;
14165 }
14166
14167 let selection = self.selections.newest::<OffsetUtf16>(cx);
14168 let range = selection.range();
14169
14170 Some(UTF16Selection {
14171 range: range.start.0..range.end.0,
14172 reversed: selection.reversed,
14173 })
14174 }
14175
14176 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14177 let snapshot = self.buffer.read(cx).read(cx);
14178 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14179 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14180 }
14181
14182 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14183 self.clear_highlights::<InputComposition>(cx);
14184 self.ime_transaction.take();
14185 }
14186
14187 fn replace_text_in_range(
14188 &mut self,
14189 range_utf16: Option<Range<usize>>,
14190 text: &str,
14191 cx: &mut ViewContext<Self>,
14192 ) {
14193 if !self.input_enabled {
14194 cx.emit(EditorEvent::InputIgnored { text: text.into() });
14195 return;
14196 }
14197
14198 self.transact(cx, |this, cx| {
14199 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14200 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14201 Some(this.selection_replacement_ranges(range_utf16, cx))
14202 } else {
14203 this.marked_text_ranges(cx)
14204 };
14205
14206 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14207 let newest_selection_id = this.selections.newest_anchor().id;
14208 this.selections
14209 .all::<OffsetUtf16>(cx)
14210 .iter()
14211 .zip(ranges_to_replace.iter())
14212 .find_map(|(selection, range)| {
14213 if selection.id == newest_selection_id {
14214 Some(
14215 (range.start.0 as isize - selection.head().0 as isize)
14216 ..(range.end.0 as isize - selection.head().0 as isize),
14217 )
14218 } else {
14219 None
14220 }
14221 })
14222 });
14223
14224 cx.emit(EditorEvent::InputHandled {
14225 utf16_range_to_replace: range_to_replace,
14226 text: text.into(),
14227 });
14228
14229 if let Some(new_selected_ranges) = new_selected_ranges {
14230 this.change_selections(None, cx, |selections| {
14231 selections.select_ranges(new_selected_ranges)
14232 });
14233 this.backspace(&Default::default(), cx);
14234 }
14235
14236 this.handle_input(text, cx);
14237 });
14238
14239 if let Some(transaction) = self.ime_transaction {
14240 self.buffer.update(cx, |buffer, cx| {
14241 buffer.group_until_transaction(transaction, cx);
14242 });
14243 }
14244
14245 self.unmark_text(cx);
14246 }
14247
14248 fn replace_and_mark_text_in_range(
14249 &mut self,
14250 range_utf16: Option<Range<usize>>,
14251 text: &str,
14252 new_selected_range_utf16: Option<Range<usize>>,
14253 cx: &mut ViewContext<Self>,
14254 ) {
14255 if !self.input_enabled {
14256 return;
14257 }
14258
14259 let transaction = self.transact(cx, |this, cx| {
14260 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14261 let snapshot = this.buffer.read(cx).read(cx);
14262 if let Some(relative_range_utf16) = range_utf16.as_ref() {
14263 for marked_range in &mut marked_ranges {
14264 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14265 marked_range.start.0 += relative_range_utf16.start;
14266 marked_range.start =
14267 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14268 marked_range.end =
14269 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14270 }
14271 }
14272 Some(marked_ranges)
14273 } else if let Some(range_utf16) = range_utf16 {
14274 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14275 Some(this.selection_replacement_ranges(range_utf16, cx))
14276 } else {
14277 None
14278 };
14279
14280 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14281 let newest_selection_id = this.selections.newest_anchor().id;
14282 this.selections
14283 .all::<OffsetUtf16>(cx)
14284 .iter()
14285 .zip(ranges_to_replace.iter())
14286 .find_map(|(selection, range)| {
14287 if selection.id == newest_selection_id {
14288 Some(
14289 (range.start.0 as isize - selection.head().0 as isize)
14290 ..(range.end.0 as isize - selection.head().0 as isize),
14291 )
14292 } else {
14293 None
14294 }
14295 })
14296 });
14297
14298 cx.emit(EditorEvent::InputHandled {
14299 utf16_range_to_replace: range_to_replace,
14300 text: text.into(),
14301 });
14302
14303 if let Some(ranges) = ranges_to_replace {
14304 this.change_selections(None, cx, |s| s.select_ranges(ranges));
14305 }
14306
14307 let marked_ranges = {
14308 let snapshot = this.buffer.read(cx).read(cx);
14309 this.selections
14310 .disjoint_anchors()
14311 .iter()
14312 .map(|selection| {
14313 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14314 })
14315 .collect::<Vec<_>>()
14316 };
14317
14318 if text.is_empty() {
14319 this.unmark_text(cx);
14320 } else {
14321 this.highlight_text::<InputComposition>(
14322 marked_ranges.clone(),
14323 HighlightStyle {
14324 underline: Some(UnderlineStyle {
14325 thickness: px(1.),
14326 color: None,
14327 wavy: false,
14328 }),
14329 ..Default::default()
14330 },
14331 cx,
14332 );
14333 }
14334
14335 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14336 let use_autoclose = this.use_autoclose;
14337 let use_auto_surround = this.use_auto_surround;
14338 this.set_use_autoclose(false);
14339 this.set_use_auto_surround(false);
14340 this.handle_input(text, cx);
14341 this.set_use_autoclose(use_autoclose);
14342 this.set_use_auto_surround(use_auto_surround);
14343
14344 if let Some(new_selected_range) = new_selected_range_utf16 {
14345 let snapshot = this.buffer.read(cx).read(cx);
14346 let new_selected_ranges = marked_ranges
14347 .into_iter()
14348 .map(|marked_range| {
14349 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14350 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14351 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14352 snapshot.clip_offset_utf16(new_start, Bias::Left)
14353 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14354 })
14355 .collect::<Vec<_>>();
14356
14357 drop(snapshot);
14358 this.change_selections(None, cx, |selections| {
14359 selections.select_ranges(new_selected_ranges)
14360 });
14361 }
14362 });
14363
14364 self.ime_transaction = self.ime_transaction.or(transaction);
14365 if let Some(transaction) = self.ime_transaction {
14366 self.buffer.update(cx, |buffer, cx| {
14367 buffer.group_until_transaction(transaction, cx);
14368 });
14369 }
14370
14371 if self.text_highlights::<InputComposition>(cx).is_none() {
14372 self.ime_transaction.take();
14373 }
14374 }
14375
14376 fn bounds_for_range(
14377 &mut self,
14378 range_utf16: Range<usize>,
14379 element_bounds: gpui::Bounds<Pixels>,
14380 cx: &mut ViewContext<Self>,
14381 ) -> Option<gpui::Bounds<Pixels>> {
14382 let text_layout_details = self.text_layout_details(cx);
14383 let gpui::Point {
14384 x: em_width,
14385 y: line_height,
14386 } = self.character_size(cx);
14387
14388 let snapshot = self.snapshot(cx);
14389 let scroll_position = snapshot.scroll_position();
14390 let scroll_left = scroll_position.x * em_width;
14391
14392 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14393 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14394 + self.gutter_dimensions.width
14395 + self.gutter_dimensions.margin;
14396 let y = line_height * (start.row().as_f32() - scroll_position.y);
14397
14398 Some(Bounds {
14399 origin: element_bounds.origin + point(x, y),
14400 size: size(em_width, line_height),
14401 })
14402 }
14403}
14404
14405trait SelectionExt {
14406 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14407 fn spanned_rows(
14408 &self,
14409 include_end_if_at_line_start: bool,
14410 map: &DisplaySnapshot,
14411 ) -> Range<MultiBufferRow>;
14412}
14413
14414impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14415 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14416 let start = self
14417 .start
14418 .to_point(&map.buffer_snapshot)
14419 .to_display_point(map);
14420 let end = self
14421 .end
14422 .to_point(&map.buffer_snapshot)
14423 .to_display_point(map);
14424 if self.reversed {
14425 end..start
14426 } else {
14427 start..end
14428 }
14429 }
14430
14431 fn spanned_rows(
14432 &self,
14433 include_end_if_at_line_start: bool,
14434 map: &DisplaySnapshot,
14435 ) -> Range<MultiBufferRow> {
14436 let start = self.start.to_point(&map.buffer_snapshot);
14437 let mut end = self.end.to_point(&map.buffer_snapshot);
14438 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14439 end.row -= 1;
14440 }
14441
14442 let buffer_start = map.prev_line_boundary(start).0;
14443 let buffer_end = map.next_line_boundary(end).0;
14444 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14445 }
14446}
14447
14448impl<T: InvalidationRegion> InvalidationStack<T> {
14449 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14450 where
14451 S: Clone + ToOffset,
14452 {
14453 while let Some(region) = self.last() {
14454 let all_selections_inside_invalidation_ranges =
14455 if selections.len() == region.ranges().len() {
14456 selections
14457 .iter()
14458 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14459 .all(|(selection, invalidation_range)| {
14460 let head = selection.head().to_offset(buffer);
14461 invalidation_range.start <= head && invalidation_range.end >= head
14462 })
14463 } else {
14464 false
14465 };
14466
14467 if all_selections_inside_invalidation_ranges {
14468 break;
14469 } else {
14470 self.pop();
14471 }
14472 }
14473 }
14474}
14475
14476impl<T> Default for InvalidationStack<T> {
14477 fn default() -> Self {
14478 Self(Default::default())
14479 }
14480}
14481
14482impl<T> Deref for InvalidationStack<T> {
14483 type Target = Vec<T>;
14484
14485 fn deref(&self) -> &Self::Target {
14486 &self.0
14487 }
14488}
14489
14490impl<T> DerefMut for InvalidationStack<T> {
14491 fn deref_mut(&mut self) -> &mut Self::Target {
14492 &mut self.0
14493 }
14494}
14495
14496impl InvalidationRegion for SnippetState {
14497 fn ranges(&self) -> &[Range<Anchor>] {
14498 &self.ranges[self.active_index]
14499 }
14500}
14501
14502pub fn diagnostic_block_renderer(
14503 diagnostic: Diagnostic,
14504 max_message_rows: Option<u8>,
14505 allow_closing: bool,
14506 _is_valid: bool,
14507) -> RenderBlock {
14508 let (text_without_backticks, code_ranges) =
14509 highlight_diagnostic_message(&diagnostic, max_message_rows);
14510
14511 Arc::new(move |cx: &mut BlockContext| {
14512 let group_id: SharedString = cx.block_id.to_string().into();
14513
14514 let mut text_style = cx.text_style().clone();
14515 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14516 let theme_settings = ThemeSettings::get_global(cx);
14517 text_style.font_family = theme_settings.buffer_font.family.clone();
14518 text_style.font_style = theme_settings.buffer_font.style;
14519 text_style.font_features = theme_settings.buffer_font.features.clone();
14520 text_style.font_weight = theme_settings.buffer_font.weight;
14521
14522 let multi_line_diagnostic = diagnostic.message.contains('\n');
14523
14524 let buttons = |diagnostic: &Diagnostic| {
14525 if multi_line_diagnostic {
14526 v_flex()
14527 } else {
14528 h_flex()
14529 }
14530 .when(allow_closing, |div| {
14531 div.children(diagnostic.is_primary.then(|| {
14532 IconButton::new("close-block", IconName::XCircle)
14533 .icon_color(Color::Muted)
14534 .size(ButtonSize::Compact)
14535 .style(ButtonStyle::Transparent)
14536 .visible_on_hover(group_id.clone())
14537 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14538 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14539 }))
14540 })
14541 .child(
14542 IconButton::new("copy-block", IconName::Copy)
14543 .icon_color(Color::Muted)
14544 .size(ButtonSize::Compact)
14545 .style(ButtonStyle::Transparent)
14546 .visible_on_hover(group_id.clone())
14547 .on_click({
14548 let message = diagnostic.message.clone();
14549 move |_click, cx| {
14550 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14551 }
14552 })
14553 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14554 )
14555 };
14556
14557 let icon_size = buttons(&diagnostic)
14558 .into_any_element()
14559 .layout_as_root(AvailableSpace::min_size(), cx);
14560
14561 h_flex()
14562 .id(cx.block_id)
14563 .group(group_id.clone())
14564 .relative()
14565 .size_full()
14566 .block_mouse_down()
14567 .pl(cx.gutter_dimensions.width)
14568 .w(cx.max_width - cx.gutter_dimensions.full_width())
14569 .child(
14570 div()
14571 .flex()
14572 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14573 .flex_shrink(),
14574 )
14575 .child(buttons(&diagnostic))
14576 .child(div().flex().flex_shrink_0().child(
14577 StyledText::new(text_without_backticks.clone()).with_highlights(
14578 &text_style,
14579 code_ranges.iter().map(|range| {
14580 (
14581 range.clone(),
14582 HighlightStyle {
14583 font_weight: Some(FontWeight::BOLD),
14584 ..Default::default()
14585 },
14586 )
14587 }),
14588 ),
14589 ))
14590 .into_any_element()
14591 })
14592}
14593
14594fn inline_completion_edit_text(
14595 editor_snapshot: &EditorSnapshot,
14596 edits: &Vec<(Range<Anchor>, String)>,
14597 cx: &WindowContext,
14598) -> InlineCompletionText {
14599 let edit_start = edits
14600 .first()
14601 .unwrap()
14602 .0
14603 .start
14604 .to_display_point(editor_snapshot);
14605
14606 let mut text = String::new();
14607 let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14608 let mut highlights = Vec::new();
14609 for (old_range, new_text) in edits {
14610 let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14611 text.extend(
14612 editor_snapshot
14613 .buffer_snapshot
14614 .chunks(offset..old_offset_range.start, false)
14615 .map(|chunk| chunk.text),
14616 );
14617 offset = old_offset_range.end;
14618
14619 let start = text.len();
14620 text.push_str(new_text);
14621 let end = text.len();
14622 highlights.push((
14623 start..end,
14624 HighlightStyle {
14625 background_color: Some(cx.theme().status().created_background),
14626 ..Default::default()
14627 },
14628 ));
14629 }
14630
14631 let edit_end = edits
14632 .last()
14633 .unwrap()
14634 .0
14635 .end
14636 .to_display_point(editor_snapshot);
14637 let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14638 .to_offset(editor_snapshot, Bias::Right);
14639 text.extend(
14640 editor_snapshot
14641 .buffer_snapshot
14642 .chunks(offset..end_of_line, false)
14643 .map(|chunk| chunk.text),
14644 );
14645
14646 InlineCompletionText::Edit {
14647 text: text.into(),
14648 highlights,
14649 }
14650}
14651
14652pub fn highlight_diagnostic_message(
14653 diagnostic: &Diagnostic,
14654 mut max_message_rows: Option<u8>,
14655) -> (SharedString, Vec<Range<usize>>) {
14656 let mut text_without_backticks = String::new();
14657 let mut code_ranges = Vec::new();
14658
14659 if let Some(source) = &diagnostic.source {
14660 text_without_backticks.push_str(source);
14661 code_ranges.push(0..source.len());
14662 text_without_backticks.push_str(": ");
14663 }
14664
14665 let mut prev_offset = 0;
14666 let mut in_code_block = false;
14667 let has_row_limit = max_message_rows.is_some();
14668 let mut newline_indices = diagnostic
14669 .message
14670 .match_indices('\n')
14671 .filter(|_| has_row_limit)
14672 .map(|(ix, _)| ix)
14673 .fuse()
14674 .peekable();
14675
14676 for (quote_ix, _) in diagnostic
14677 .message
14678 .match_indices('`')
14679 .chain([(diagnostic.message.len(), "")])
14680 {
14681 let mut first_newline_ix = None;
14682 let mut last_newline_ix = None;
14683 while let Some(newline_ix) = newline_indices.peek() {
14684 if *newline_ix < quote_ix {
14685 if first_newline_ix.is_none() {
14686 first_newline_ix = Some(*newline_ix);
14687 }
14688 last_newline_ix = Some(*newline_ix);
14689
14690 if let Some(rows_left) = &mut max_message_rows {
14691 if *rows_left == 0 {
14692 break;
14693 } else {
14694 *rows_left -= 1;
14695 }
14696 }
14697 let _ = newline_indices.next();
14698 } else {
14699 break;
14700 }
14701 }
14702 let prev_len = text_without_backticks.len();
14703 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14704 text_without_backticks.push_str(new_text);
14705 if in_code_block {
14706 code_ranges.push(prev_len..text_without_backticks.len());
14707 }
14708 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14709 in_code_block = !in_code_block;
14710 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14711 text_without_backticks.push_str("...");
14712 break;
14713 }
14714 }
14715
14716 (text_without_backticks.into(), code_ranges)
14717}
14718
14719fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14720 match severity {
14721 DiagnosticSeverity::ERROR => colors.error,
14722 DiagnosticSeverity::WARNING => colors.warning,
14723 DiagnosticSeverity::INFORMATION => colors.info,
14724 DiagnosticSeverity::HINT => colors.info,
14725 _ => colors.ignored,
14726 }
14727}
14728
14729pub fn styled_runs_for_code_label<'a>(
14730 label: &'a CodeLabel,
14731 syntax_theme: &'a theme::SyntaxTheme,
14732) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14733 let fade_out = HighlightStyle {
14734 fade_out: Some(0.35),
14735 ..Default::default()
14736 };
14737
14738 let mut prev_end = label.filter_range.end;
14739 label
14740 .runs
14741 .iter()
14742 .enumerate()
14743 .flat_map(move |(ix, (range, highlight_id))| {
14744 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14745 style
14746 } else {
14747 return Default::default();
14748 };
14749 let mut muted_style = style;
14750 muted_style.highlight(fade_out);
14751
14752 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14753 if range.start >= label.filter_range.end {
14754 if range.start > prev_end {
14755 runs.push((prev_end..range.start, fade_out));
14756 }
14757 runs.push((range.clone(), muted_style));
14758 } else if range.end <= label.filter_range.end {
14759 runs.push((range.clone(), style));
14760 } else {
14761 runs.push((range.start..label.filter_range.end, style));
14762 runs.push((label.filter_range.end..range.end, muted_style));
14763 }
14764 prev_end = cmp::max(prev_end, range.end);
14765
14766 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14767 runs.push((prev_end..label.text.len(), fade_out));
14768 }
14769
14770 runs
14771 })
14772}
14773
14774pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14775 let mut prev_index = 0;
14776 let mut prev_codepoint: Option<char> = None;
14777 text.char_indices()
14778 .chain([(text.len(), '\0')])
14779 .filter_map(move |(index, codepoint)| {
14780 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14781 let is_boundary = index == text.len()
14782 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14783 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14784 if is_boundary {
14785 let chunk = &text[prev_index..index];
14786 prev_index = index;
14787 Some(chunk)
14788 } else {
14789 None
14790 }
14791 })
14792}
14793
14794pub trait RangeToAnchorExt: Sized {
14795 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14796
14797 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14798 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14799 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14800 }
14801}
14802
14803impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14804 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14805 let start_offset = self.start.to_offset(snapshot);
14806 let end_offset = self.end.to_offset(snapshot);
14807 if start_offset == end_offset {
14808 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14809 } else {
14810 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14811 }
14812 }
14813}
14814
14815pub trait RowExt {
14816 fn as_f32(&self) -> f32;
14817
14818 fn next_row(&self) -> Self;
14819
14820 fn previous_row(&self) -> Self;
14821
14822 fn minus(&self, other: Self) -> u32;
14823}
14824
14825impl RowExt for DisplayRow {
14826 fn as_f32(&self) -> f32 {
14827 self.0 as f32
14828 }
14829
14830 fn next_row(&self) -> Self {
14831 Self(self.0 + 1)
14832 }
14833
14834 fn previous_row(&self) -> Self {
14835 Self(self.0.saturating_sub(1))
14836 }
14837
14838 fn minus(&self, other: Self) -> u32 {
14839 self.0 - other.0
14840 }
14841}
14842
14843impl RowExt for MultiBufferRow {
14844 fn as_f32(&self) -> f32 {
14845 self.0 as f32
14846 }
14847
14848 fn next_row(&self) -> Self {
14849 Self(self.0 + 1)
14850 }
14851
14852 fn previous_row(&self) -> Self {
14853 Self(self.0.saturating_sub(1))
14854 }
14855
14856 fn minus(&self, other: Self) -> u32 {
14857 self.0 - other.0
14858 }
14859}
14860
14861trait RowRangeExt {
14862 type Row;
14863
14864 fn len(&self) -> usize;
14865
14866 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14867}
14868
14869impl RowRangeExt for Range<MultiBufferRow> {
14870 type Row = MultiBufferRow;
14871
14872 fn len(&self) -> usize {
14873 (self.end.0 - self.start.0) as usize
14874 }
14875
14876 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14877 (self.start.0..self.end.0).map(MultiBufferRow)
14878 }
14879}
14880
14881impl RowRangeExt for Range<DisplayRow> {
14882 type Row = DisplayRow;
14883
14884 fn len(&self) -> usize {
14885 (self.end.0 - self.start.0) as usize
14886 }
14887
14888 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14889 (self.start.0..self.end.0).map(DisplayRow)
14890 }
14891}
14892
14893fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14894 if hunk.diff_base_byte_range.is_empty() {
14895 DiffHunkStatus::Added
14896 } else if hunk.row_range.is_empty() {
14897 DiffHunkStatus::Removed
14898 } else {
14899 DiffHunkStatus::Modified
14900 }
14901}
14902
14903/// If select range has more than one line, we
14904/// just point the cursor to range.start.
14905fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14906 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14907 range
14908 } else {
14909 range.start..range.start
14910 }
14911}
14912
14913pub struct KillRing(ClipboardItem);
14914impl Global for KillRing {}
14915
14916const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);